text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import i18next from "i18next";
import RequestErrorEvent from "terriajs-cesium/Source/Core/RequestErrorEvent";
import Resource from "terriajs-cesium/Source/Core/Resource";
import TileProviderError from "terriajs-cesium/Source/Core/TileProviderError";
import ImageryProvider from "terriajs-cesium/Source/Scene/ImageryProvider";
import WebMapServiceImageryProvider from "terriajs-cesium/Source/Scene/WebMapServiceImageryProvider";
import MappableMixin, { MapItem } from "../../lib/ModelMixins/MappableMixin";
import TileErrorHandlerMixin from "../../lib/ModelMixins/TileErrorHandlerMixin";
import CommonStrata from "../../lib/Models/Definition/CommonStrata";
import CreateModel from "../../lib/Models/Definition/CreateModel";
import Terria from "../../lib/Models/Terria";
import CatalogMemberTraits from "../../lib/Traits/TraitsClasses/CatalogMemberTraits";
import MappableTraits from "../../lib/Traits/TraitsClasses/MappableTraits";
import mixTraits from "../../lib/Traits/mixTraits";
import RasterLayerTraits from "../../lib/Traits/TraitsClasses/RasterLayerTraits";
import UrlTraits from "../../lib/Traits/TraitsClasses/UrlTraits";
class TestCatalogItem extends TileErrorHandlerMixin(
MappableMixin(
CreateModel(
mixTraits(
UrlTraits,
RasterLayerTraits,
MappableTraits,
CatalogMemberTraits
)
)
)
) {
constructor(
name: string,
terria: Terria,
readonly imageryProvider: ImageryProvider
) {
super(name, terria);
this.tileRetryOptions = {
...this.tileRetryOptions,
retries: 3,
minTimeout: 0,
maxTimeout: 0,
randomize: false
};
}
protected forceLoadMapItems(): Promise<void> {
return Promise.resolve();
}
get mapItems(): MapItem[] {
return [
{
imageryProvider: this.imageryProvider,
show: true,
alpha: 1,
clippingRectangle: undefined
}
];
}
}
describe("TileErrorHandlerMixin", function() {
let item: TestCatalogItem;
let imageryProvider: ImageryProvider;
const newError = (statusCode: number | undefined, timesRetried = 0) => {
const httpError = (new RequestErrorEvent(statusCode) as any) as Error;
return new TileProviderError(
imageryProvider,
"Something broke",
42,
42,
42,
timesRetried,
httpError
);
};
// A convenience function to call tile load error while returning a promise
// that waits for its completion.
function onTileLoadError(item: TestCatalogItem, error: TileProviderError) {
item.onTileLoadError(error);
return new Promise((resolve, reject) => {
const retry: { then?: any; otherwise: any } = error.retry as any;
if (retry && retry.then) {
retry.then(resolve).otherwise(reject);
} else {
resolve();
}
});
}
beforeEach(function() {
imageryProvider = new WebMapServiceImageryProvider({
url: "/foo",
layers: "0"
});
item = new TestCatalogItem("test", new Terria(), imageryProvider);
item.setTrait(CommonStrata.user, "url", "/foo");
});
it("gives up silently if the failed tile is outside the extent of the item", async function() {
item.setTrait(CommonStrata.user, "rectangle", {
west: 106.9,
east: 120.9,
north: 4.1,
south: 4.3
});
try {
await onTileLoadError(item, newError(400));
} catch {}
expect(item.tileFailures).toBe(0);
});
describe("when statusCode is between 400 and 499", function() {
it("gives up silently if statusCode is 403 and treat403AsError is false", async function() {
try {
item.tileErrorHandlingOptions.setTrait(
CommonStrata.user,
"treat403AsError",
false
);
await onTileLoadError(item, newError(403));
} catch {}
expect(item.tileFailures).toBe(0);
});
it("gives up silently if statusCode is 404 and treat404AsError is false", async function() {
try {
item.tileErrorHandlingOptions.setTrait(
CommonStrata.user,
"treat404AsError",
false
);
await onTileLoadError(item, newError(404));
} catch {}
expect(item.tileFailures).toBe(0);
});
it("fails otherwise", async function() {
item.tileErrorHandlingOptions.setTrait(
CommonStrata.user,
"treat403AsError",
true
);
item.tileErrorHandlingOptions.setTrait(
CommonStrata.user,
"treat404AsError",
true
);
try {
await Promise.all([
onTileLoadError(item, newError(403, 0)),
onTileLoadError(item, newError(404, 1)),
onTileLoadError(item, newError(randomIntBetween(400, 499), 2))
]);
} catch {}
expect(item.tileFailures).toBe(3);
});
});
describe("when statusCode is between 500 and 599", function() {
it("retries fetching the tile using xhr", async function() {
try {
const error = newError(randomIntBetween(500, 599));
spyOn(Resource, "fetchImage").and.returnValue(
Promise.reject(error.error)
);
await onTileLoadError(item, error);
} catch (e) {}
expect(Resource.fetchImage).toHaveBeenCalled();
});
});
describe("when statusCode is undefined", function() {
let raiseEvent: jasmine.Spy;
beforeEach(function() {
raiseEvent = spyOn(item.terria, "raiseErrorToUser");
item.tileErrorHandlingOptions.setTrait(
CommonStrata.user,
"thresholdBeforeDisablingItem",
0
);
});
it("gives up silently if ignoreUnknownTileErrors is true", async function() {
item.tileErrorHandlingOptions.setTrait(
CommonStrata.user,
"ignoreUnknownTileErrors",
true
);
try {
await onTileLoadError(item, newError(undefined));
} catch {}
expect(item.tileFailures).toBe(0);
expect(raiseEvent.calls.count()).toBe(0);
});
it("fails with bad image error if the error defines a target element", async function() {
try {
const tileProviderError = newError(undefined);
// @ts-ignore
tileProviderError.error = { ...tileProviderError.error, target: {} };
await onTileLoadError(item, tileProviderError);
} catch {}
expect(item.tileFailures).toBe(1);
expect(raiseEvent.calls.count()).toBe(1);
expect(raiseEvent.calls.argsFor(0)[0]?.message).toContain(
i18next.t("models.imageryLayer.tileErrorMessageII")
);
});
it("otherwise, it fails with unknown error", async function() {
try {
await onTileLoadError(item, newError(undefined));
} catch {}
expect(item.tileFailures).toBe(1);
expect(raiseEvent.calls.count()).toBe(1);
expect(raiseEvent.calls.argsFor(0)[0]?.message).toContain(
i18next.t("models.imageryLayer.unknownTileErrorMessage")
);
});
});
describe("when performing xhr retries", function() {
it("it fails after retrying a maximum of specified number of times", async function() {
try {
const error = newError(randomIntBetween(500, 599));
spyOn(Resource, "fetchImage").and.returnValue(
Promise.reject(error.error)
);
await onTileLoadError(item, error);
} catch {}
expect(Resource.fetchImage).toHaveBeenCalledTimes(
item.tileRetryOptions.retries || 0
);
expect(item.tileFailures).toBe(1);
});
it("tells the map to reload the tile again if an xhr attempt succeeds", async function() {
spyOn(Resource, "fetchImage").and.returnValue(Promise.resolve());
await onTileLoadError(item, newError(randomIntBetween(500, 599)));
expect(item.tileFailures).toBe(0);
});
it("fails if the xhr succeeds but the map fails to load the tile for more than 5 times", async function() {
try {
spyOn(Resource, "fetchImage").and.returnValue(Promise.resolve());
await onTileLoadError(item, newError(randomIntBetween(500, 599), 0));
await onTileLoadError(item, newError(randomIntBetween(500, 599), 1));
await onTileLoadError(item, newError(randomIntBetween(500, 599), 2));
await onTileLoadError(item, newError(randomIntBetween(500, 599), 3));
await onTileLoadError(item, newError(randomIntBetween(500, 599), 4));
await onTileLoadError(item, newError(randomIntBetween(500, 599), 5));
} catch {}
expect(item.tileFailures).toEqual(1);
});
it("gives up silently if the item is hidden", async function() {
try {
const error = newError(randomIntBetween(500, 599));
spyOn(Resource, "fetchImage").and.returnValue(
Promise.reject(error.error)
);
const result = onTileLoadError(item, error);
item.setTrait(CommonStrata.user, "show", false);
await result;
} catch {}
expect(item.tileFailures).toEqual(0);
});
});
describe("when a tile fails more than the threshold number of times", function() {
beforeEach(function() {
item.tileErrorHandlingOptions.setTrait(
CommonStrata.user,
"thresholdBeforeDisablingItem",
1
);
});
it("reports the last error to the user", async function() {
spyOn(item.terria, "raiseErrorToUser");
try {
await onTileLoadError(item, newError(undefined));
} catch {}
try {
await onTileLoadError(item, newError(undefined, 1));
} catch {}
expect(item.tileFailures).toBe(2);
expect(item.terria.raiseErrorToUser).toHaveBeenCalled();
});
it("disables the catalog item", async function() {
expect(item.show).toBe(true);
try {
await onTileLoadError(item, newError(undefined));
} catch {}
try {
await onTileLoadError(item, newError(undefined, 1));
} catch {}
expect(item.show).toBe(false);
});
});
it("resets tileFailures to 0 when there is an intervening success", async function() {
const error = newError(undefined);
expect(item.tileFailures).toBe(0);
try {
await onTileLoadError(item, error);
} catch {}
expect(item.tileFailures).toBe(1);
try {
error.timesRetried = 1;
await onTileLoadError(item, error);
} catch {}
expect(item.tileFailures).toBe(2);
try {
error.timesRetried = 0;
await onTileLoadError(item, error);
} catch {}
expect(item.tileFailures).toBe(1);
});
it("calls `handleTileError` if the item defines it", async function() {
item.handleTileError = promise => promise;
spyOn(item, "handleTileError");
try {
await onTileLoadError(item, newError(400));
} catch {}
expect(item.handleTileError).toHaveBeenCalledTimes(1);
});
});
function randomIntBetween(first: number, last: number) {
return Math.floor(first + Math.random() * (last - first));
} | the_stack |
import {
createStore,
createEvent,
createDomain,
allSettled,
combine,
fork,
hydrate,
serialize,
sample,
createEffect,
attach,
} from 'effector'
it('serialize stores to object of sid as keys', () => {
const $a = createStore('value', {sid: 'a'})
const $b = createStore([], {sid: 'b'})
const $c = createStore(null as null | number, {sid: 'c'})
const $d = createStore(false, {sid: 'd'})
const scope = fork({
values: [
[$a, 'value2'],
[$b, []],
[$c, 0],
[$d, true],
],
})
expect(serialize(scope)).toEqual({
a: 'value2',
b: [],
c: 0,
d: true,
})
})
it('serialize stores with ignore parameter', () => {
const $a = createStore('value', {sid: 'a'})
const $b = createStore([], {sid: 'b'})
const $c = createStore(null as null | number, {sid: 'c'})
const $d = createStore(false, {sid: 'd'})
const scope = fork({
values: [
[$a, 'value2'],
[$b, []],
[$c, 0],
[$d, true],
],
})
expect(serialize(scope, {ignore: [$b, $d]})).toEqual({
a: 'value2',
c: 0,
})
})
test('serialize: ignore', async () => {
const inc = createEvent()
const $a = createStore(0, {sid: 'a', serialize: 'ignore'})
const $b = createStore(0, {sid: 'b'})
$a.on(inc, x => x + 1)
$b.on(inc, x => x + 1)
const scope = fork()
await allSettled(inc, {scope})
expect(serialize(scope)).toEqual({b: 1})
})
it('serialize stores in nested domain', () => {
const app = createDomain()
const first = app.createDomain()
const second = app.createDomain()
const third = second.createDomain()
const $a = first.createStore('value', {sid: 'a'})
const $b = second.createStore([], {sid: 'b'})
const $c = third.createStore(null as null | number, {sid: 'c'})
const $d = app.createStore(false, {sid: 'd'})
const scope = fork(app, {
values: [
[$a, 'value2'],
[$b, []],
[$c, 0],
[$d, true],
],
})
expect(serialize(scope, {ignore: [$d, $a]})).toEqual({
b: [],
c: 0,
})
})
describe('onlyChanges: true', () => {
it('avoid serializing combined stores when they are not changed', async () => {
const newMessage = createEvent()
const messages = createStore(0, {sid: 'messages'}).on(
newMessage,
x => x + 1,
)
const stats = combine({messages})
const scope = fork()
expect(serialize(scope)).toEqual({})
await allSettled(newMessage, {scope})
expect(serialize(scope)).toEqual({messages: 1})
})
it('skip unchanged objects', async () => {
const newMessage = createEvent()
const messages = createStore(0, {sid: 'messages'}).on(
newMessage,
x => x + 1,
)
const scope = fork()
expect(serialize(scope)).toEqual({})
await allSettled(newMessage, {scope})
expect(serialize(scope)).toEqual({messages: 1})
})
it('keep store in serialization when it returns to default state', async () => {
const newMessage = createEvent()
const resetMessages = createEvent()
const messages = createStore(0, {sid: 'messages'})
.on(newMessage, x => x + 1)
.reset(resetMessages)
const scope = fork()
await allSettled(newMessage, {scope})
await allSettled(resetMessages, {scope})
expect(serialize(scope)).toEqual({messages: 0})
})
it('keep store in serialization when it filled with fork values', async () => {
const newMessage = createEvent()
const resetMessages = createEvent()
const messages = createStore(0, {sid: 'messages'})
.on(newMessage, x => x + 1)
.reset(resetMessages)
const scope = fork({
values: [[messages, 1]],
})
expect(serialize(scope)).toEqual({messages: 1})
await allSettled(resetMessages, {scope})
expect(serialize(scope)).toEqual({messages: 0})
})
it('keep store in serialization when it filled with hydrate values', async () => {
const app = createDomain()
const newMessage = app.createEvent()
const resetMessages = app.createEvent()
const messages = app
.createStore(0, {sid: 'messages'})
.on(newMessage, x => x + 1)
.reset(resetMessages)
const scope = fork(app)
hydrate(scope, {
values: [[messages, 0]],
})
expect(serialize(scope)).toEqual({messages: 0})
await allSettled(newMessage, {scope})
expect(serialize(scope)).toEqual({messages: 1})
})
describe('serializing combine', () => {
it('should not serialize combine in default case', async () => {
const trigger = createEvent()
const foo = createStore(0, {sid: 'foo'}).on(trigger, x => x + 1)
const bar = createStore(0, {sid: 'bar'}).on(trigger, x => x + 1)
const combined = combine({foo, bar})
const scope = fork()
await allSettled(trigger, {scope})
expect(serialize(scope)).toEqual({foo: 1, bar: 1})
})
it('should serialize combine when it updated by on', async () => {
const warn = jest.spyOn(console, 'error').mockImplementation(() => {})
const trigger = createEvent()
const foo = createStore(0, {sid: 'foo'})
const bar = createStore(0, {sid: 'bar'})
const combined = combine({foo, bar}).on(trigger, ({foo, bar}) => ({
foo: foo + 1,
bar: bar + 1,
}))
warn.mockRestore()
const sid = String(combined.sid)
const scope = fork()
await allSettled(trigger, {scope})
expect(serialize(scope)).toEqual({
[sid]: {foo: 1, bar: 1},
})
})
describe('don`t reuse values from user', () => {
test('with sample (more convenient)', async () => {
const triggerA = createEvent()
const triggerB = createEvent()
const foo = createStore(0, {sid: 'foo'})
const bar = createStore(0, {sid: 'bar'}).on(triggerB, x => x + 10)
const combined = combine({foo, bar})
sample({
clock: triggerA,
source: combined,
target: combined,
fn: ({foo, bar}) => ({
foo: foo + 1,
bar: bar + 1,
}),
})
const sid = String(combined.sid)
const scope = fork()
await allSettled(triggerA, {scope})
expect(serialize(scope)).toEqual({[sid]: {foo: 1, bar: 1}})
await allSettled(triggerB, {scope})
expect(serialize(scope)).toEqual({bar: 10, [sid]: {foo: 0, bar: 10}})
await allSettled(triggerA, {scope})
expect(serialize(scope)).toEqual({bar: 10, [sid]: {foo: 1, bar: 11}})
await allSettled(triggerB, {scope})
expect(serialize(scope)).toEqual({bar: 20, [sid]: {foo: 0, bar: 20}})
})
test('with on (less convenient)', async () => {
const warn = jest.spyOn(console, 'error').mockImplementation(() => {})
const triggerA = createEvent()
const triggerB = createEvent()
const foo = createStore(0, {sid: 'foo'})
const bar = createStore(0, {sid: 'bar'}).on(triggerB, x => x + 10)
const combined = combine({foo, bar})
combined.on(triggerA, ({foo, bar}) => ({
foo: foo + 1,
bar: bar + 1,
}))
warn.mockRestore()
const sid = String(combined.sid)
const scope = fork()
await allSettled(triggerA, {scope})
expect(serialize(scope)).toEqual({[sid]: {foo: 1, bar: 1}})
await allSettled(triggerB, {scope})
expect(serialize(scope)).toEqual({bar: 10, [sid]: {foo: 0, bar: 10}})
await allSettled(triggerA, {scope})
expect(serialize(scope)).toEqual({bar: 10, [sid]: {foo: 1, bar: 11}})
await allSettled(triggerB, {scope})
expect(serialize(scope)).toEqual({bar: 20, [sid]: {foo: 0, bar: 20}})
})
})
})
test('serialize: ignore', async () => {
const app = createDomain()
const inc = app.createEvent()
const $a = app.createStore(0, {sid: 'a', serialize: 'ignore'})
const $b = app.createStore(0, {sid: 'b'})
$a.on(inc, x => x + 1)
$b.on(inc, x => x + 1)
const scope = fork(app)
await allSettled(inc, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({b: 1})
})
})
describe('onlyChanges: false', () => {
it('avoid serializing combined stores when they are not changed', async () => {
const app = createDomain()
const newMessage = app.createEvent()
const messages = app
.createStore(0, {sid: 'messages'})
.on(newMessage, x => x + 1)
const stats = combine({messages})
const scope = fork(app)
expect(serialize(scope, {onlyChanges: false})).toEqual({messages: 0})
await allSettled(newMessage, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({messages: 1})
})
it('keep unchanged objects', async () => {
const app = createDomain()
const newMessage = app.createEvent()
const messages = app
.createStore(0, {sid: 'messages'})
.on(newMessage, x => x + 1)
const scope = fork(app)
expect(serialize(scope, {onlyChanges: false})).toEqual({messages: 0})
await allSettled(newMessage, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({messages: 1})
})
it('keep store in serialization when it returns to default state', async () => {
const app = createDomain()
const newMessage = app.createEvent()
const resetMessages = app.createEvent()
const messages = app
.createStore(0, {sid: 'messages'})
.on(newMessage, x => x + 1)
.reset(resetMessages)
const scope = fork(app)
await allSettled(newMessage, {scope})
await allSettled(resetMessages, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({messages: 0})
})
it('keep store in serialization when it filled with fork values', async () => {
const app = createDomain()
const newMessage = app.createEvent()
const resetMessages = app.createEvent()
const messages = app
.createStore(0, {sid: 'messages'})
.on(newMessage, x => x + 1)
.reset(resetMessages)
const scope = fork(app, {
values: [[messages, 1]],
})
expect(serialize(scope, {onlyChanges: false})).toEqual({messages: 1})
await allSettled(resetMessages, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({messages: 0})
})
it('keep store in serialization when it filled with hydrate values', async () => {
const app = createDomain()
const newMessage = app.createEvent()
const resetMessages = app.createEvent()
const messages = app
.createStore(0, {sid: 'messages'})
.on(newMessage, x => x + 1)
.reset(resetMessages)
const scope = fork(app)
hydrate(scope, {
values: [[messages, 0]],
})
expect(serialize(scope, {onlyChanges: false})).toEqual({messages: 0})
await allSettled(newMessage, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({messages: 1})
})
describe('serializing combine', () => {
it('should not serialize combine in default case', async () => {
const app = createDomain()
const trigger = app.createEvent()
const foo = app.createStore(0, {sid: 'foo'}).on(trigger, x => x + 1)
const bar = app.createStore(0, {sid: 'bar'}).on(trigger, x => x + 1)
const combined = combine({foo, bar})
const scope = fork(app)
await allSettled(trigger, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({foo: 1, bar: 1})
})
it('should serialize combine when it updated by on', async () => {
const warn = jest.spyOn(console, 'error').mockImplementation(() => {})
const app = createDomain()
const trigger = app.createEvent()
const foo = app.createStore(0, {sid: 'foo'})
const bar = app.createStore(0, {sid: 'bar'})
const combined = combine({foo, bar}).on(trigger, ({foo, bar}) => ({
foo: foo + 1,
bar: bar + 1,
}))
warn.mockRestore()
const sid = String(combined.sid)
const scope = fork(app)
await allSettled(trigger, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({
foo: 0,
bar: 0,
[sid]: {foo: 1, bar: 1},
})
})
describe('don`t reuse values from user', () => {
test('with sample (more convenient)', async () => {
const app = createDomain()
const triggerA = app.createEvent()
const triggerB = app.createEvent()
const foo = app.createStore(0, {sid: 'foo'})
const bar = app.createStore(0, {sid: 'bar'}).on(triggerB, x => x + 10)
const combined = combine({foo, bar})
sample({
clock: triggerA,
source: combined,
target: combined,
fn: ({foo, bar}) => ({
foo: foo + 1,
bar: bar + 1,
}),
})
const sid = String(combined.sid)
const scope = fork(app)
await allSettled(triggerA, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({
foo: 0,
bar: 0,
[sid]: {foo: 1, bar: 1},
})
await allSettled(triggerB, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({
foo: 0,
bar: 10,
[sid]: {foo: 0, bar: 10},
})
await allSettled(triggerA, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({
foo: 0,
bar: 10,
[sid]: {foo: 1, bar: 11},
})
await allSettled(triggerB, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({
foo: 0,
bar: 20,
[sid]: {foo: 0, bar: 20},
})
})
test('with on (less convenient)', async () => {
const warn = jest.spyOn(console, 'error').mockImplementation(() => {})
const app = createDomain()
const triggerA = app.createEvent()
const triggerB = app.createEvent()
const foo = app.createStore(0, {sid: 'foo'})
const bar = app.createStore(0, {sid: 'bar'}).on(triggerB, x => x + 10)
const combined = combine({foo, bar})
combined.on(triggerA, ({foo, bar}) => ({
foo: foo + 1,
bar: bar + 1,
}))
warn.mockRestore()
const sid = String(combined.sid)
const scope = fork(app)
await allSettled(triggerA, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({
foo: 0,
bar: 0,
[sid]: {foo: 1, bar: 1},
})
await allSettled(triggerB, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({
foo: 0,
bar: 10,
[sid]: {foo: 0, bar: 10},
})
await allSettled(triggerA, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({
foo: 0,
bar: 10,
[sid]: {foo: 1, bar: 11},
})
await allSettled(triggerB, {scope})
expect(serialize(scope, {onlyChanges: false})).toEqual({
foo: 0,
bar: 20,
[sid]: {foo: 0, bar: 20},
})
})
})
})
})
test('onlyChanges: false supported only in domain-based scopes', () => {
const scope = fork()
expect(() => {
serialize(scope, {onlyChanges: false})
}).toThrowErrorMatchingInlineSnapshot(`"scope should be created from domain"`)
})
describe('serialize: missing sids', () => {
const consoleError = console.error
beforeEach(() => {
console.error = jest.fn()
})
afterEach(() => {
console.error = consoleError
})
test('serialize: warns about missing sids', () => {
// forcing missing sid
// equals to situation, if user forgot to configure babel-plugin
// or did not install the sid manually
const $store = createStore('value', {sid: ''})
const scope = fork()
allSettled($store, {scope, params: 'scope value'})
const result = serialize(scope)
expect(result).toEqual({})
expect(scope.getState($store)).toEqual('scope value')
expect(console.error).toHaveBeenCalledWith(
'There is a store without sid in this scope, its value is omitted',
)
})
test('serialize: doesn not warn, if no sid is missing', () => {
const $store = createStore('value')
const scope = fork()
allSettled($store, {scope, params: 'scope value'})
const result = serialize(scope)
expect(result).toEqual({
[$store.sid as string]: 'scope value',
})
expect(scope.getState($store)).toEqual('scope value')
expect(console.error).toHaveBeenCalledTimes(0)
})
test('serialize: doesn not warn on mapped or combined stores', () => {
const $store = createStore('value')
const $mapped = $store.map(s => s)
// combined stores have sids, but not used in serialize
// this trick is needed to hide combine call from plugin
const $combine = {_: combine}._($store, $mapped, (_, m) => m)
const scope = fork()
allSettled($store, {scope, params: 'scope value'})
const result = serialize(scope)
expect($combine.sid).toEqual(null)
expect(scope.getState($store)).toEqual('scope value')
expect(scope.getState($combine)).toEqual('scope value')
expect(result).toEqual({
[$store.sid as string]: 'scope value',
})
expect(console.error).toHaveBeenCalledTimes(0)
})
test('serialize: does not warn on internal store changes', async () => {
const sleep = (p: number) => new Promise(r => setTimeout(r, p))
const sleepFx = createEffect(sleep)
const $sleep = createStore(1)
const sleepAttachedFx = attach({
source: $sleep,
effect: sleep,
})
const start = createEvent<number>()
sample({
clock: start,
target: [sleepFx, sleepAttachedFx],
})
const scope = fork()
await allSettled(start, {scope, params: 1})
const result = serialize(scope)
expect(result).toMatchObject({})
expect(console.error).toBeCalledTimes(0)
})
}) | the_stack |
import * as Immutable from "immutable";
import * as _ from "lodash";
import { Base } from "./base";
import { Index, index } from "./index";
import { Key } from "./key";
import { Time, time } from "./time";
import { TimeRange, timerange } from "./timerange";
import { ReducerFunction, ValueListMap, ValueMap } from "./types";
import util from "./util";
/**
* An Event is a mapping from a time based key to a data object represented
* by an `Immutable.Map`.
*
* The key needs to be a sub-class of the base class `Key`, which typically
* would be one of the following:
*
* * `Time` - a single timestamp
* * `TimeRange` - a timerange over which the Event took place
* * `Index` - a different representation of a TimeRange
*
* The data object needs to be an `Immutable.Map<string, any>`.
*
* To get values out of the data, use `get()`. This method takes
* what is called a field, which is a top level key of the data
* map.
*
* Fields can refer to deep data with either a path (as an array)
* or dot notation ("path.to.value").
*
* Example:
*
* ```
* const timestamp = time(new Date("2015-04-22T03:30:00Z");
* const e = event(t, Immutable.Map({ temperature: 75.2, humidity: 84 }));
* const humidity = e.get("humidity"); // 84
* ```
*
* There exists several static methods for `Event` that enable the
* ability to compare `Events`, `merge()` or `combine()` lists of `Event`s or
* check for duplicates.
*
* You can also do per-`Event` operations like `select()` out specific fields or
* `collapse()` multiple fields into one using an aggregation function.
*
* Note: Managing multiple `Event`s is typically done with a `Collection`
* which is literally a collections of `Event`s, or a `TimeSeries` which
* is an chronological set of `Event`s plus some additional meta data.
*/
export class Event<T extends Key = Time> extends Base {
/**
* Do the two supplied events contain the same data, even if they are not
* the same instance? Uses `Immutable.is()` to compare the event data and
* the key.
*/
public static is(event1: Event<Key>, event2: Event<Key>): boolean {
return (
event1.getKey().toString() === event2.getKey().toString() &&
event1.getData().equals(event2.getData())
);
}
/**
* Returns if the two supplied events are duplicates of each other.
*
* Duplicated is defined as the keys of the `Event`s being the same.
* This is the case with incoming events sometimes where a second event
* is either known to be the same (but duplicate) of the first, or
* supersedes the first.
*
* You can also pass in `false` for `ignoreValues` and get a full compare,
* including the data of the event, thus ignoring the supersede case.
*
* Example:
* ```
* const e1 = event(t, Immutable.Map({ a: 5, b: 6, c: 7 }));
* const e2 = event(t, Immutable.Map({ a: 5, b: 6, c: 7 }));
* const e3 = event(t, Immutable.Map({ a: 100, b: 6, c: 7 }));
*
* Event.isDuplicate(e1, e2) // true
* Event.isDuplicate(e1, e3) // true
* Event.isDuplicate(e1, e3, false) // false
* Event.isDuplicate(e1, e2, false) // false
* ```
*/
public static isDuplicate(
event1: Event<Key>,
event2: Event<Key>,
ignoreValues: boolean = true
): boolean {
if (ignoreValues) {
return (
event1.keyType() === event2.keyType() &&
event1.getKey().toString() === event2.getKey().toString()
);
} else {
return event1.keyType() === event2.keyType() && Event.is(event1, event2);
}
}
/**
* Merges multiple `Event`'s together into a new array of `Event`s, one
* for each key of the source events. Merging is done on the data of
* each `Event`. Values from later events in the list overwrite
* earlier values if fields conflict.
*
* Common use cases:
* * append events of different timestamps
* e.g. merge earlier events with later events
* * merge in events with one field to events with another field
* e.g. combine events with a field "in" with another list of events
* with a field "out" to get events with both "in" and "out"
* * merge in events that supersede the previous events
*
* Events in the supplied list need to be of homogeneous types
*
* See also:
* * `TimeSeries.timeSeriesListMerge()` if what you have is a
* `TimeSeries`. That uses this code but with a friendlier API.
*
* Example:
* ```
* const t = time(new Date("2015-04-22T03:30:00Z"));
* const event1 = event(t, Immutable.Map({ a: 5, b: 6 }));
* const event2 = event(t, Immutable.Map({ c: 2 }));
* const merged = Event.merge(Immutable.List([event1, event2]));
* merged.get(0).get("a"); // 5
* merged.get(0).get("b"); // 6
* merged.get(0).get("c"); // 2
*/
public static merge<K extends Key>(
events: Immutable.List<Event<K>>,
deep?: boolean
): Immutable.List<Event<K>> {
// Early exit
if (events instanceof Immutable.List && events.size === 0) {
return Immutable.List();
}
//
// Group events by event key
//
const mergeDeep = deep || false;
const eventList: Array<Event<K>> = [];
const eventMap: { [key: string]: Array<Event<K>> } = {};
const keyMap: { [key: string]: K } = {};
events.forEach(e => {
const key = e.getKey();
const k = key.toString();
if (!_.has(eventMap, k)) {
eventMap[k] = [];
keyMap[k] = e.getKey();
}
eventMap[k].push(e);
});
//
// For each key we'll build a new event of the same type as the source
// events. Here we loop through all the events for that key, then for each field
// we are considering, we get all the values and reduce them (sum, avg, etc)
// to a new data object d, which we then build a new Event from.
//
const outEvents: Array<Event<K>> = [];
_.each(eventMap, (perKeyEvents: Array<Event<K>>, key: string) => {
let reduced: Event<K> = null;
let d = null;
_.each(perKeyEvents, (e: Event<K>) => {
if (!reduced) {
reduced = e;
d = reduced.getData();
} else {
d = mergeDeep ? d.mergeDeep(e.getData()) : d.merge(e.getData());
}
reduced = reduced.setData(d);
});
outEvents.push(reduced);
});
return Immutable.List(outEvents);
}
/**
* Returns a function that will take a list of `Event`s and merge them
* together using the `fieldSpec` provided. This is used as a `reducer` for
* merging multiple `TimeSeries` together with `TimeSeries.timeSeriesListMerge()`.
*/
static merger<K extends Key>(
deep
): (events: Immutable.List<Event<K>>) => Immutable.List<Event<Key>> {
return (events: Immutable.List<Event<K>>) => Event.merge(events, deep);
}
/**
* Static function to combine multiple `Event`s together into a new array
* of events, one `Event` for each key of the source events. The list of
* `Events` should be specified as an array or `Immutable.List<Event<K>>`.
*
* Combining acts on the fields specified in the `fieldSpec` (or all
* fields) and uses the `reducer` function supplied to take the multiple
* values associated with the key and reduce them down to a single value.
*
* The return result will be an `Immutable.List<Event<K>>` of the same type K
* as the input.
*
* Example:
* ```
* const t = time("2015-04-22T03:30:00Z");
* const events = [
* event(t, Immutable.Map({ a: 5, b: 6, c: 7 })),
* event(t, Immutable.Map({ a: 2, b: 3, c: 4 })),
* event(t, Immutable.Map({ a: 1, b: 2, c: 3 }))
* ];
* const result = Event.combine(Immutable.List(events), sum());
* // result[0] is {a: 8, b: 11, c: 14 }
* ```
* See also: `TimeSeries.timeSeriesListSum()`
*/
public static combine<K extends Key>(
events: Immutable.List<Event<K>>,
reducer: ReducerFunction,
fieldSpec?: string | string[]
): Immutable.List<Event<K>> {
if (events instanceof Immutable.List && events.size === 0) {
return Immutable.List();
}
let eventTemplate;
if (events instanceof Immutable.List) {
eventTemplate = events.get(0);
} else {
eventTemplate = events[0];
}
let fieldNames: string[];
if (_.isString(fieldSpec)) {
fieldNames = [fieldSpec as string];
} else if (_.isArray(fieldSpec)) {
fieldNames = fieldSpec as string[];
}
//
// Group events by event key
//
const eventMap: { [key: string]: Array<Event<K>> } = {};
const keyMap: { [key: string]: K } = {};
events.forEach(e => {
const key = e.getKey();
const k = key.toString();
if (!_.has(eventMap, k)) {
eventMap[k] = [];
keyMap[k] = e.getKey();
}
eventMap[k].push(e);
});
//
// For each key we'll build a new event of the same type as the source
// events. Here we loop through all the events for that key, then for
// each field we are considering, we get all the values and reduce
// them (sum, avg, etc) to get a the new data for that key.
//
const outEvents: Array<Event<K>> = [];
_.each(eventMap, (perKeyEvents: Array<Event<K>>, key: string) => {
// tslint:disable-next-line
const mapEvent: { [key: string]: number[] } = {};
_.each(perKeyEvents, (perKeyEvent: Event<K>) => {
let fields = fieldNames;
if (!fields) {
const obj = perKeyEvent.getData().toJSON() as {};
fields = _.map(obj, (v, fieldName) => `${fieldName}`);
}
fields.forEach(fieldName => {
if (!mapEvent[fieldName]) {
mapEvent[fieldName] = [];
}
mapEvent[fieldName].push(perKeyEvent.getData().get(fieldName));
});
});
const data: { [key: string]: number } = {};
_.map(mapEvent, (values, fieldName) => {
data[fieldName] = reducer(values);
});
const e = new Event<K>(keyMap[key], eventTemplate.getData().merge(data));
outEvents.push(e);
});
return Immutable.List(outEvents);
}
/**
* Static method that returns a function that will take a list of `Event`'s
* and combine them together using the `fieldSpec` and reducer function provided.
* This is used as an event reducer for merging multiple `TimeSeries` together
* with `timeSeriesListReduce()`.
*/
static combiner<K extends Key>(
fieldSpec,
reducer
): (events: Immutable.List<Event<K>>) => Immutable.List<Event<Key>> {
return (events: Immutable.List<Event<K>>) => Event.combine(events, reducer, fieldSpec);
}
/**
* Static function that takes a list of `Events<T>` and makes a map from each
* field names to an array of values, one value for each Event.
*
* Example:
* ```
* const events = [
* event(t1, Immutable.Map({in: 2, out: 11 })),
* event(t2, Immutable.Map({in: 4, out: 13 })),
* event(t3, Immutable.Map({in: 6, out: 15 })),
* event(t4, Immutable.Map({in: 8, out: 17 }))
* ];
*
* const fieldMapping = Event.map(events, ["in", "out"]);
* // { in: [ 2, 4, 6, 8 ], out: [ 11, 13, 15, 18 ] }
* ```
*/
public static map<K extends Key>(
events: Immutable.List<Event<K>>,
multiFieldSpec: string | string[]
): ValueListMap;
public static map<K extends Key>(events, multiFieldSpec: any = "value") {
const result = {};
if (typeof multiFieldSpec === "string") {
const fieldSpec = multiFieldSpec;
events.forEach(e => {
if (!_.has(result, fieldSpec)) {
result[fieldSpec] = [];
}
const value = e.get(fieldSpec);
result[fieldSpec].push(value);
});
} else if (_.isArray(multiFieldSpec)) {
const fieldSpecList = multiFieldSpec as string[];
_.each(fieldSpecList, fieldSpec => {
events.forEach(e => {
if (!_.has(result, fieldSpec)) {
result[fieldSpec] = [];
}
result[fieldSpec].push(e.get(fieldSpec));
});
});
} else {
events.forEach(e => {
_.each(e.data().toJSON(), (value, key) => {
if (!_.has(result, key)) {
result[key] = [];
}
result[key].push(value);
});
});
}
return result;
}
/**
* Static function that takes a `Immutable.List` of events, a `reducer` function and a
* `fieldSpec` (field or list of fields) and returns an aggregated result in the form
* of a new Event, for each column.
*
* The reducer is of the form:
* ```
* (values: number[]) => number
* ```
*
* Example:
* ```
* const result = Event.aggregate(EVENT_LIST, avg(), ["in", "out"]);
* // result = { in: 5, out: 14.25 }
* ```
*/
public static aggregate<K extends Key>(
events: Immutable.List<Event<K>>,
reducer: ReducerFunction,
multiFieldSpec: string | string[]
): ValueMap {
function reduce(mapped: ValueListMap, f: ReducerFunction): ValueMap {
const result = {};
_.each(mapped, (valueList, key) => {
result[key] = f(valueList);
});
return result;
}
return reduce(this.map(events, multiFieldSpec), reducer);
}
/**
* Construction of an `Event` requires both a time-based key and an
* `Immutable.Map` of (`string` -> data) mappings.
*
* The time-based key should be either a `Time`, a `TimeRange` or an `Index`,
* though it would be possible to subclass `Key` with another type so long
* as it implements that abstract interface.
*
* The data portion maybe deep data. Using `Immutable.toJS()` is helpful in
* that case.
*
* You can use `new Event<T>()` to create a new `Event`, but it's easier to use
* one of the factory functions: `event()`, `timeEvent()`, `timeRangeEvent()` and
* `indexedEvent()`
*
* Example 1:
* ```
* const e = event(time(new Date(1487983075328)), Immutable.Map({ name: "bob" }));
* ```
*
* Example 2:
* ```
* // An event for a particular day with indexed key
* const e = event(index("1d-12355"), Immutable.Map({ value: 42 }));
* ```
*
* Example 3:
* ```
* // Outage event spans a timerange
* const e = event(timerange(beginTime, endTime), Immutable.Map({ ticket: "A1787383" }));
* ```
*
* Example 4:
* ```
* const e = timeEvent({
* time: 1487983075328,
* data: { a: 2, b: 3 }
* });
* ```
*/
constructor(protected key: T, protected data: Immutable.Map<string, any>) {
super();
}
/**
* Returns the key this `Event`.
*
* The result is of type T (a `Time`, `TimeRange` or `Index`), depending on
* what the `Event` was constructed with.
*/
public getKey(): T {
return this.key;
}
/**
* Returns the label of the key
*/
public keyType(): string {
return this.key.type();
}
/**
* Returns the data associated with this event in the form
* of an `Immutable.Map`. This is infact an accessor for the internal
* representation of data in this `Event`.
*/
public getData(): Immutable.Map<string, any> {
return this.data;
}
/**
* Sets new `data` associated with this event. The new `data` is supplied
* in the form of an `Immutable.Map`. A new `Event<T>` will be returned
* containing this new data, but having the same key.
*/
public setData(data: Immutable.Map<string, any>): Event<T> {
return new Event<T>(this.key, data);
}
/**
* Gets the `value` of a specific field within the `Event`.
*
* You can refer to a fields with one of the following notations:
* * (undefined) -> "value"
* * "temperature"
* * "path.to.deep.data"
* * ["path", "to", "deep", "data"].
*
* Example 1:
* ```
* const e = event(index("1d-12355"), Immutable.Map({ value: 42 }));
* e.get("value"); // 42
* ```
*
* Example 2:
* ```
* const t = time(new Date("2015-04-22T03:30:00Z"));
* const e = event(t, Immutable.fromJS({ a: 5, b: { c: 6 } }));
* e.get("b.c"); // 6
* ```
*
* Note: the default `field` is "value".
*/
public get(field: string | string[] = "value"): any {
const f = util.fieldAsArray(field);
return this.getData().getIn(f);
}
/**
* Set a new `value` on the `Event` for the given `field`, and return a new `Event`.
*
* You can refer to a `field` with one of the following notations:
* * (undefined) -> "value"
* * "temperature"
* * "path.to.deep.data"
* * ["path", "to", "deep", "data"].
*
* `value` is the new value to set on for the given `field` on the `Event`.
*
* ```
* const t = time(new Date(1487983075328));
* const initial = event(t, Immutable.Map({ name: "bob" }));
* const modified = e.set("name", "fred");
* modified.toString() // {"time": 1487983075328, "data": {"name":"fred"} }
* ```
*/
public set(field: string | string[] = "value", value: any): Event<T> {
const f = util.fieldAsArray(field);
return new Event<T>(this.getKey(), this.getData().setIn(f, value));
}
/**
* Will return false if the value for the specified `fields` in this `Event` is
* either `undefined`, `NaN` or `null` for the given field or fields. This
* serves as a determination of a "missing" value within a `TimeSeries` or
* `Collection`.
*/
public isValid(fields?: string | string[]): boolean {
let invalid = false;
const fieldList: string[] = _.isUndefined(fields) || _.isArray(fields) ? fields : [fields];
fieldList.forEach(field => {
const v = this.get(field);
invalid = _.isUndefined(v) || _.isNaN(v) || _.isNull(v);
});
return !invalid;
}
/**
* Converts the `Event` into a standard Javascript object
*/
public toJSON(): {} {
const k = this.getKey().toJSON()[this.keyType()];
return {
[this.keyType()]: k,
data: this.getData().toJSON()
};
}
/**
* Converts the `Event` to a string
*/
public toString(): string {
return JSON.stringify(this.toJSON());
}
/**
* Returns the timestamp of the `Event`.
*
* This a convenience for calling `Event.getKey()` followed by `timestamp()`.
*/
public timestamp(): Date {
return this.getKey().timestamp();
}
/**
* The begin time of the `Event`. If the key of the `Event` is a `Time` then
* the begin and end time of the `Event` will be the same as the `Event`
* timestamp.
*/
public begin(): Date {
return this.getKey().begin();
}
/**
* The end time of the `Event`. If the key of the `Event` is a `Time` then
* the begin and end time of the `Event` will be the same as the `Event`
* timestamp.
*/
public end(): Date {
return this.getKey().end();
}
public index() {
return index(this.indexAsString());
}
public indexAsString() {
return this.key.toString();
}
/**
* Returns the `TimeRange` over which this `Event` occurs. If this `Event`
* has a `Time` key then the duration of this range will be 0.
*/
public timerange() {
return new TimeRange(this.key.begin(), this.key.end());
}
/**
* Shortcut for `timerange()` followed by `toUTCString()`.
*/
public timerangeAsUTCString() {
return this.timerange().toUTCString();
}
/**
* Shortcut for `timestamp()` followed by `toUTCString()`.
*/
public timestampAsUTCString() {
return this.timestamp().toUTCString();
}
/**
* Returns an array containing the key in the first element and then the data map
* expressed as JSON as the second element. This is the method that is used by
* a `TimeSeries` to build its wireformat representation.
*/
public toPoint(columns: string[]) {
const values = [];
columns.forEach(c => {
const v = this.getData().get(c);
values.push(v === "undefined" ? null : v);
});
if (this.keyType() === "time") {
return [this.timestamp().getTime(), ...values];
} else if (this.keyType() === "index") {
return [this.indexAsString(), ...values];
} else if (this.keyType() === "timerange") {
return [
[
this.timerange()
.begin()
.getTime(),
this.timerange()
.end()
.getTime()
],
...values
];
}
}
/**
* Collapses an array of fields, specified in the `fieldSpecList`, into a single
* field named `fieldName` using the supplied reducer function. Optionally you can keep
* all existing fields by supplying the `append` argument as `true`.
*
* Example:
* ```
* const t = time(new Date("2015-04-22T03:30:00Z"));
* const e = event(t, Immutable.Map({ in: 5, out: 6, status: "ok" }));
* const result = e.collapse(["in", "out"], "total", sum(), true);
* // { "in": 5, "out": 6, "status": "ok", "total": 11 } }
* ```
*/
public collapse(
fieldSpecList: string[],
fieldName: string,
reducer: ReducerFunction,
append: boolean = false
): Event<T> {
const data = append ? this.getData().toJS() : {};
const d = fieldSpecList.map(fs => this.get(fs));
data[fieldName] = reducer(d);
return this.setData(Immutable.fromJS(data));
}
/**
* Selects specific fields of an `Event` using the `fields` array of strings
* and returns a new event with just those fields.
*
* Example:
* ```
* const t = time(new Date("2015-04-22T03:30:00Z"));
* const e = event(t, Immutable.Map({ a: 5, b: 6, c: 7 }));
* const result = e.select(["a", "b"]); // data is { a: 5, b: 6 }}
* ```
*/
public select(fields: string[]): Event<T> {
const data = {};
_.each(fields, fieldName => {
const value = this.get(fieldName);
data[fieldName] = value;
});
return this.setData(Immutable.fromJS(data));
}
}
export interface TimeEventObject {
time: number;
data: { [data: string]: any };
}
function timeEvent(arg: TimeEventObject): Event<Time>;
function timeEvent(t: Time, data: Immutable.Map<string, any>): Event<Time>;
function timeEvent(arg1: any, arg2?: any): Event<Time> {
if (arg1 instanceof Time && Immutable.Map.isMap(arg2)) {
const data = arg2 as Immutable.Map<string, any>;
return new Event<Time>(arg1, data);
} else {
const t = arg1.time as number;
const data = arg1.data as { [data: string]: any };
return new Event<Time>(time(t), Immutable.Map(data));
}
}
export interface IndexedEventObject {
index: string;
data: { [data: string]: any };
}
function indexedEvent(arg: IndexedEventObject): Event<Index>;
function indexedEvent(idx: Index, data: Immutable.Map<string, any>): Event<Index>;
function indexedEvent(arg1: any, arg2?: any): Event<Index> {
if (arg1 instanceof Index && Immutable.Map.isMap(arg2)) {
const data = arg2 as Immutable.Map<string, any>;
return new Event<Index>(arg1, data);
} else {
const i = arg1.index as number;
const data = arg1.data as { [data: string]: any };
return new Event<Index>(index(i), Immutable.Map(data));
}
}
export interface TimeRangeEventObject {
timerange: number[]; // should be length 2
data: { [data: string]: any };
}
function timeRangeEvent(arg: TimeRangeEventObject): Event<TimeRange>;
function timeRangeEvent(idx: Index, data: Immutable.Map<string, any>): Event<TimeRange>;
function timeRangeEvent(arg1: any, arg2?: any): Event<TimeRange> {
if (arg1 instanceof TimeRange && Immutable.Map.isMap(arg2)) {
const data = arg2 as Immutable.Map<string, any>;
return new Event<TimeRange>(arg1, data);
} else {
const tr = arg1.timerange as number[];
const data = arg1.data as { [data: string]: any };
return new Event<TimeRange>(timerange(tr[0], tr[1]), Immutable.Map(data));
}
}
function event<T extends Key>(key: T, data: Immutable.Map<string, any>) {
return new Event<T>(key, data);
}
export { event, timeEvent, timeRangeEvent, indexedEvent }; | the_stack |
import React, { Component } from 'react';
import Paper from '@material-ui/core/Paper';
import { withLocation, withNavigation } from '../../lib/routeUtil';
import { registerComponent } from '../../lib/vulcan-lib';
import { withUpdateCurrentUser, WithUpdateCurrentUserProps } from '../hooks/useUpdateCurrentUser';
import { withMessages } from '../common/withMessages';
import { groupTypes } from '../../lib/collections/localgroups/groupTypes';
import classNames from 'classnames'
import Divider from '@material-ui/core/Divider';
import VisibilityIcon from '@material-ui/icons/VisibilityOff';
import EmailIcon from '@material-ui/icons/Email';
import AddIcon from '@material-ui/icons/Add';
import RoomIcon from '@material-ui/icons/Room';
import StarIcon from '@material-ui/icons/Star';
import PersonPinIcon from '@material-ui/icons/PersonPin';
import Tooltip from '@material-ui/core/Tooltip';
import withDialog from '../common/withDialog'
import withUser from '../common/withUser';
import { PersonSVG, ArrowSVG, GroupIconSVG } from './Icons'
import qs from 'qs'
import * as _ from 'underscore';
import { forumTypeSetting } from '../../lib/instanceSettings';
import { userIsAdmin } from '../../lib/vulcan-users';
const availableFilters = _.map(groupTypes, t => t.shortName);
const styles = (theme: ThemeType): JssStyles => ({
root: {
width: 120,
padding: "10px 10px 5px 10px",
borderRadius: 2,
marginBottom: theme.spacing.unit,
},
filters: {
borderTopLeftRadius: 4,
borderTopRightRadius: 4,
overflow: 'hidden',
},
filter: {
padding: 8,
paddingLeft: 10,
paddingRight: 10,
display: 'inline-block',
cursor: "pointer",
'&:hover': {
backgroundColor: theme.palette.grey[200]
}
},
firstFilter: {
paddingLeft: 16
},
lastFilter: {
paddingRight: 16
},
filterChecked: {
backgroundColor: theme.palette.grey[500],
'&:hover': {
backgroundColor: theme.palette.grey[400]
}
},
checkbox: {
padding: 0,
marginRight: 5,
width: '0.7em',
height: '0.7em'
},
checkboxLabel: {
...theme.typography.body2
},
checkedLabel: {
color: theme.palette.text.tooltipText,
},
filterSection: {
display: "flex",
alignItems: "center",
padding: '8px 16px',
[theme.breakpoints.down('sm')]: {
display: 'inline-block',
flexGrow: 1,
padding: '8px 22px'
}
},
actions: {
marginBottom: 8,
[theme.breakpoints.down('sm')]: {
display: 'flex'
}
},
hideMap: {
width: 34,
padding: 5
},
buttonText: {
marginLeft: 10,
...theme.typography.body2,
[theme.breakpoints.down('sm')]: {
display: 'none'
}
},
hideText: {
marginLeft: 'auto',
fontSize: '1rem',
cursor: "pointer"
},
hideSection: {
backgroundColor: theme.palette.panelBackground.darken05,
},
buttonIcon: {
width: '1.2rem',
height: '1.2rem',
},
eaButtonIcon: {
width: '1.7rem',
height: '1.7rem',
},
actionIcon: {
width: '0.7em',
height: '0.7em',
marginLeft: theme.spacing.unit,
position: 'relative',
top: 2,
cursor: "pointer"
},
visibilityIcon: {
color: theme.palette.icon.dim2,
cursor: "pointer",
},
addIcon: {
[theme.breakpoints.down('sm')]: {
display: 'none'
}
},
checkedVisibilityIcon: {
color: theme.palette.text.normal,
},
actionContainer: {
marginLeft: 'auto',
[theme.breakpoints.down('sm')]: {
display: 'none'
}
},
divider: {
marginTop: theme.spacing.unit,
marginBottom: theme.spacing.unit
},
topDivider: {
marginTop: 0
},
subscribeSection: {
cursor: "pointer",
marginBottom: theme.spacing.unit,
[theme.breakpoints.down('sm')]: {
display: 'none'
}
},
subscribeIcon: {
marginLeft: 0,
top: 0
},
desktopFilter: {
[theme.breakpoints.down('sm')]: {
display: 'none'
}
},
mobileFilter: {
display: 'none',
[theme.breakpoints.down('sm')]: {
display: 'block'
},
},
mobileFilterActive: {
opacity: 0.3
},
bottomDivider: {
[theme.breakpoints.down('sm')]: {
display: 'none'
}
}
});
const createFallBackDialogHandler = (openDialog, dialogName, currentUser) => {
return () => openDialog({
componentName: currentUser ? dialogName : "LoginPopup",
});
}
interface ExternalProps {
setShowMap: any,
showHideMap: boolean,
toggleGroups: any,
showGroups: boolean,
toggleEvents: any,
showEvents: boolean,
toggleIndividuals: any,
showIndividuals: boolean,
}
interface CommunityMapFilterProps extends ExternalProps, WithLocationProps, WithNavigationProps, WithDialogProps, WithUserProps, WithUpdateCurrentUserProps, WithMessagesProps, WithStylesProps {
}
interface CommunityMapFilterState {
filters: any,
}
class CommunityMapFilter extends Component<CommunityMapFilterProps,CommunityMapFilterState> {
constructor(props: CommunityMapFilterProps) {
super(props);
const { query } = this.props.location;
const filters = query?.filters
if (Array.isArray(filters)) {
this.state = {filters: filters}
} else if (typeof filters === "string") {
this.state = {filters: [filters]}
} else {
this.state = {filters: []}
}
}
handleCheck = (filter) => {
const { location, history } = this.props
let newFilters: Array<any> = [];
if (Array.isArray(this.state.filters) && this.state.filters.includes(filter)) {
newFilters = _.without(this.state.filters, filter);
} else {
newFilters = [...this.state.filters, filter];
}
this.setState({filters: newFilters});
// FIXME: qs.stringify doesn't handle array parameters in the way react-router-v3
// did, which causes awkward-looking and backwards-incompatible (but not broken) URLs.
history.replace({...location.location, search: qs.stringify({filters: newFilters})})
}
handleHideMap = () => {
const { currentUser, updateCurrentUser, flash, setShowMap } = this.props
let undoAction
if (currentUser) {
void updateCurrentUser({
hideFrontpageMap: true
})
undoAction = () => {
void updateCurrentUser({hideFrontpageMap: false})
}
} else {
setShowMap(false)
undoAction = () => setShowMap(true)
}
flash({messageString: "Hid map from Frontpage", action: undoAction})
}
render() {
const { classes, openDialog, currentUser, showHideMap, toggleGroups, showGroups, toggleEvents, showEvents, toggleIndividuals, showIndividuals, history } = this.props;
const isEAForum = forumTypeSetting.get() === 'EAForum';
const GroupIcon = () => isEAForum ? <StarIcon className={classes.eaButtonIcon}/> : <GroupIconSVG className={classes.buttonIcon}/>;
const EventIcon = () => isEAForum ? <RoomIcon className={classes.eaButtonIcon}/> : <ArrowSVG className={classes.buttonIcon}/>;
const PersonIcon = () => isEAForum ? <PersonPinIcon className={classes.eaButtonIcon}/> : <PersonSVG className={classes.buttonIcon}/>;
const isAdmin = userIsAdmin(currentUser);
return <Paper>
{!isEAForum && <div className={classes.filters}>
{availableFilters.map((value, i) => {
const checked = this.state.filters.includes(value)
return <span
className={classNames(classes.filter, {[classes.filterChecked]: checked, [classes.firstFilter]: i === 0, [classes.lastFilter]: i === (availableFilters.length - 1)})}
key={value}
onClick={() => this.handleCheck(value)}
>
<span className={classNames(classes.checkboxLabel, {[classes.checkedLabel]: checked})}>
{value}
</span>
</span>
})}
</div>}
<Divider className={classNames(classes.divider, classes.topDivider)} />
<div className={classes.actions}>
<div
className={classes.filterSection}
>
<span className={classes.desktopFilter}>
<GroupIcon/>
</span>
<span className={classNames(classes.mobileFilter, {[classes.mobileFilterActive]: !showGroups})} onClick={toggleGroups}>
<GroupIcon/>
</span>
<span className={classes.buttonText}>Groups</span>
<span className={classes.actionContainer}>
{(!isEAForum || isAdmin) && <Tooltip title="Create New Group">
<AddIcon className={classNames(classes.actionIcon, classes.addIcon)} onClick={createFallBackDialogHandler(openDialog, "GroupFormDialog", currentUser)} />
</ Tooltip>}
<Tooltip title="Hide groups from map">
<VisibilityIcon
onClick={toggleGroups}
className={classNames(classes.actionIcon, classes.visibilityIcon, {[classes.checkedVisibilityIcon]: !showGroups})}
/>
</Tooltip>
</span>
</div>
<div
className={classes.filterSection}>
<span className={classes.desktopFilter}>
<EventIcon/>
</span>
<span className={classNames(classes.mobileFilter, {[classes.mobileFilterActive]: !showEvents})} onClick={toggleEvents}>
<EventIcon/>
</span>
<span className={classes.buttonText}> Events </span>
<span className={classes.actionContainer}>
{currentUser && <Tooltip title="Create New Event">
<AddIcon className={classNames(classes.actionIcon, classes.addIcon)} onClick={() => history.push({ pathname: '/newPost', search: `?eventForm=true`})}/>
</Tooltip>}
<Tooltip title="Hide events from map">
<VisibilityIcon
onClick={toggleEvents}
className={classNames(classes.actionIcon, classes.visibilityIcon, {[classes.checkedVisibilityIcon]: !showEvents})}
/>
</Tooltip>
</span>
</div>
<div
className={classes.filterSection}
>
<span className={classes.desktopFilter}>
<PersonIcon />
</span>
<span className={classNames(classes.mobileFilter, {[classes.mobileFilterActive]: !showIndividuals})} onClick={toggleIndividuals}>
<PersonIcon />
</span>
<span className={classes.buttonText}> Individuals </span>
<span className={classes.actionContainer}>
<Tooltip title="Add your location to the map">
<AddIcon className={classNames(classes.actionIcon, classes.addIcon)} onClick={createFallBackDialogHandler(openDialog, "SetPersonalMapLocationDialog", currentUser)}/>
</Tooltip>
<Tooltip title="Hide individual user locations from map">
<VisibilityIcon
onClick={toggleIndividuals}
className={classNames(classes.actionIcon, classes.visibilityIcon, {[classes.checkedVisibilityIcon]: !showIndividuals})}
/>
</Tooltip>
</span>
</div>
</div>
<Divider className={classNames(classes.divider, classes.bottomDivider)} />
<div
className={classNames(classes.filterSection, classes.subscribeSection)}
onClick={createFallBackDialogHandler(openDialog, "EventNotificationsDialog", currentUser)}
>
<EmailIcon className={classNames(classes.actionIcon, classes.subscribeIcon)} />
<span className={classes.buttonText}> Subscribe to events</span>
</div>
{showHideMap && <span>
<Tooltip title="Hide the map from the frontpage">
<div className={classNames(classes.filterSection, classes.hideSection)}>
{/* <CloseIcon className={classes.buttonIcon} /> */}
<span className={classNames(classes.buttonText, classes.hideText)} onClick={this.handleHideMap}>
Hide Map
</span>
</div>
</Tooltip>
</span>}
</Paper>
}
}
const CommunityMapFilterComponent = registerComponent<ExternalProps>('CommunityMapFilter', CommunityMapFilter, {
styles,
hocs: [
withLocation, withNavigation,
withDialog,
withUser,
withUpdateCurrentUser,
withMessages
]
});
declare global {
interface ComponentTypes {
CommunityMapFilter: typeof CommunityMapFilterComponent
}
} | the_stack |
import * as React from 'react';
import copy from './copy';
import * as util from './util';
import { ControllerImpl } from './controller';
import {vm} from './vm';
import DEBUG from '../debug';
const ROOT_SELECTOR = '.edit-text';
// TODO This should be a type exported from Rust using
// wasm-typescript-definition.
type Cursor = any;
function isTextNode(
el: Node | null,
) {
return el !== null && el.nodeType == 3;
}
function isBlock(
el: Node | null,
) {
if (el !== null && el.nodeType == 1 && (el as Element).tagName.toLowerCase() == 'div') {
if ((el as HTMLElement).dataset['tag'] === 'caret') {
return false;
}
return true;
}
return false;
}
function isEmptyBlock(
el: Node | null
) {
return isBlock(el) && (el as Element).querySelector('span') == null;
}
function isSpan(
el: Node | null,
) {
return el !== null && el.nodeType == 1 && (el as Element).tagName.toLowerCase() == 'span';
}
function isElement(
el: Node | null,
) {
return el !== null && el.nodeType == 1;
}
function charLength(
node: Node,
): number {
if (isTextNode(node)) {
return (node as Text).data.length
} else if (isSpan(node)) {
return (node.childNodes[0] as Text).data.length;
} else {
throw new Error('Invalid');
}
}
export type CurElement = any;
export type CurSpan = Array<CurElement>;
function curto(
el: Node | null,
textOffset: number | null = null,
): Cursor {
// Null elements are null cursors.
if (!el) {
return null;
}
// Normalize text nodes at 0 to be spans...
if (isTextNode(el) && textOffset == 0) {
textOffset = null;
}
// Normalize leading spans to be their predecessor text node...
// while (el !== null && textOffset == null) {
// if (isElement(el) && isBlock(el)) {
// break;
// }
// if (isTextNode(el)) {
// el = el.parentNode!;
// continue;
// }
// let prev: Node | null = el!.previousSibling;
// if (prev == null) {
// el = el!.parentNode!;
// } else if (isSpan(prev)) {
// el = prev.firstChild!;
// textOffset = charLength(el!);
// break;
// } else {
// el = prev;
// }
// }
// Is our cursor at a group or at a char?
let cur: CurSpan = [
isElement(el) ? {
'CurGroup': null
} : {
'CurChar': null
}
];
// What is the character (or element) offset?
if (textOffset !== null && textOffset > 0) {
cur.unshift({
"CurSkip": textOffset,
});
}
if (isTextNode(el) && isSpan(el.parentNode)) {
el = el.parentNode;
}
// TODO We should assert that isSpan(el.parentNode).
function place_skip(cur: CurSpan, value: number) {
if ('CurSkip' in cur[0]) {
cur[0].CurSkip += value;
} else {
cur.unshift({
"CurSkip": value,
});
}
}
// Find the offset to the start of the parent element by
// iterating previous siblings.
while (el !== null) {
if (el.previousSibling) {
// Skip previous sibling.
if (isSpan(el.previousSibling) || isTextNode(el.previousSibling)) {
place_skip(cur, charLength(el.previousSibling));
} else if (isElement(el.previousSibling)) {
place_skip(cur, 1);
} else {
throw new Error('unreachable');
}
el = el.previousSibling;
} else {
// Move to parent node.
el = el.parentNode;
if (el == null) {
throw new Error('Unexpectedly reached root');
}
if (!isSpan(el)) {
if (isElement(el) && util.matchesSelector(el, ROOT_SELECTOR)) {
break;
}
cur = [{
"CurWithGroup": cur,
}];
}
}
}
el = el!;
if (!(isElement(el) && util.matchesSelector(el, ROOT_SELECTOR))) {
console.error('Invalid selection!!!');
}
// console.log('result:', JSON.stringify(cur));
return cur;
}
function resolveCursorFromPositionInner(
node: Node | null,
parent: Node,
): Cursor {
if (node == null) {
// Text node is first in element, so select parent node.
return curto(parent);
} else if (isTextNode(node)) {
// Text node has a preceding text element; move to end.
return resolveCursorFromPosition((node as Text), charLength(node));
} else {
// TODO can this be made simpler?
// Enter empty block nodes.
if (isEmptyBlock(node)) {
return curto(node);
}
// Skip empty groups.
if (node.childNodes.length == 0) {
return resolveCursorFromPositionInner(node.previousSibling, parent);
}
// Inspect previous element last to first.
let child = node.childNodes[node.childNodes.length - 1];
if (isTextNode(child)) {
// Text node
return resolveCursorFromPosition((child as Text), charLength(child));
} else {
// Element node
return resolveCursorFromPositionInner(child, node);
}
}
}
function resolveCursorFromPosition(
textNode: Text,
offset: number,
): Cursor {
if (offset == 0) {
return resolveCursorFromPositionInner(textNode.previousSibling, textNode.parentElement!);
} else {
// Move to offset of this text node.
return curto(
textNode,
offset,
);
}
}
// Scan from a point in either direction until a caret is reached.
function caretScan(
x: number,
y: number,
UP: boolean,
): {x: number, y: number} | null {
let root = document.querySelector('.edit-text')!;
// Attempt to get the text node under our scanning point.
let first: any = util.textNodeAtPoint(x, y);
// In doc "# Most of all\n\nThe world is a place where parts of wholes are perscribed"
// When you hit the down key for any character in the first line, it works,
// until the last character (end of the line), where if you hit the down key it
// no longer works and the above turns null. Instead, this check once for the main case,
// check at this offset for the edge case is weird but works well enough.
if (first == null) {
first = util.textNodeAtPoint(x - 2, y);
}
// Select empty blocks directly, which have no anchoring text nodes.
if (first == null) {
let el = document.elementFromPoint(x + 2, y);
if (isEmptyBlock(el)) {
first = el;
}
}
if (first !== null) { // Or we have nothing to compare to and we'll loop all day
while (true) {
// Step a reasonable increment in each direction.
const STEP = 14;
y += UP ? -STEP : STEP;
let el = document.elementFromPoint(x, y);
// console.log('locating element at %d, %d:', x, y, el);
if (!root.contains(el) || el == null) { // Off the page!
break;
}
// Don't do anything if the scanned element is the root element.
if (root !== el) {
// Check when we hit a text node.
let caret = util.textNodeAtPoint(x, y); // TODO should we reuse `first` here?
let isTextNode = caret !== null && (first.textNode !== caret.textNode || first.offset !== caret.offset); // TODO would this comparison even work lol
// Check for the "empty div" scenario
let isEmptyDiv = isEmptyBlock(el);
// if (isEmptyDiv) {
// console.log('----->', el.getBoundingClientRect());
// }
// console.log('attempted caret at', x, y, caret);
if (isTextNode || isEmptyDiv) {
// console.log('CARET', caret);
return {x, y};
}
}
}
}
return null;
}
function getCursorFromPoint(root: Element, x: number, y: number): any {
// Get the boundaries of the root element. Any coordinate we're looking at that exist
// outside of those boundaries, we snap back to the closest edge of the boundary.
let boundary = root.getBoundingClientRect();
// console.info('(m) Snapping x', x, 'y', y, 'to boundary');
// console.info('(m)', boundary);
if (x < boundary.left) {
x = boundary.left;
}
if (y < boundary.top) {
y = boundary.top;
}
if (x > boundary.right) {
x = boundary.right - 1;
}
if (y > boundary.bottom) {
y = boundary.bottom - 1;
}
// console.info('(m) Snapped x', x, 'y', y, 'to boundary.');
// Check whether we selected a text node or a block element, and create a
// cursor for it Only select blocks which are empty.
// TODO merge textNodeAtPoint and caretPositionFromPoint !
let text = util.textNodeAtPoint(x, y);
let element = util.caretPositionFromPoint(x, y);
let target = document.elementFromPoint(x, y);
return text !== null
? resolveCursorFromPosition(text.textNode, text.offset)
: (element !== null
? resolveCursorFromPositionInner(element.textNode.childNodes[element.offset - 1], element.textNode)
: (isEmptyBlock(target)
? curto(target as any)
: null));
}
export class Editor extends React.Component {
props: {
content: string,
controller: ControllerImpl,
KEY_WHITELIST: Array<any>,
editorID: string,
disabled: boolean,
};
el: HTMLElement;
mouseDown = false;
lastClickTime = 0;
onClick(e: MouseEvent) {
let option = e.ctrlKey || e.metaKey;
let isAnchor = e.target ? util.matchesSelector(e.target as Node, '[data-style-Link]') : false;
if (option && isAnchor) {
let url = (e.target as HTMLElement).dataset['styleLink'];
(window as any).open(url, '_blank').focus();
}
}
onMouseDown(e: MouseEvent) {
// Skip if we already handled mousedown. This might be triggered when
// rewriting the underlying HTML, it's also a good sanity check.
if (this.mouseDown) {
return;
}
// Manually detect doubleclick.
if (Date.now() - this.lastClickTime < 400) {
let destCursor = getCursorFromPoint(this.el, e.clientX, e.clientY);
if (destCursor !== null) {
this.props.controller.sendCommand({
'tag': 'CursorSelectWord',
'fields': {
'focus': destCursor,
},
});
this.mouseDown = true;
return;
}
}
this.lastClickTime = Date.now();
let option = e.ctrlKey || e.metaKey;
if (option) {
// Ignore, handle this in onClick
} else {
this.el.focus();
this.mouseDown = true;
this.onMouseMove(e, true);
}
}
onMouseUp(e: MouseEvent) {
this.mouseDown = false;
}
onMouseMove(e: MouseEvent, dropAnchor: boolean = false) {
// Only enable dragging while the mouse is down.
if (!this.mouseDown) {
return;
}
// Cancel the event to prevent native text selection.
e.preventDefault();
// Focus the window
//TODO despite us cancelling the event above? why does this need to happen?
window.focus();
this.moveCursorToPoint(e.clientX, e.clientY, dropAnchor);
}
moveCursorToPoint(x: number, y: number, dropAnchor: boolean = false): CurSpan | null {
// Send the command to the client.
let destCursor = getCursorFromPoint(this.el, x, y);
if (destCursor !== null) {
this.props.controller.sendCommand({
'tag': 'Cursor',
'fields': {
focus: destCursor,
anchor: dropAnchor ? destCursor : null,
},
});
}
return destCursor;
}
onGlobalKeypress(e: KeyboardEvent) {
if (this.props.disabled) {
return;
}
// Don't accept keypresses when a modifier key is pressed.
if (e.ctrlKey || e.metaKey) {
return;
}
// Don't accept non-character keypresses.
if (e.charCode === 0) {
return;
}
this.props.controller.sendCommand({
'tag': 'Character',
'fields': {
char_code: e.charCode,
},
});
e.preventDefault();
}
onGlobalPaste(e: ClipboardEvent) {
if (this.props.disabled) {
return;
}
const text = e.clipboardData.getData('text/plain');
console.info('(c) got pasted text: ', text);
this.props.controller.sendCommand({
'tag': 'InsertText',
'fields': {
text: text,
},
});
}
onGlobalKeydown(e: KeyboardEvent) {
let current = document.querySelector('div.current[data-tag="caret"]');
// We should leave a key event targeting the header element unmodified.
if (e.target !== null) {
if (document.querySelector('#toolbar') && document.querySelector('#toolbar')!.contains(e.target! as Node)) {
return;
}
}
if (this.props.disabled) {
return;
}
// Listener: command + c
if (e.keyCode == 67 && (e.ctrlKey || e.metaKey)) {
this.performCopy();
e.preventDefault();
return;
}
// Listener: command + left, command + right
if (e.metaKey && (e.keyCode == 37 || e.keyCode == 39)) {
// TODO This shouldn't call into DEBUG, this code should instead live
// in editor.tsx and be called from debug.ts.
if (e.keyCode == 37) {
DEBUG.caretToStartOfLine();
} else {
DEBUG.caretToEndOfLine();
}
e.preventDefault();
return;
}
// Check if this event exists in the list of whitelisted key combinations.
let isWhitelisted = this.props.KEY_WHITELIST
.some((x: any) => Object.keys(x).every((key: any) => (e as any)[key] == (x as any)[key]));
if (!isWhitelisted) {
return;
}
// Up and down cursor navigation to find text in the same visual column.
// This requires we perform this from JavaScript, since we need to interact with
// the client box model.
let UP = e.keyCode == 38;
let DOWN = e.keyCode == 40;
// Listener: up, down
if (UP || DOWN) {
let current = document.querySelector('div.current[data-tag="caret"][data-focus="true"]');
if (current !== null) {
// Calculate starting coordinates to "scan" from above our below
// the current cursor position.
let rect = current.getBoundingClientRect();
let y = UP ? rect.top + 5 : rect.bottom - 5;
let x = rect.right;
let coords = caretScan(x, y, UP);
if (coords !== null) {
// Move the cursor and prevent the event from bubbling.
this.moveCursorToPoint(coords.x, coords.y, true);
e.preventDefault();
}
}
// Don't forward up or down keypresses to the controller.
return;
}
// console.log({
// key_code: e.keyCode,
// meta_key: e.metaKey,
// shift_key: e.shiftKey,
// alt_key: e.altKey,
// });
// Forward the keypress to the controller.
this.props.controller.sendCommand({
'tag': 'Keypress',
'fields': {
key_code: e.keyCode,
meta_key: e.metaKey,
shift_key: e.shiftKey,
alt_key: e.altKey,
},
});
e.preventDefault();
}
performCopy() {
// Generate string from selected text by just concatenating
// all .innerText lines.
let str = Array.from(
document.querySelectorAll('span.Selected')
)
.map(x => (x as HTMLElement).innerText)
.join('');
// Debug
console.error('copied: ' + JSON.stringify(str));
copy(str)
.then((res: any) => {
console.info('(c) clipboard successful copy');
})
.catch((err: any) => {
console.info('(c) clipboard unsuccessful copy:', err);
});
}
_setHTML(html: string) {
this.el.innerHTML = html;
this._highlightOwnCarets();
}
_runProgram(program: any) {
vm(this.el).run(program);
this._highlightOwnCarets();
}
_highlightOwnCarets() {
// Highlight our own caret.
let carets: Array<Node> = [];
this.el.querySelectorAll(
`div[data-tag="caret"][data-client=${JSON.stringify(this.props.editorID)}]`,
).forEach(caret => {
caret.classList.add("current");
carets.push(caret);
});
// Create selected span.
if (carets.length >= 2) {
let range = document.createRange();
range.setStartBefore(carets[0]);
range.setEndBefore(carets[1]);
let root = range.commonAncestorContainer as HTMLElement;
// TODO assert(root.contains(start));
for (let start = carets[0] as HTMLElement; start != root; start = start.parentNode! as HTMLElement) {
start.classList.add('selection-start');
}
for (let end = carets[1] as HTMLElement; end != root; end = end.parentNode! as HTMLElement) {
end.classList.add('selection-end');
}
}
}
componentDidMount() {
// Attach all "global" events to the document.
document.addEventListener('keypress', (e: KeyboardEvent) => {
this.onGlobalKeypress(e);
});
document.addEventListener('paste', (e: ClipboardEvent) => {
this.onGlobalPaste(e);
});
document.addEventListener('keydown', (e) => {
this.onGlobalKeydown(e);
});
this._setHTML(this.props.content);
}
render() {
return (
<div
className="edit-text theme-mock"
tabIndex={0}
ref={(el) => { if (el) this.el = el;}}
onClick={this.onClick.bind(this)}
onMouseDown={this.onMouseDown.bind(this)}
onMouseUp={this.onMouseUp.bind(this)}
onMouseMove={this.onMouseMove.bind(this)}
/>
);
}
} | the_stack |
import React, { PureComponent, ReactElement } from 'react'
import {
Animated,
Image,
StyleSheet,
PanResponder,
View,
Text,
PanResponderInstance,
ImageSourcePropType,
Platform,
ViewStyle,
RegisteredStyle
} from 'react-native'
import variables from '../../common/styles/variables'
import sliderStyles from './styles'
import Coord from './Coord'
const thumbImage = require('./images/rectangle.png')
const otherThumbImage = require('./images/rectangle.png')
export interface SliderProps {
style?: ViewStyle | RegisteredStyle<ViewStyle>
value?: number | number[]
min?: number
max?: number
disabled?: boolean
step?: number
marks?: any[] // 刻度
range?: boolean
vertical?: boolean
trackWeight?: number // 滑轨粗细
thumbSize?: number
maxTrackColor?: string
minTrackColor?: string
midTrackColor?: string
onChange?: (value: number | number []) => void
showTip?: boolean
renderTip?: (value: any) => ReactElement<any>
renderThumb?: (isOther: any) => ReactElement<any>
}
interface State {
containerSize: {
width: number
height: number
}
trackSize: {
width: number
height: number
}
thumbSize: {
width: number
height: number
}
otherThumbSize: {
width: number
height: number
}
value: Animated.Value
otherValue: Animated.Value
tip: string
otherTip: string
}
const styles = StyleSheet.create<any>(sliderStyles)
export default class Slider extends PureComponent<SliderProps, State> {
oldValue: any
oldOtherValue: any
panResponder: PanResponderInstance
previousLeft: number
otherPreviousLeft: number
isOther: boolean
showAndroidTip: boolean
static defaultProps = {
value: 0,
min: 0,
max: 1,
step: 0,
maxTrackColor: variables.mtdFillGray,
minTrackColor: variables.mtdBrandPrimary,
midTrackColor: variables.mtdBrandDanger,
range: false,
vertical: false,
showTip: false,
trackWeight: 5,
thumbSize: 30
}
constructor (props) {
super(props)
this.state = {
containerSize: { width: 0, height: 0 },
trackSize: { width: 0, height: 0 },
thumbSize: { width: props.thumbSize, height: props.thumbSize },
otherThumbSize: { width: props.thumbSize, height: props.thumbSize },
value: new Animated.Value(this.getValueByProps()),
otherValue: new Animated.Value(this.getValueByProps(true)),
tip: `${this.getValueByProps()}`,
otherTip: `${this.getValueByProps(true)}`
}
this.isOther = false
this.showAndroidTip = this.props.showTip && Platform.OS === 'android'
}
componentWillMount () {
this.panResponder = PanResponder.create({
onStartShouldSetPanResponder: this.touchStart,
onMoveShouldSetPanResponder: _ => false,
onPanResponderGrant: this.pressStart,
onPanResponderMove: this.lastMove,
onPanResponderRelease: this.touchEnd,
onPanResponderTerminationRequest: _ => false,
onPanResponderTerminate: this.touchEnd
})
}
componentWillReceiveProps (nextProps) {
let newValue = 0
let newOtherValue = 0
const { range } = this.props
if (range && nextProps.value instanceof Array) {
newValue = nextProps.value[0]
newOtherValue = nextProps.value[1]
} else {
newValue = nextProps.value
}
if (this.getValueByProps() !== newValue) {
this.setCurrentValue(newValue)
}
if (range && this.getValueByProps(true) !== newOtherValue) {
this.setCurrentValue(newOtherValue, range)
}
}
/**
* 通过props获取滑块对应的value值
*/
getValueByProps = (isOther?: boolean) => {
const { value, range } = this.props
if (range && value instanceof Array) {
if (isOther) {
return value[1]
}
return value[0]
}
return value as number
}
/**
* 判断用户触控的区域是否在滑块上
*/
thumbTouchCheck = (e: any) => {
const nativeEvent = e.nativeEvent
const { range } = this.props
if (range) {
const otherThumbCoord = this.getThumbCoord(range)
const otherCheckResult = otherThumbCoord.contain(
nativeEvent.locationX,
nativeEvent.locationY
)
if (otherCheckResult) {
this.isOther = true
return otherCheckResult
}
}
const ThumbCoord = this.getThumbCoord()
const checkResult = ThumbCoord.contain(
nativeEvent.locationX,
nativeEvent.locationY
)
if (checkResult) {
this.isOther = false
return checkResult
}
return false
}
getThumbCoord = (isOther?: boolean) => {
const { thumbSize, otherThumbSize, containerSize } = this.state
let currThumb = thumbSize
if (isOther) {
currThumb = otherThumbSize
}
const { vertical } = this.props
let x = null
let y = null
if (vertical) {
x = (containerSize.width - currThumb.width) / 2
y = this.getThumbLeft(this.getCurrentValue(isOther))
} else {
x = this.getThumbLeft(this.getCurrentValue(isOther))
y = (containerSize.height - currThumb.height) / 2
}
return new Coord(
x,
y,
currThumb.width,
currThumb.height,
)
}
/**
* 滚动状态响应
*/
scroll = (gestureState: Object) => {
if (this.props.disabled) {
return
}
if (this.isOther) {
const isOtherValue = this.getValue(gestureState, this.isOther)
this.setCurrentValue(isOtherValue, this.isOther)
} else {
const value = this.getValue(gestureState)
this.setCurrentValue(value)
}
}
touchStart = (e: Object) => {
this.oldValue = (this.state.value as any).__getValue()
this.oldOtherValue = (this.state.otherValue as any).__getValue()
return this.thumbTouchCheck(e)
}
pressStart = () => {
if (this.isOther) {
this.otherPreviousLeft = this.getThumbLeft(this.getCurrentValue(this.isOther))
} else {
this.previousLeft = this.getThumbLeft(this.getCurrentValue())
}
}
lastMove = (_: Object, gestureState: Object) => {
this.scroll(gestureState)
}
touchEnd = (_: Object, gestureState: Object) => {
this.scroll(gestureState)
if (this.oldValue !== this.getCurrentValue()) {
this.triggerEvent('onChange')
}
if (this.props.range && this.oldOtherValue !== this.getCurrentValue(true)) {
this.triggerEvent('onChange')
}
}
measureContainer = (x: Object) => {
this.handleMeasure('containerSize', x)
}
measureTrack = (x: Object) => {
this.handleMeasure('trackSize', x)
}
measureThumb = (x: Object) => {
this.handleMeasure('thumbSize', x)
}
measureOtherThumb = (x: Object) => {
this.handleMeasure('otherThumbSize', x)
}
handleMeasure = (name: string, x: any) => {
const { width, height } = x.nativeEvent.layout
const size = { width, height }
const currentSize = this.state[name]
if (
currentSize &&
width === currentSize.width &&
height === currentSize.height
) {
return
}
const newState: any = {
[name]: size
}
// 双滑块
this.setState(newState)
}
/**
* 获取可滑动长度
*/
getScrollLength = () => {
const { vertical } = this.props
const { trackSize } = this.state
if (vertical) {
return trackSize.height
} else {
return trackSize.width
}
}
/**
* 获取滑块的坐标的宽度
* 如果是横向slider则取width,纵向取height
*/
getThumbOffset = (isOther?: boolean) => {
const { vertical } = this.props
const { thumbSize, otherThumbSize } = this.state
if (vertical && isOther) {
return otherThumbSize.height
} else if (!vertical && isOther) {
return otherThumbSize.width
} else if (vertical && !isOther) {
return thumbSize.height
} else if (!vertical && !isOther) {
return thumbSize.height
}
}
/**
* 获取当前value值所占的百分比
*/
getRatio = (value: number) => {
const { min, max } = this.props
if (max === min) {
return 0
}
return (value - min) / (max - min)
}
/**
* 滑块在滑动轴上的偏移量
* value => x
*/
getThumbLeft = (value: number) => {
const { vertical } = this.props
let ratio = this.getRatio(value)
if (vertical) {
ratio = 1 - ratio
}
const scrollLength = this.getScrollLength()
return (
ratio * scrollLength
)
}
/**
* 互斥prop
* 刻度属性只有正在非纵向轴、非双滑块下才生效
*/
showStep = () => {
const { vertical, step, range } = this.props
if (!range && !vertical && step) {
return true
}
return false
}
/**
* 获取滑动位置所对应的value值,和getThumbLeft方法对应
* x => value
*/
getValue = (gestureState: Object, isOther?: boolean) => {
let previousLeft = this.previousLeft
if (isOther) {
previousLeft = this.otherPreviousLeft
}
const scrollLength = this.getScrollLength()
const { step, min, max, vertical } = this.props
let thumbLeft = null
if (vertical) {
thumbLeft = previousLeft + (gestureState as any).dy
} else {
thumbLeft = previousLeft + (gestureState as any).dx
}
let ratio = thumbLeft / scrollLength
if (vertical) {
ratio = 1 - ratio
}
if (this.showStep()) {
return Math.max(
min,
Math.min(
max,
min + Math.round(ratio * (max - min) / step) * step
)
)
}
return Math.max(
min,
Math.min(
max,
ratio * (max - min) + min
)
)
}
/**
* 获取滑块的value值
*/
getCurrentValue = (isOther?: boolean) => {
let value: any = this.state.value
if (isOther) {
value = this.state.otherValue
}
return value.__getValue()
}
setCurrentValue = (value: number, isOther?: boolean) => {
if (isOther) {
this.setState({
otherTip: `${Math.round(value)}`
})
this.state.otherValue.setValue(value)
} else {
this.setState({
tip: `${Math.round(value)}`
})
this.state.value.setValue(value)
}
}
triggerEvent = (event) => {
if (this.props[event]) {
let args = [Math.round(this.getCurrentValue())]
const { range } = this.props
if (range) {
if (this.compareValue()) {
args.unshift(Math.round(this.getCurrentValue(range)))
} else {
args.push(Math.round(this.getCurrentValue(range)))
}
this.props[event](args)
} else {
this.props[event](args[0])
}
}
}
/**
* 默认滑块的的滑块图片渲染
*/
renderThumbImage = (isOther?: boolean) => {
if (!isOther && !thumbImage) return
if (isOther && !otherThumbImage) return
const { renderThumb } = this.props
const { thumbSize } = this.state
if (typeof renderThumb === 'function') {
return renderThumb(isOther)
}
return <Image style={[thumbSize, { borderRadius: this.getThumbOffset() / 2 }]} source={isOther ? otherThumbImage as ImageSourcePropType : thumbImage as ImageSourcePropType}/>
}
/**
* 刻度模块的渲染
*/
renderMarks = () => {
const { step, marks, min, max, thumbSize } = this.props
if (!this.showStep() || !marks) {
return null
}
const maxStep = Math.ceil(Math.abs((max - min) / step)) + 1
let currStep = 0
const markViewArr = []
while (maxStep > currStep) {
if (React.isValidElement(marks[currStep])) {
markViewArr.push(marks[currStep])
} else {
markViewArr.push(
<View key={currStep} style={{ width: thumbSize, alignItems: 'center' }}>
<Text style={styles.markItemText}>{marks[currStep]}</Text>
<View style={styles.markItemLine}></View>
</View>
)
}
currStep += 1
}
return (
<View
style={styles.markContainer}
>
{markViewArr}
</View>
)
}
/**
* 渲染滑块的toopTip提示
*/
renderThumbToolTip = (isOther?: boolean) => {
const { showTip, renderTip } = this.props
if (!showTip) {
return
}
const { tip, otherTip } = this.state
return (
<View
style={[
styles.tip,
// this.showAndroidTip ? { top: 0, marginTop: 0, height: 100 } : {}
]}>
<View key={1} style={styles.tipContent}>
{
renderTip ? renderTip(isOther ? otherTip : tip)
:
<Text style={styles.tipText}>{isOther ? otherTip : tip}</Text>
}
</View>
<View key={2} style={styles.tipIcon}></View>
</View>
)
}
/**
* 滑动的起始和结束x值
*/
getScrollRange = () => {
const scrollLength = this.getScrollLength()
return [0, scrollLength]
}
/**
* 滑块渲染
*/
renderThumb = (isOther?: boolean) => {
const { vertical, range } = this.props
if (isOther && !range) return
const { value, otherValue, thumbSize, otherThumbSize } = this.state
let currValue = value
let currThumb = thumbSize
let measureFn = this.measureThumb
if (isOther) {
currValue = otherValue
currThumb = otherThumbSize
measureFn = this.measureOtherThumb
}
const thumbLeft = this.getThumbLeft((currValue as any).__getValue())
let thumbStyle: any = {
transform: [{ translateX: thumbLeft }, { translateY: 0 }],
alignItems: 'center',
borderRadius: this.getThumbOffset(isOther) / 2,
}
if (vertical) {
thumbStyle.transform = [{ translateX: 0 }, { translateY: thumbLeft }]
}
if (this.showAndroidTip) {
return (
<Animated.View
onLayout={measureFn}
renderToHardwareTextureAndroid
style={[
styles.thumb,
thumbStyle,
]}
>
{this.renderThumbToolTip(isOther)}
<View
style={[
currThumb,
{ borderRadius: this.getThumbOffset(isOther) / 2 }
]}
>
{this.renderThumbImage(isOther)}
</View>
</Animated.View>
)
}
return (
<Animated.View
onLayout={measureFn}
renderToHardwareTextureAndroid
style={[
styles.thumb,
currThumb,
thumbStyle,
]}
>
{this.renderThumbToolTip(isOther)}
{this.renderThumbImage(isOther)}
</Animated.View>
)
}
/**
* 两个滑块值比较,滑块A的值是否大于B
*/
compareValue = () => {
const { range } = this.props
return range && this.getCurrentValue() >= this.getCurrentValue(true)
}
/**
* 滑轨色值计算
* 双滑块模式下,需要根据两个滑块的值大小结果互换色值
* 垂直滑块模式下,因为滑块的渲染是从顶部计算的,所以滑块需要使用反向色值来实现从底部滑动的效果
* 假设滑块A,B
*/
getTrackColor = (isOther?: boolean) => {
const { minTrackColor, midTrackColor, maxTrackColor, range, vertical } = this.props
let activeColor = ''
// 双滑块B
if (isOther) {
if (this.compareValue()) {
if (vertical) {
// 纵向双滑块A>=B B => midTrackColor
activeColor = midTrackColor
} else {
// 横向双滑块A>=B B => minTrackColor
activeColor = minTrackColor
}
} else {
if (vertical) {
// 纵向双滑块A<B B => trackColor
activeColor = maxTrackColor
} else {
// 横向双滑块A<B B => midTrackColor
activeColor = midTrackColor
}
}
// 双滑块A
} else if (range) {
if (this.compareValue()) {
if (vertical) {
// 纵向双滑块A<B A => trackColor
activeColor = maxTrackColor
} else {
// 横向双滑块A<B A => midTrackColor
activeColor = midTrackColor
}
} else {
if (vertical) {
// 纵向双滑块A>=B A => midTrackColor
activeColor = midTrackColor
} else {
// 横向单滑块A>=B A => minTrackColor
activeColor = minTrackColor
}
}
// 单滑块
} else {
if (vertical) {
// 纵向单滑块 A => trackColor
activeColor = maxTrackColor
} else {
// 横向单滑块 A => minTrackColor
activeColor = minTrackColor
}
}
return [activeColor]
}
/**
* 默认滑块划过的滑轨
*/
renderMinimumTrack = (isOther?: boolean) => {
const { disabled, range, vertical, trackWeight } = this.props
if (isOther && !range) return
const { value, otherValue } = this.state
let currValue: any = value
let minimumTrackColor = null
let currKey = 'minTrack'
if (isOther) {
currValue = otherValue
currKey = 'otherMinTrack'
}
const minimumTrackWidth = this.getThumbLeft(currValue.__getValue())
// 滑轨颜色值设定
const trackColors = this.getTrackColor(isOther)
minimumTrackColor = trackColors[0]
const minimumTrackStyle: any = {
position: 'absolute',
backgroundColor: minimumTrackColor
}
let trackStyle = null
if (vertical) {
minimumTrackStyle.height = minimumTrackWidth
minimumTrackStyle.width = this.props.trackWeight
trackStyle = { marginVertical: this.getThumbOffset(isOther) / 2 }
} else {
minimumTrackStyle.height = this.props.trackWeight
minimumTrackStyle.width = minimumTrackWidth
trackStyle = { marginHorizontal: this.getThumbOffset(isOther) / 2 }
}
return (
<Animated.View
key={currKey}
renderToHardwareTextureAndroid
style={[{ borderRadius: trackWeight / 2 }, minimumTrackStyle, trackStyle]}
/>
)
}
getTrackStyle = () => {
const { range, vertical, maxTrackColor, minTrackColor, trackWeight, thumbSize } = this.props
const trackStyle: any = { backgroundColor: maxTrackColor }
let marginArr = [ 'marginLeft', 'marginRight', 'marginHorizontal', 'height' ]
const rest = thumbSize - trackWeight
const spacing = rest > 0 ? Math.ceil(rest / 2) : 0
if (vertical) {
marginArr = [ 'marginTop', 'marginBottom', 'marginVertical', 'width' ]
trackStyle.flex = 1
trackStyle.alignItems = 'flex-start'
trackStyle.backgroundColor = minTrackColor
trackStyle.marginHorizontal = spacing
} else {
trackStyle.marginVertical = spacing
}
// 样式处理
if (range) {
trackStyle[marginArr[0]] = this.getThumbOffset() / 2
trackStyle[marginArr[1]] = this.getThumbOffset(true) / 2
} else {
trackStyle[marginArr[2]] = this.getThumbOffset() / 2
}
trackStyle[marginArr[3]] = this.props.trackWeight
return trackStyle
}
renderTracks = () => {
const { vertical, trackWeight } = this.props
const trackStyle: any = this.getTrackStyle()
// 如果value > oldValue,则代表两个滑块滑动位置互换,则更新渲染层级
let tracks = [
<View
style={[ { borderRadius: trackWeight / 2 }, trackStyle ]}
onLayout={this.measureTrack}
/>
]
// vertical的值和this.compareValue()值相同时,次滑块轴在底层,反之主滑块轴在底层
if (vertical === this.compareValue()) {
tracks.push(this.renderMinimumTrack(true))
tracks.push(this.renderMinimumTrack())
} else {
tracks.push(this.renderMinimumTrack())
tracks.push(this.renderMinimumTrack(true))
}
return tracks
}
render () {
const { style, vertical } = this.props
return (
<View
style={[
{ flexDirection: vertical ? 'row' : 'column' },
style
]}>
{this.renderMarks()}
<View
style={{
alignItems: vertical ? 'center' : undefined,
justifyContent: vertical ? undefined : 'center'
}}
onLayout={this.measureContainer}
>
{this.renderTracks()}
{this.renderThumb()}
{this.renderThumb(true)}
<View
renderToHardwareTextureAndroid
style={styles.touchArea}
{...this.panResponder.panHandlers}>
</View>
</View>
</View>
)
}
} | the_stack |
import * as coreClient from "@azure/core-client";
/** A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. */
export interface OperationListResult {
/**
* List of operations supported by the resource provider
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: Operation[];
/**
* URL to get the next set of operation list results (if there are any).
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Details of a REST API operation, returned from the Resource Provider Operations API */
export interface Operation {
/**
* The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action"
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for ARM/control-plane operations.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly isDataAction?: boolean;
/** Localized display information for this particular operation. */
display?: OperationDisplay;
/**
* The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system"
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly origin?: Origin;
/**
* Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly actionType?: ActionType;
}
/** Localized display information for this particular operation. */
export interface OperationDisplay {
/**
* The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute".
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provider?: string;
/**
* The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections".
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly resource?: string;
/**
* The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual Machine".
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly operation?: string;
/**
* The short, localized friendly description of the operation; suitable for tool tips and detailed views.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly description?: string;
}
/** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.). */
export interface ErrorResponse {
/** The error object. */
error?: ErrorDetail;
}
/** The error detail. */
export interface ErrorDetail {
/**
* The error code.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly code?: string;
/**
* The error message.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly message?: string;
/**
* The error target.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly target?: string;
/**
* The error details.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly details?: ErrorDetail[];
/**
* The error additional info.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly additionalInfo?: ErrorAdditionalInfo[];
}
/** The resource management error additional info. */
export interface ErrorAdditionalInfo {
/**
* The additional info type.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The additional info.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly info?: Record<string, unknown>;
}
/** List of resources page result. */
export interface LoadTestResourcePageList {
/** List of resources in current page. */
value?: LoadTestResource[];
/** Link to next page of resources. */
nextLink?: string;
}
/** Managed service identity (either system assigned, or none) */
export interface SystemAssignedServiceIdentity {
/**
* The service principal ID of the system assigned identity. This property will only be provided for a system assigned identity.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly principalId?: string;
/**
* The tenant ID of the system assigned identity. This property will only be provided for a system assigned identity.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly tenantId?: string;
/** Type of managed service identity (either system assigned, or none). */
type: SystemAssignedServiceIdentityType;
}
/** Common fields that are returned in the response for all Azure Resource Manager resources */
export interface Resource {
/**
* Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly id?: string;
/**
* The name of the resource
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts"
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* Azure Resource Manager metadata containing createdBy and modifiedBy information.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly systemData?: SystemData;
}
/** Metadata pertaining to creation and last modification of the resource. */
export interface SystemData {
/** The identity that created the resource. */
createdBy?: string;
/** The type of identity that created the resource. */
createdByType?: CreatedByType;
/** The timestamp of resource creation (UTC). */
createdAt?: Date;
/** The identity that last modified the resource. */
lastModifiedBy?: string;
/** The type of identity that last modified the resource. */
lastModifiedByType?: CreatedByType;
/** The timestamp of resource last modification (UTC) */
lastModifiedAt?: Date;
}
/** LoadTest resource patch request body. */
export interface LoadTestResourcePatchRequestBody {
/** Resource tags. */
tags?: Record<string, unknown>;
/** The type of identity used for the resource. */
identity?: SystemAssignedServiceIdentity;
/** Load Test resource properties */
properties?: LoadTestResourcePatchRequestBodyProperties;
}
/** Load Test resource properties */
export interface LoadTestResourcePatchRequestBodyProperties {
/** Description of the resource. */
description?: string;
}
/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */
export type TrackedResource = Resource & {
/** Resource tags. */
tags?: { [propertyName: string]: string };
/** The geo-location where the resource lives */
location: string;
};
/** LoadTest details */
export type LoadTestResource = TrackedResource & {
/** The type of identity used for the resource. */
identity?: SystemAssignedServiceIdentity;
/** Description of the resource. */
description?: string;
/**
* Resource provisioning state.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: ResourceState;
/**
* Resource data plane URI.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly dataPlaneURI?: string;
};
/** Known values of {@link Origin} that the service accepts. */
export enum KnownOrigin {
User = "user",
System = "system",
UserSystem = "user,system"
}
/**
* Defines values for Origin. \
* {@link KnownOrigin} can be used interchangeably with Origin,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **user** \
* **system** \
* **user,system**
*/
export type Origin = string;
/** Known values of {@link ActionType} that the service accepts. */
export enum KnownActionType {
Internal = "Internal"
}
/**
* Defines values for ActionType. \
* {@link KnownActionType} can be used interchangeably with ActionType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Internal**
*/
export type ActionType = string;
/** Known values of {@link ResourceState} that the service accepts. */
export enum KnownResourceState {
Succeeded = "Succeeded",
Failed = "Failed",
Canceled = "Canceled",
Deleted = "Deleted"
}
/**
* Defines values for ResourceState. \
* {@link KnownResourceState} can be used interchangeably with ResourceState,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Succeeded** \
* **Failed** \
* **Canceled** \
* **Deleted**
*/
export type ResourceState = string;
/** Known values of {@link SystemAssignedServiceIdentityType} that the service accepts. */
export enum KnownSystemAssignedServiceIdentityType {
None = "None",
SystemAssigned = "SystemAssigned"
}
/**
* Defines values for SystemAssignedServiceIdentityType. \
* {@link KnownSystemAssignedServiceIdentityType} can be used interchangeably with SystemAssignedServiceIdentityType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **None** \
* **SystemAssigned**
*/
export type SystemAssignedServiceIdentityType = string;
/** Known values of {@link CreatedByType} that the service accepts. */
export enum KnownCreatedByType {
User = "User",
Application = "Application",
ManagedIdentity = "ManagedIdentity",
Key = "Key"
}
/**
* Defines values for CreatedByType. \
* {@link KnownCreatedByType} can be used interchangeably with CreatedByType,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **User** \
* **Application** \
* **ManagedIdentity** \
* **Key**
*/
export type CreatedByType = string;
/** Optional parameters. */
export interface OperationsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type OperationsListResponse = OperationListResult;
/** Optional parameters. */
export interface OperationsListNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listNext operation. */
export type OperationsListNextResponse = OperationListResult;
/** Optional parameters. */
export interface LoadTestsListBySubscriptionOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listBySubscription operation. */
export type LoadTestsListBySubscriptionResponse = LoadTestResourcePageList;
/** Optional parameters. */
export interface LoadTestsListByResourceGroupOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroup operation. */
export type LoadTestsListByResourceGroupResponse = LoadTestResourcePageList;
/** Optional parameters. */
export interface LoadTestsGetOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the get operation. */
export type LoadTestsGetResponse = LoadTestResource;
/** Optional parameters. */
export interface LoadTestsCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the createOrUpdate operation. */
export type LoadTestsCreateOrUpdateResponse = LoadTestResource;
/** Optional parameters. */
export interface LoadTestsUpdateOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the update operation. */
export type LoadTestsUpdateResponse = LoadTestResource;
/** Optional parameters. */
export interface LoadTestsDeleteOptionalParams
extends coreClient.OperationOptions {
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface LoadTestsListBySubscriptionNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listBySubscriptionNext operation. */
export type LoadTestsListBySubscriptionNextResponse = LoadTestResourcePageList;
/** Optional parameters. */
export interface LoadTestsListByResourceGroupNextOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the listByResourceGroupNext operation. */
export type LoadTestsListByResourceGroupNextResponse = LoadTestResourcePageList;
/** Optional parameters. */
export interface LoadTestClientOptionalParams
extends coreClient.ServiceClientOptions {
/** server parameter */
$host?: string;
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import * as napa from "../lib/index";
import * as assert from 'assert';
import * as path from 'path';
import * as t from './napa-zone/test';
describe('napajs/transport', () => {
let napaZone = napa.zone.create('zone10');
describe('TransportContext', () => {
let tc = napa.transport.createTransportContext();
let allocator = napa.memory.debugAllocator(napa.memory.crtAllocator);
it('#saveShared', () => {
tc.saveShared(allocator);
});
let shareable: napa.memory.Shareable = null;
it('#loadShared', () => {
shareable = tc.loadShared(allocator.handle);
assert.deepEqual(shareable.handle, allocator.handle);
});
it('#sharedCount', () => {
assert.equal(shareable.refCount, 3);
});
});
describe('Transportable', () => {
it('#IsTransportable', () => {
assert(napa.transport.isTransportable(new t.CanPass(napa.memory.crtAllocator)));
assert(napa.transport.isTransportable(1));
assert(napa.transport.isTransportable('hello world'));
assert(napa.transport.isTransportable([1, 2, 3]));
assert(napa.transport.isTransportable([1, 2, new t.CanPass(napa.memory.crtAllocator)]));
assert(napa.transport.isTransportable({ a: 1}));
assert(napa.transport.isTransportable({ a: 1, b: new t.CanPass(napa.memory.crtAllocator)}));
assert(napa.transport.isTransportable(() => { return 0; }));
assert(!napa.transport.isTransportable(new t.CannotPass()));
assert(!napa.transport.isTransportable([1, new t.CannotPass()]));
assert(!napa.transport.isTransportable({ a: 1, b: new t.CannotPass()}));
});
});
describe('Marshall/Unmarshall', () => {
it('@node: simple types', () => {
t.simpleTypeTransportTest();
});
it('@napa: simple types', () => {
napaZone.execute('./napa-zone/test', "simpleTypeTransportTest");
}).timeout(3000);
it('@node: JS transportable', () => {
t.jsTransportTest();
});
it('@napa: JS transportable', () => {
napaZone.execute('./napa-zone/test', "jsTransportTest");
});
it('@node: addon transportable', () => {
t.addonTransportTest();
});
it('@napa: addon transportable', () => {
napaZone.execute('./napa-zone/test', "addonTransportTest");
});
it('@node: function transportable', () => {
t.functionTransportTest();
});
it('@napa: function transportable', () => {
napaZone.execute('./napa-zone/test', "functionTransportTest");
});
it('@node: composite transportable', () => {
t.compositeTransportTest();
});
it('@napa: composite transportable', () => {
napaZone.execute('./napa-zone/test', "compositeTransportTest");
});
it('@node: non-transportable', () => {
t.nontransportableTest();
});
it('@napa: non-transportable', () => {
napaZone.execute('./napa-zone/test', "nontransportableTest");
});
});
function transportBuiltinObjects() {
let zoneId: string = 'transport-built-in-test-zone';
let transportTestZone: napa.zone.Zone = napa.zone.create(zoneId, { workers: 4 });
/// Construct an expected result string.
/// constructExpectedResult(5, 5, 255, 0) returns '0,0,0,0,0'
/// constructExpectedResult(2, 5, 255, 0) returns '0,0,255,255,255'
/// constructExpectedResult(0, 5, 255, 0) returns '255,255,255,255,255'
function constructExpectedResult(i: number, size: number, expectedValue: number, defaultValue: number = 0): string {
const assert = require('assert');
assert(i >= 0 && size >= i);
let expected: string = '';
for (let t: number = 0; t < i; t++) {
if (t > 0) expected += ',';
expected += defaultValue.toString();
}
for (var t = i; t < size; t++) {
if (t > 0) expected += ',';
expected += expectedValue.toString();
}
return expected;
}
(<any>global).constructExpectedResult = constructExpectedResult;
transportTestZone.broadcast("global.constructExpectedResult = " + constructExpectedResult.toString());
it('@node: transport SharedArrayBuffer (SAB)', () => {
let promises: Array<Promise<any>> = [];
let sab: SharedArrayBuffer = new SharedArrayBuffer(4);
for (let i: number = 0; i < 4; i++) {
promises[i] = transportTestZone.execute((sab, i) => {
let ta: Uint8Array = new Uint8Array(sab);
ta[i] = 100;
}, [sab, i]);
}
return Promise.all(promises).then((values: Array<napa.zone.Result>) => {
let ta: Uint8Array = new Uint8Array(sab);
assert.deepEqual(ta.toString(), '100,100,100,100');
});
});
it('@node: transport composite object of SharedArrayBuffer', () => {
let sab: SharedArrayBuffer = new SharedArrayBuffer(4);
let ta1: Uint8Array = new Uint8Array(sab);
let ta2: Uint8Array = new Uint8Array(sab);
let obj: Object = { sab: sab, tas: { ta1: ta1, ta2: ta2 }, ta22:ta2 };
return transportTestZone.execute((obj) => {
let ta: Uint8Array = new Uint8Array(obj.sab);
ta[0] = 99;
obj.tas.ta1[1] = 88;
obj.tas.ta2[2] = 77;
obj.ta22[3] = 66;
}, [obj]).then((result: napa.zone.Result) => {
var ta_sab: Uint8Array = new Uint8Array(sab);
assert.deepEqual(ta_sab.toString(), '99,88,77,66');
});
});
function recursivelySetElementOfSharedArrayBuffer(zoneId: string, sab: SharedArrayBuffer, i: number, value: number) {
if (i < 0) return;
let ta: Uint8Array = new Uint8Array(sab);
ta[i] = value;
const assert = require('assert');
// SharedArrayBuffer shares storage when it is transported,
// so elements with index > i have been set to {value} by those finished zone.executions.
let expected: string = (<any>global).constructExpectedResult(i, ta.length, value);
assert.equal(ta.toString(), expected);
const napa = require('../lib/index');
let zone: napa.zone.Zone = (i % 4 < 2) ? napa.zone.get(zoneId) : napa.zone.node;
zone.execute(
recursivelySetElementOfSharedArrayBuffer,
[zoneId, sab, i - 1, value]
).then((result: napa.zone.Result) => {
// SharedArrayBuffer shares storage when it is transported,
// if i > 0, ta[i - 1] has been set to {value} by the previous zone.execute,
// so ta.toString() should be larger than {expected} constructed before.
if (i > 0) assert(ta.toString() > expected);
else if (i === 0) assert.equal(ta.toString(), expected);
else assert(false);
});
}
// @node: node -> napa -> napa -> node -> node -> napa -> napa
it('@node: recursively transport received SharedArrayBuffer (SAB)', () => {
let size: number = 8;
let timeout: number = 50;
let value: number = 255;
let sab: SharedArrayBuffer = new SharedArrayBuffer(size);
let ta: Uint8Array = new Uint8Array(sab);
recursivelySetElementOfSharedArrayBuffer(zoneId, sab, size - 1, value);
return new Promise((resolve, reject) => {
setTimeout(() => {
// Because SharedArrayBuffer will share storage when it is transported,
// once the recursive process finished, all elements of
// the original TypeArray (based on SharedArrayBuffer) should have been set to {value}.
let expected = (<any>global).constructExpectedResult(0, ta.length, value);
assert.equal(ta.toString(), expected);
resolve();
}, timeout);
});
});
function recursivelySetElementOfTypedArray_SAB(zoneId: string, ta: Uint8Array, i: number, value: number) {
if (i < 0) return;
ta[i] = value;
const assert = require('assert');
// SharedArrayBuffer shares storage when it is transported,
// so elements with index > i have been set to {value} by those finished zone.executions.
let expected: string = (<any>global).constructExpectedResult(i, ta.length, value);
assert.equal(ta.toString(), expected);
const napa = require('../lib/index');
let zone: napa.zone.Zone = (i % 4 < 2) ? napa.zone.get(zoneId) : napa.zone.node;
zone.execute(
recursivelySetElementOfTypedArray_SAB,
[zoneId, ta, i - 1, value]
).then((result: napa.zone.Result) => {
// SharedArrayBuffer shares storage when it is transported,
// if i > 0, ta[i - 1] has been set to {value} by the previous zone.execute,
// so ta.toString() should be larger than {expected} constructed before.
if (i > 0) assert(ta.toString() > expected);
else if (i === 0) assert.equal(ta.toString(), expected);
else assert(false);
});
}
// @node: node -> napa -> napa -> node -> node -> napa -> napa
it('@node: recursively transport received TypedArray based on SAB', () => {
let size: number = 8;
let timeout: number = 50;
let value: number = 255;
let sab: SharedArrayBuffer = new SharedArrayBuffer(size);
let ta: Uint8Array = new Uint8Array(sab);
recursivelySetElementOfTypedArray_SAB(zoneId, ta, size - 1, value);
return new Promise((resolve, reject) => {
setTimeout(() => {
// Because SharedArrayBuffer will share storage when it is transported,
// once the recursive process finished, all elements of
// the original TypeArray (based on SharedArrayBuffer) should have been set to {value}.
let expected: string = (<any>global).constructExpectedResult(0, ta.length, value);
assert.equal(ta.toString(), expected);
resolve();
}, timeout);
});
});
function recursivelySetElementOfArrayBuffer(zoneId: string, ab: ArrayBuffer, i: number, value: number) {
if (i < 0) {
return;
}
let ta: Uint8Array = new Uint8Array(ab);
ta[i] = value;
const assert = require('assert');
// ArrayBuffer's storage will be copied when it is transported.
// Elements with index > i should all be {value}.
// They are copied from the previous zone.execution.
let expected: string = (<any>global).constructExpectedResult(i, ta.length, value);
assert.equal(ta.toString(), expected);
const napa = require('../lib/index');
let zone: napa.zone.Zone = (i % 4 < 2) ? napa.zone.get(zoneId) : napa.zone.node;
zone.execute(
recursivelySetElementOfArrayBuffer,
[zoneId, ab, i - 1, value]
).then((result: napa.zone.Result) => {
// The original TypeArray (based on ArrayBuffer) shouldn't been changed by the just-finished zone.execute.
assert.equal(ta.toString(), expected);
});
}
// @node: node -> napa -> napa -> node -> node -> napa -> napa
it('@node: recursively transport received ArrayBuffer (AB)', () => {
let size: number = 8;
let timeout: number = 50;
let value: number = 255;
let ab: ArrayBuffer = new ArrayBuffer(size);
let ta: Uint8Array = new Uint8Array(ab);
recursivelySetElementOfArrayBuffer(zoneId, ab, size - 1, value);
return new Promise((resolve, reject) => {
setTimeout(() => {
// Except ta[ta-length -1] was set to {value} before the 1st transportation,
// the original TypeArray (based on ArrayBuffer) shouldn't been changed by the recursive execution.
let expected: string = (<any>global).constructExpectedResult(ta.length - 1, ta.length, value);
assert.equal(ta.toString(), expected);
resolve();
}, timeout);
});
});
function recursivelySetElementOfTypeArray_AB(zoneId: string, ta: Uint8Array, i: number, value: number) {
if (i < 0) {
return;
}
ta[i] = value;
const assert = require('assert');
// ArrayBuffer's storage will be copied when it is transported.
// Elements with index > i should all be {value}.
// They are copied from the previous zone.execution.
let expected: string = (<any>global).constructExpectedResult(i, ta.length, value);
assert.equal(ta.toString(), expected);
const napa = require('../lib/index');
let zone: napa.zone.Zone = (i % 4 < 2) ? napa.zone.get(zoneId) : napa.zone.node;
zone.execute(
recursivelySetElementOfTypeArray_AB,
[zoneId, ta, i - 1, value]
).then((result: napa.zone.Result) => {
// The original TypeArray (based on ArrayBuffer) shouldn't been changed by the just-finished zone.execute.
assert.equal(ta.toString(), expected);
});
}
// @node: node -> napa -> napa -> node -> node -> napa -> napa
it('@node: recursively transport received TypedArray based on AB', () => {
let size: number = 8;
let timeout: number = 50;
let value: number = 255;
let ab: ArrayBuffer = new ArrayBuffer(size);
let ta: Uint8Array = new Uint8Array(ab);
recursivelySetElementOfTypeArray_AB(zoneId, ta, size - 1, value);
return new Promise((resolve, reject) => {
setTimeout(() => {
// Except ta[ta-length -1] was set to {value} before the 1st transportation,
// the original TypeArray (based on ArrayBuffer) shouldn't been changed by the recursive execution.
let expected: string = (<any>global).constructExpectedResult(ta.length - 1, ta.length, value);
assert.equal(ta.toString(), expected);
resolve();
}, timeout);
});
});
}
let builtinTestGroup = 'Transport built-in objects';
let nodeVersionMajor = parseInt(process.versions.node.split('.')[0]);
if (nodeVersionMajor >= 9) {
describe(builtinTestGroup, transportBuiltinObjects);
} else {
describe.skip(builtinTestGroup, transportBuiltinObjects);
require('npmlog').warn(builtinTestGroup, 'This test group is skipped since it requires node v9.0.0 or above.');
}
}); | the_stack |
import React, { FC, KeyboardEvent as ReactKeyboardEvent, MouseEvent, useCallback, useEffect, useState } from "react";
import { Hit, Links, ValueHitField } from "@scm-manager/ui-types";
import styled from "styled-components";
import { useSearch } from "@scm-manager/ui-api";
import classNames from "classnames";
import { Link, useHistory, useLocation } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Button, HitProps, Notification, RepositoryAvatar, useStringHitFieldValue } from "@scm-manager/ui-components";
import SyntaxHelp from "../search/SyntaxHelp";
import SyntaxModal from "../search/SyntaxModal";
import SearchErrorNotification from "../search/SearchErrorNotification";
import queryString from "query-string";
const Input = styled.input`
border-radius: 4px !important;
`;
type Props = {
links: Links;
};
const namespaceAndName = (hit: Hit) => {
const namespace = (hit.fields["namespace"] as ValueHitField).value as string;
const name = (hit.fields["name"] as ValueHitField).value as string;
return `${namespace}/${name}`;
};
type HitsProps = {
hits: Hit[];
index: number;
showHelp: () => void;
gotoDetailSearch: () => void;
clear: () => void;
};
const QuickSearchNotification: FC = ({ children }) => <div className="dropdown-content p-4">{children}</div>;
type GotoProps = {
gotoDetailSearch: () => void;
};
const EmptyHits: FC = () => {
const [t] = useTranslation("commons");
return (
<Notification className="m-4" type="info">
{t("search.quickSearch.noResults")}
</Notification>
);
};
const ResultHeading = styled.h3`
border-bottom: 1px solid lightgray;
`;
const DropdownMenu = styled.div`
max-width: 20rem;
`;
const ResultFooter = styled.div`
border-top: 1px solid lightgray;
`;
const AvatarSection: FC<HitProps> = ({ hit }) => {
const namespace = useStringHitFieldValue(hit, "namespace");
const name = useStringHitFieldValue(hit, "name");
const type = useStringHitFieldValue(hit, "type");
const repository = hit._embedded?.repository;
if (!namespace || !name || !type || !repository) {
return null;
}
return (
<span className="mr-2">
<RepositoryAvatar repository={repository} size={24} />
</span>
);
};
const MoreResults: FC<GotoProps> = ({ gotoDetailSearch }) => {
const [t] = useTranslation("commons");
return (
<ResultFooter className={classNames("dropdown-item", "has-text-centered", "mx-2", "px-2", "py-1")}>
<Button action={gotoDetailSearch} color="primary" data-omnisearch="true">
{t("search.quickSearch.moreResults")}
</Button>
</ResultFooter>
);
};
const HitsList: FC<HitsProps> = ({ hits, index, clear, gotoDetailSearch }) => {
const id = useCallback(namespaceAndName, [hits]);
if (hits.length === 0) {
return <EmptyHits />;
}
return (
<>
{hits.map((hit, idx) => (
<div key={id(hit)} onMouseDown={(e) => e.preventDefault()} onClick={clear}>
<Link
className={classNames("is-flex", "dropdown-item", "has-text-weight-medium", "is-ellipsis-overflow", {
"is-active": idx === index,
})}
title={id(hit)}
to={`/repo/${id(hit)}`}
role="option"
data-omnisearch="true"
>
<AvatarSection hit={hit} />
{id(hit)}
</Link>
</div>
))}
</>
);
};
const Hits: FC<HitsProps> = ({ showHelp, gotoDetailSearch, ...rest }) => {
const [t] = useTranslation("commons");
return (
<>
<div aria-expanded="true" role="listbox" className="dropdown-content">
<ResultHeading
className={classNames(
"dropdown-item",
"is-flex",
"is-justify-content-space-between",
"is-align-items-center",
"mx-2",
"px-2",
"py-1",
"has-text-weight-bold"
)}
>
<span>{t("search.quickSearch.resultHeading")}</span>
<SyntaxHelp onClick={showHelp} />
</ResultHeading>
<HitsList showHelp={showHelp} gotoDetailSearch={gotoDetailSearch} {...rest} />
<MoreResults gotoDetailSearch={gotoDetailSearch} />
</div>
</>
);
};
const useKeyBoardNavigation = (gotoDetailSearch: () => void, clear: () => void, hits?: Array<Hit>) => {
const [index, setIndex] = useState(-1);
const history = useHistory();
useEffect(() => {
setIndex(-1);
}, [hits]);
const onKeyDown = (e: ReactKeyboardEvent<HTMLInputElement>) => {
// We use e.which, because ie 11 does not support e.code
// https://caniuse.com/keyboardevent-code
switch (e.which) {
case 40: // e.code: ArrowDown
if (hits) {
setIndex((idx) => {
if (idx + 1 < hits.length) {
return idx + 1;
}
return idx;
});
}
break;
case 38: // e.code: ArrowUp
if (hits) {
setIndex((idx) => {
if (idx > 0) {
return idx - 1;
}
return idx;
});
}
break;
case 13: // e.code: Enter
if (hits && index >= 0) {
const hit = hits[index];
history.push(`/repo/${namespaceAndName(hit)}`);
clear();
} else {
e.preventDefault();
gotoDetailSearch();
}
break;
case 27: // e.code: Escape
if (index >= 0) {
setIndex(-1);
} else {
clear();
}
break;
}
};
return {
onKeyDown,
index,
};
};
const useDebounce = (value: string, delay: number) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
const isMoreResultsButton = (element: Element) => {
return element.tagName.toLocaleLowerCase("en") === "button" && element.className.includes("is-primary");
};
const isOnmiSearchElement = (element: Element) => {
return element.getAttribute("data-omnisearch") || isMoreResultsButton(element);
};
const useShowResultsOnFocus = () => {
const [showResults, setShowResults] = useState(false);
useEffect(() => {
if (showResults) {
const close = () => {
setShowResults(false);
};
const onKeyUp = (e: KeyboardEvent) => {
if (e.which === 9) {
// tab
const element = document.activeElement;
if (!element || !isOnmiSearchElement(element)) {
close();
}
}
};
window.addEventListener("click", close);
window.addEventListener("keyup", onKeyUp);
return () => {
window.removeEventListener("click", close);
window.removeEventListener("keyup", onKeyUp);
};
}
}, [showResults]);
return {
showResults,
onClick: (e: MouseEvent<HTMLInputElement>) => {
e.stopPropagation();
setShowResults(true);
},
onKeyPress: () => setShowResults(true),
onFocus: () => setShowResults(true),
hideResults: () => setShowResults(false),
};
};
const useSearchParams = () => {
const location = useLocation();
const pathname = location.pathname;
let searchType = "repository";
let initialQuery = "";
if (pathname.startsWith("/search/")) {
const path = pathname.substring("/search/".length);
const index = path.indexOf("/");
if (index > 0) {
searchType = path.substring(0, index);
} else {
searchType = path;
}
const queryParams = queryString.parse(location.search);
initialQuery = queryParams.q || "";
}
return {
searchType,
initialQuery,
};
};
const OmniSearch: FC = () => {
const { searchType, initialQuery } = useSearchParams();
const [query, setQuery] = useState(initialQuery);
const debouncedQuery = useDebounce(query, 250);
const { data, isLoading, error } = useSearch(debouncedQuery, { type: "repository", pageSize: 5 });
const { showResults, hideResults, ...handlers } = useShowResultsOnFocus();
const [showHelp, setShowHelp] = useState(false);
const history = useHistory();
const openHelp = () => setShowHelp(true);
const closeHelp = () => setShowHelp(false);
const clearQuery = () => setQuery("");
const gotoDetailSearch = () => {
if (query.length > 1) {
history.push(`/search/${searchType}/?q=${query}`);
hideResults();
}
};
const { onKeyDown, index } = useKeyBoardNavigation(gotoDetailSearch, clearQuery, data?._embedded.hits);
return (
<div className={classNames("navbar-item", "field", "mb-0")}>
{showHelp ? <SyntaxModal close={closeHelp} /> : null}
<div
className={classNames("control", "has-icons-right", {
"is-loading": isLoading,
})}
>
<div className={classNames("dropdown", { "is-active": (!!data || error) && showResults })}>
<div className="dropdown-trigger">
<Input
className="input is-small"
type="text"
placeholder="Search ..."
onChange={(e) => setQuery(e.target.value)}
onKeyDown={onKeyDown}
value={query}
role="combobox"
aria-autocomplete="list"
data-omnisearch="true"
{...handlers}
/>
{isLoading ? null : (
<span className="icon is-right">
<i className="fas fa-search" />
</span>
)}
</div>
<DropdownMenu className="dropdown-menu" onMouseDown={(e) => e.preventDefault()}>
{error ? (
<QuickSearchNotification>
<SearchErrorNotification error={error} showHelp={openHelp} />
</QuickSearchNotification>
) : null}
{!error && data ? (
<Hits
showHelp={openHelp}
gotoDetailSearch={gotoDetailSearch}
clear={clearQuery}
index={index}
hits={data._embedded.hits}
/>
) : null}
</DropdownMenu>
</div>
</div>
</div>
);
};
const OmniSearchGuard: FC<Props> = ({ links }) => {
if (!links.search) {
return null;
}
return <OmniSearch />;
};
export default OmniSearchGuard; | the_stack |
import {
findRedirect,
getRandStr,
resolvePageRoute,
setStoreItem,
sleep,
TCCSVersion,
TDefaultPageName,
TPackageCromwellConfig,
} from '@cromwell/core';
import {
BasePageEntity,
cmsPackageName,
getCmsEntity,
getCmsInfo,
getCmsModuleInfo,
getCmsSettings,
getLogger,
getModulePackage,
getNodeModuleDir,
getPublicDir,
getServerDir,
getThemeConfigs,
PostRepository,
ProductCategoryRepository,
ProductRepository,
readCmsModules,
runShellCommand,
TagRepository,
} from '@cromwell/core-backend';
import { getCentralServerClient } from '@cromwell/core-frontend';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import archiver from 'archiver';
import { format } from 'date-fns';
import { FastifyReply } from 'fastify';
import fs from 'fs-extra';
import { join, resolve } from 'path';
import { pipeline } from 'stream';
import { Container, Service } from 'typedi';
import { getConnection, getCustomRepository, Repository } from 'typeorm';
import * as util from 'util';
import { AdminCmsConfigDto } from '../dto/admin-cms-config.dto';
import { CmsStatusDto } from '../dto/cms-status.dto';
import { SetupDto } from '../dto/setup.dto';
import { childSendMessage } from '../helpers/server-manager';
import { endTransaction, restartService, setPendingKill, startTransaction } from '../helpers/state-manager';
import { MockService } from './mock.service';
import { PluginService } from './plugin.service';
import { ThemeService } from './theme.service';
const logger = getLogger();
const pump = util.promisify(pipeline);
@Injectable()
@Service()
export class CmsService {
private get pluginService() {
return Container.get(PluginService);
}
private get themeService() {
return Container.get(ThemeService);
}
private get mockService() {
return Container.get(MockService);
}
private isRunningNpm = false;
private checkedYarn = false;
constructor() {
this.init();
}
private async init() {
await sleep(1);
if (!getConnection()?.isConnected) return;
// Schedule sitemap re-build once in a day
setInterval(() => this.buildSitemap, 1000 * 60 * 60 * 24);
}
public async getIsRunningNpm() {
return this.isRunningNpm;
}
public async setIsRunningNpm(isRunning) {
this.isRunningNpm = isRunning;
}
public async checkYarn() {
if (this.checkedYarn) return;
this.checkedYarn = true;
try {
await runShellCommand(`npm i -g yarn`);
} catch (error) {
logger.error(error);
}
}
public async setThemeName(themeName: string) {
const entity = await getCmsEntity();
if (entity) {
entity.publicSettings = {
...(entity.publicSettings ?? {}),
themeName,
}
await entity.save();
return true;
}
return false;
}
async uploadFile(req: any, dirName: string): Promise<any> {
if (!req.isMultipart()) {
return;
}
const parts = req.files();
for await (const part of parts) {
const fullPath = join(`${dirName}/${part.filename}`);
await pump(part.file, fs.createWriteStream(fullPath));
}
}
async downloadFile(response: FastifyReply, inPath: string, fileName: string) {
const fullPath = join(getPublicDir(), inPath ?? '', fileName);
if (! await fs.pathExists(fullPath)) {
response.code(404).send({ message: 'File not found' });
return;
}
if ((await fs.lstat(fullPath)).isFile()) {
response.header('Content-Disposition', `attachment; filename=${fileName}`);
try {
const readStream = fs.createReadStream(fullPath);
response.type('text/html').send(readStream);
} catch (error) {
logger.error(error);
response.code(500).send({ message: error + '' });
}
} else {
response.header('Content-Disposition', `attachment; filename=${fileName}.zip`);
// zip the directory
const archive = archiver('zip', {
zlib: { level: 9 }
});
archive.directory(fullPath, '/' + fileName);
response.type('text/html').send(archive);
await archive.finalize();
}
}
public async parseModuleConfigImages(moduleInfo: TPackageCromwellConfig, moduleName: string) {
if (!moduleInfo) return;
if (moduleInfo.icon) {
const moduleDir = await getNodeModuleDir(moduleName);
// Read icon and convert to base64
if (moduleDir) {
const imgPath = resolve(moduleDir, moduleInfo?.icon);
if (await fs.pathExists(imgPath)) {
const data = (await fs.readFile(imgPath))?.toString('base64');
if (data) moduleInfo.icon = data;
}
}
}
if (!moduleInfo.images) moduleInfo.images = [];
if (moduleInfo.image) {
// Read image and convert to base64
const moduleDir = await getNodeModuleDir(moduleName);
if (moduleDir) {
const imgPath = resolve(moduleDir, moduleInfo.image);
if (await fs.pathExists(imgPath)) {
const data = (await fs.readFile(imgPath))?.toString('base64');
if (data) moduleInfo.image = data;
}
}
if (!moduleInfo.images.includes(moduleInfo.image))
moduleInfo.images.push(moduleInfo.image);
}
}
public async installCms(input: SetupDto) {
if (!input.url)
throw new HttpException('URL is not provided', HttpStatus.UNPROCESSABLE_ENTITY);
const cmsEntity = await getCmsEntity();
if (cmsEntity?.internalSettings?.installed) {
logger.error('CMS already installed');
throw new HttpException('CMS already installed', HttpStatus.BAD_REQUEST);
}
cmsEntity.internalSettings = {
...(cmsEntity.internalSettings ?? {}),
installed: true,
}
cmsEntity.publicSettings = {
...(cmsEntity.publicSettings ?? {}),
url: input.url,
}
await cmsEntity.save();
const settings = await getCmsSettings();
if (settings) {
setStoreItem('cmsSettings', settings)
}
await this.mockService.mockAll();
const serverDir = getServerDir();
const publicDir = getPublicDir();
if (!serverDir || !publicDir) return false;
const robotsSource = resolve(serverDir, 'static/robots.txt');
let robotsContent = await (await fs.readFile(robotsSource)).toString();
robotsContent += `\n\nSitemap: ${input.url}/default_sitemap.xml`;
await fs.outputFile(resolve(publicDir, 'robots.txt'), robotsContent, {
encoding: 'UTF-8'
});
return true;
}
public async buildSitemap() {
const settings = await getCmsSettings();
if (!settings?.url) throw new HttpException("CmsService::buildSitemap: could not find website's URL", HttpStatus.INTERNAL_SERVER_ERROR);
if (!settings.themeName) throw new HttpException("CmsService::buildSitemap: could not find website's themeName", HttpStatus.INTERNAL_SERVER_ERROR);
const configs = await getThemeConfigs(settings.themeName);
setStoreItem('defaultPages', configs.themeConfig?.defaultPages);
const urls: string[] = [];
let content = '';
const addPage = (route: string, updDate: Date) => {
if (!route.startsWith('/')) route = '/' + route;
const redirect = findRedirect(route);
if (redirect?.type === 'redirect' && redirect.to) {
route = redirect.to;
}
if (redirect?.type === 'rewrite' && redirect.from === '/404') return;
if (!route.startsWith('http')) {
route = settings.url + route;
}
if (urls.includes(route)) return;
urls.push(route);
content +=
` <url>
<loc>${route}</loc>
<lastmod>${format(updDate, 'yyyy-MM-dd')}</lastmod>
</url>\n`;
}
configs.themeConfig?.pages?.forEach(page => {
if (!page.route || page.route.includes('[slug]') ||
page.route.includes('[id]') || page.route === 'index'
|| page.route === '404') return;
addPage(
page.route,
new Date(Date.now())
);
})
const outputEntity = async (repo: Repository<any>, pageName: TDefaultPageName) => {
const entities: BasePageEntity[] = await repo.find({
select: ['slug', 'id', 'updateDate', 'createDate'],
});
entities.forEach(ent => {
const updDate = ent.updateDate ?? ent.createDate;
addPage(
resolvePageRoute(pageName, { slug: ent.slug ?? ent.id + '' }),
updDate ?? new Date(Date.now())
);
});
}
await outputEntity(getCustomRepository(PostRepository), 'post');
await outputEntity(getCustomRepository(ProductRepository), 'product');
await outputEntity(getCustomRepository(ProductCategoryRepository), 'category');
await outputEntity(getCustomRepository(TagRepository), 'tag');
content = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${content}
</urlset>`;
await fs.outputFile(resolve(getPublicDir(), 'default_sitemap.xml'), content, {
encoding: 'UTF-8'
});
return true;
}
public async readPlugins(): Promise<TPackageCromwellConfig[]> {
const out: TPackageCromwellConfig[] = [];
const pluginModules = (await readCmsModules()).plugins;
for (const pluginName of pluginModules) {
const moduleInfo = await getCmsModuleInfo(pluginName);
delete moduleInfo?.frontendDependencies;
delete moduleInfo?.bundledDependencies;
delete moduleInfo?.firstLoadedDependencies;
if (moduleInfo) {
await this.parseModuleConfigImages(moduleInfo, pluginName);
out.push(moduleInfo);
}
}
return out;
}
public async readThemes(): Promise<TPackageCromwellConfig[]> {
const out: TPackageCromwellConfig[] = [];
const themeModuleNames = (await readCmsModules()).themes;
for (const themeName of themeModuleNames) {
const moduleInfo = await getCmsModuleInfo(themeName);
if (moduleInfo) {
delete moduleInfo.frontendDependencies;
delete moduleInfo.bundledDependencies;
delete moduleInfo.firstLoadedDependencies;
await this.parseModuleConfigImages(moduleInfo, themeName);
out.push(moduleInfo);
}
}
return out;
}
public async getAdminConfig() {
const config = await getCmsSettings();
const info = await getCmsInfo();
if (!config) {
throw new HttpException('CmsController::getPrivateConfig Failed to read CMS Config', HttpStatus.INTERNAL_SERVER_ERROR);
}
const dto = new AdminCmsConfigDto().parseConfig(config);
dto.cmsInfo = info;
try {
const robotsPath = resolve(getPublicDir(), 'robots.txt');
if (await fs.pathExists(robotsPath))
dto.robotsContent = (await fs.readFile(robotsPath)).toString();
} catch (error) {
logger.error(error);
}
return dto;
}
public async updateCmsSettings(input: AdminCmsConfigDto): Promise<AdminCmsConfigDto> {
const entity = await getCmsEntity();
if (!entity) throw new HttpException('CMS settings not found', HttpStatus.INTERNAL_SERVER_ERROR);
if (typeof input.currencies === 'string') {
try {
input.currencies = JSON.parse(input.currencies);
} catch (error) {
logger.error(error);
}
}
entity.publicSettings = {
url: input.url,
defaultPageSize: input.defaultPageSize,
currencies: input.currencies,
timezone: input.timezone,
language: input.language,
favicon: input.favicon,
logo: input.logo,
headHtml: input.headHtml,
footerHtml: input.footerHtml,
defaultShippingPrice: input.defaultShippingPrice,
customMeta: input.customMeta,
}
entity.adminSettings = {
sendFromEmail: input.sendFromEmail,
smtpConnectionString: input.smtpConnectionString,
customFields: input.customFields,
customEntities: input.customEntities,
}
await entity.save();
if (input.robotsContent) {
await fs.outputFile(resolve(getPublicDir(), 'robots.txt'), input.robotsContent, {
encoding: 'UTF-8'
});
}
const config = await getCmsSettings();
if (!config) throw new HttpException('!config', HttpStatus.INTERNAL_SERVER_ERROR);
return new AdminCmsConfigDto().parseConfig(config);
}
async checkCmsUpdate(): Promise<TCCSVersion | undefined> {
const settings = await getCmsSettings();
const cmsPckg = await getModulePackage(cmsPackageName);
const isBeta = !!settings?.beta;
try {
return await getCentralServerClient().checkCmsUpdate(settings?.version ?? cmsPckg?.version ?? '0', isBeta);
} catch (error) { }
}
async getCmsStatus(): Promise<CmsStatusDto> {
const status = new CmsStatusDto();
const settings = await getCmsSettings();
const availableUpdate = await this.checkCmsUpdate();
status.updateAvailable = !!availableUpdate;
status.updateInfo = availableUpdate;
status.isUpdating = settings?.isUpdating;
status.currentVersion = settings?.version;
status.notifications = [];
if (!settings?.smtpConnectionString) {
status.notifications.push({
type: 'warning',
message: 'Setup SMTP settings',
documentationLink: 'https://cromwellcms.com/docs/features/mail',
pageLink: '/admin/settings'
})
}
return status;
}
async handleUpdateCms() {
const transactionId = getRandStr(8);
startTransaction(transactionId);
if (await this.getIsRunningNpm()) {
throw new HttpException('Only one install/update available at the time', HttpStatus.METHOD_NOT_ALLOWED);
}
this.setIsRunningNpm(true);
await this.checkYarn();
let success = false;
let error: any;
try {
success = await this.updateCms();
} catch (err) {
error = err;
}
await this.setIsRunningNpm(false);
endTransaction(transactionId);
if (!success) {
logger.error(error);
throw new HttpException(error?.message, error?.status);
}
return true;
}
async updateCms(): Promise<boolean> {
const availableUpdate = await this.checkCmsUpdate();
if (!availableUpdate?.packageVersion) throw new HttpException(`Update failed: !availableUpdate?.packageVersion`, HttpStatus.INTERNAL_SERVER_ERROR);
if (availableUpdate.onlyManualUpdate) throw new HttpException(`Update failed: Cannot launch automatic update. Please update using npm install command and restart CMS`, HttpStatus.FORBIDDEN);
const pckg = await getModulePackage();
if (!pckg?.dependencies?.[cmsPackageName])
throw new HttpException(`Update failed: Could not find ${cmsPackageName} in package.json`, HttpStatus.INTERNAL_SERVER_ERROR);
const cmsPckgOld = await getModulePackage(cmsPackageName);
const versionOld = cmsPckgOld?.version;
if (!versionOld)
throw new HttpException(`Update failed: Could not find ${cmsPackageName} package`, HttpStatus.INTERNAL_SERVER_ERROR);
await runShellCommand(`yarn upgrade ${cmsPackageName}@${availableUpdate.packageVersion} --exact --non-interactive`);
await sleep(1);
const cmsPckg = await getModulePackage(cmsPackageName);
if (!cmsPckg?.version || cmsPckg.version !== availableUpdate.packageVersion)
throw new HttpException(`Update failed: cmsPckg.version !== availableUpdate.packageVersion`, HttpStatus.INTERNAL_SERVER_ERROR);
const cmsEntity = await getCmsEntity();
cmsEntity.internalSettings = {
...(cmsEntity.internalSettings ?? {}),
version: availableUpdate.version,
}
await cmsEntity.save();
await getCmsSettings();
for (const service of (availableUpdate?.restartServices ?? [])) {
// Restarts entire service by Manager service
await restartService(service);
}
await sleep(1);
if ((availableUpdate?.restartServices ?? []).includes('api-server')) {
// Restart API server by Proxy manager
const resp1 = await childSendMessage('make-new');
if (resp1.message !== 'success') {
// Rollback
await runShellCommand(`yarn upgrade ${cmsPackageName}@${versionOld} --save --non-interactive`);
await sleep(1);
throw new HttpException('Could not start server after update', HttpStatus.INTERNAL_SERVER_ERROR);
} else {
const resp2 = await childSendMessage('apply-new', resp1.payload);
if (resp2.message !== 'success') throw new HttpException('Could not apply new server after update', HttpStatus.INTERNAL_SERVER_ERROR);
setPendingKill(2000);
}
}
return true;
}
async installModuleDependencies(moduleName: string) {
const pckg = await getModulePackage(moduleName);
for (const pluginName of (pckg?.cromwell?.plugins ?? [])) {
const pluginPckg = await getModulePackage(pluginName);
if (pluginPckg) continue;
try {
await this.pluginService.handleInstallPlugin(pluginName);
} catch (error) {
logger.error(error);
}
}
for (const themeName of (pckg?.cromwell?.themes ?? [])) {
const themePckg = await getModulePackage(themeName);
if (themePckg) continue;
try {
await this.themeService.handleInstallTheme(themeName);
} catch (error) {
logger.error(error);
}
}
}
} | the_stack |
import { Assert, AITestClass } from "@microsoft/ai-test-framework";
import { ITelemetryItem, AppInsightsCore, IPlugin, IConfiguration, DiagnosticLogger, IAppInsightsCore, ITelemetryPluginChain, doPerf, EventsDiscardedReason, INotificationManager, IPerfEvent} from '@microsoft/applicationinsights-core-js';
import { PerfMarkMeasureManager } from '../../../src/PerfMarkMeasureManager';
export interface PerfMeasures {
name: string;
from: string;
to: string;
};
export class MarkMeasureTests extends AITestClass {
_marks: string[] = [];
_measures: PerfMeasures[] = [];
public testInitialize() {
this._marks = [];
this._measures = [];
this.mockPerformance({
mark: (name: string) => {
this._marks.push(name);
},
measure: (name, from, to) => {
this._measures.push({ name, from, to });
}
});
}
public testCleanup() {
}
public registerTests() {
this.testCase({
name: "Empty Initialization still calls mark and measure",
test: () => {
const manager = new PerfMarkMeasureManager();
const core = new AppInsightsCore();
core.setPerfMgr(manager);
const channel = new ChannelPlugin();
core.initialize({
instrumentationKey: 'testIkey',
} as IConfiguration, [channel]);
const element = document.createElement('a');
let markSpy = this.sandbox.spy(window.performance, 'mark');
let measureSpy = this.sandbox.spy(window.performance, 'measure');
core.track({
name: "Test",
sync: true
} as ITelemetryItem);
Assert.equal(true, markSpy.called);
Assert.equal(true, measureSpy.called);
Assert.equal(true, this._marks.length > 0);
for (let lp = 0; lp < this._marks.length; lp++) {
let mark = this._marks[lp];
// Making sure there are no "end" marks
Assert.equal(0, mark.indexOf("ai.prfmrk."), "Checking mark - " + mark)
Assert.equal(-1, mark.indexOf("ai.prfmrk-end."), "Checking mark - " + mark)
}
Assert.equal(true, this._measures.length > 0);
for (let lp = 0; lp < this._measures.length; lp++) {
let measure = this._measures[lp];
// Making sure the measure mark is correct
Assert.equal(0, measure.name.indexOf("ai.prfmsr."), "Checking measure - " + JSON.stringify(measure));
Assert.equal(0, measure.from.indexOf("ai.prfmrk."), "Checking from measure - " + JSON.stringify(measure));
Assert.equal(undefined, measure.to, "Checking to measure - " + JSON.stringify(measure));
}
}
});
this.testCase({
name: "Disable measure but keep mark",
test: () => {
const manager = new PerfMarkMeasureManager({
useMeasures: false
});
const core = new AppInsightsCore();
core.setPerfMgr(manager);
const channel = new ChannelPlugin();
core.initialize({
instrumentationKey: 'testIkey',
} as IConfiguration, [channel]);
const element = document.createElement('a');
let markSpy = this.sandbox.spy(window.performance, 'mark');
let measureSpy = this.sandbox.spy(window.performance, 'measure');
core.track({
name: "Test",
sync: true
} as ITelemetryItem);
Assert.equal(true, markSpy.called);
Assert.equal(false, measureSpy.called);
Assert.equal(true, this._marks.length > 0);
for (let lp = 0; lp < this._marks.length; lp++) {
let mark = this._marks[lp];
// Making sure there are no "end" marks
Assert.equal(0, mark.indexOf("ai.prfmrk."), "Checking mark - " + mark)
Assert.equal(-1, mark.indexOf("ai.prfmrk-end."), "Checking mark - " + mark)
}
Assert.equal(0, this._measures.length);
}
});
this.testCase({
name: "Disable measure but use end marks",
test: () => {
const manager = new PerfMarkMeasureManager({
useMeasures: false,
useEndMarks: true
});
const core = new AppInsightsCore();
core.setPerfMgr(manager);
const channel = new ChannelPlugin();
core.initialize({
instrumentationKey: 'testIkey',
} as IConfiguration, [channel]);
const element = document.createElement('a');
let markSpy = this.sandbox.spy(window.performance, 'mark');
let measureSpy = this.sandbox.spy(window.performance, 'measure');
core.track({
name: "Test",
sync: true
} as ITelemetryItem);
Assert.equal(true, markSpy.called);
Assert.equal(false, measureSpy.called);
Assert.equal(true, this._marks.length > 0);
let numStart = 0;
let numEnd = 0;
for (let lp = 0; lp < this._marks.length; lp++) {
let mark = this._marks[lp];
if (mark.indexOf("ai.prfmrk.") !== -1) {
numStart++;
let foundEnd = false;
for (let lp2 = lp + 1; lp2 < this._marks.length; lp2++) {
if (this._marks[lp2].indexOf("ai.prfmrk-end." + mark.substring(10)) !== -1) {
foundEnd = true;
break;
}
}
Assert.equal(true, foundEnd, "Expect to find and end mark for " + mark);
}
if (mark.indexOf("ai.prfmrk-end.") !== -1) {
numEnd++;
}
}
Assert.equal(numStart, numEnd, "Should be same number of start and end marks");
Assert.equal(0, this._measures.length);
}
});
this.testCase({
name: "Disable marks but keep measure",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: false
});
const core = new AppInsightsCore();
core.setPerfMgr(manager);
const channel = new ChannelPlugin();
core.initialize({
instrumentationKey: 'testIkey',
} as IConfiguration, [channel]);
const element = document.createElement('a');
let markSpy = this.sandbox.spy(window.performance, 'mark');
let measureSpy = this.sandbox.spy(window.performance, 'measure');
core.track({
name: "Test",
sync: true
} as ITelemetryItem);
Assert.equal(false, markSpy.called);
Assert.equal(true, measureSpy.called);
Assert.equal(0, this._marks.length, "No Marks expected");
for (let lp = 0; lp < this._measures.length; lp++) {
let measure = this._measures[lp];
// Making sure the measure mark is correct
Assert.equal(0, measure.name.indexOf("ai.prfmsr."), "Checking measure - " + JSON.stringify(measure));
Assert.equal(undefined, measure.from, "Checking from measure - " + JSON.stringify(measure));
Assert.equal(undefined, measure.to, "Checking to measure - " + JSON.stringify(measure));
}
}
});
this.testCase({
name: "Enable start and end marks with measure",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true,
useMeasures: true
});
const core = new AppInsightsCore();
core.setPerfMgr(manager);
const channel = new ChannelPlugin();
core.initialize({
instrumentationKey: 'testIkey',
} as IConfiguration, [channel]);
const element = document.createElement('a');
let markSpy = this.sandbox.spy(window.performance, 'mark');
let measureSpy = this.sandbox.spy(window.performance, 'measure');
core.track({
name: "Test",
sync: true
} as ITelemetryItem);
Assert.equal(true, markSpy.called);
Assert.equal(true, measureSpy.called);
Assert.equal(true, this._marks.length > 0);
let numStart = 0;
let numEnd = 0;
for (let lp = 0; lp < this._marks.length; lp++) {
let mark = this._marks[lp];
if (mark.indexOf("ai.prfmrk.") !== -1) {
numStart++;
let foundEnd = false;
for (let lp2 = lp + 1; lp2 < this._marks.length; lp2++) {
if (this._marks[lp2].indexOf("ai.prfmrk-end." + mark.substring(10)) !== -1) {
foundEnd = true;
break;
}
}
Assert.equal(true, foundEnd, "Expect to find and end mark for " + mark);
}
if (mark.indexOf("ai.prfmrk-end.") !== -1) {
numEnd++;
}
}
Assert.equal(numStart, numEnd, "Should be same number of start and end marks");
Assert.equal(true, this._measures.length > 0);
for (let lp = 0; lp < this._measures.length; lp++) {
let measure = this._measures[lp];
// Making sure the measure mark is correct
Assert.equal(0, measure.name.indexOf("ai.prfmsr."), "Checking measure - " + JSON.stringify(measure));
Assert.equal(0, measure.from.indexOf("ai.prfmrk." + measure.name.substring(10)), "Checking from measure - " + JSON.stringify(measure));
Assert.equal(0, measure.to.indexOf("ai.prfmrk-end." + measure.name.substring(10)), "Checking to measure - " + JSON.stringify(measure));
}
}
});
this.testCase({
name: "Enable start and end marks with measure with unique names",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true,
useMeasures: true,
uniqueNames: true
});
const core = new AppInsightsCore();
core.setPerfMgr(manager);
const channel = new ChannelPlugin();
core.initialize({
instrumentationKey: 'testIkey',
} as IConfiguration, [channel]);
const element = document.createElement('a');
let markSpy = this.sandbox.spy(window.performance, 'mark');
let measureSpy = this.sandbox.spy(window.performance, 'measure');
core.track({
name: "Test1",
sync: true
} as ITelemetryItem);
core.track({
name: "Test2",
sync: true
} as ITelemetryItem);
Assert.equal(true, markSpy.called);
Assert.equal(true, measureSpy.called);
Assert.equal(true, this._marks.length > 0);
let numStart = 0;
let numEnd = 0;
for (let lp = 0; lp < this._marks.length; lp++) {
let mark = this._marks[lp];
if (mark.indexOf("ai.prfmrk.") !== -1) {
numStart++;
Assert.notEqual(-1, "0123456789".indexOf(mark[10]), "Make sure there is a numeric value for " + mark);
let foundEnd = false;
for (let lp2 = lp + 1; lp2 < this._marks.length; lp2++) {
if (this._marks[lp2].indexOf("ai.prfmrk-end." + mark.substring(10)) !== -1) {
foundEnd = true;
break;
}
}
Assert.equal(true, foundEnd, "Expect to find and end mark for " + mark);
}
if (mark.indexOf("ai.prfmrk-end.") !== -1) {
numEnd++;
}
}
Assert.equal(numStart, numEnd, "Should be same number of start and end marks");
Assert.equal(true, this._measures.length > 0);
for (let lp = 0; lp < this._measures.length; lp++) {
let measure = this._measures[lp];
// Making sure the measure mark is correct
Assert.equal(0, measure.name.indexOf("ai.prfmsr."), "Checking measure - " + JSON.stringify(measure));
Assert.equal(0, measure.from.indexOf("ai.prfmrk." + measure.name.substring(10)), "Checking from measure - " + JSON.stringify(measure));
Assert.equal(0, measure.to.indexOf("ai.prfmrk-end." + measure.name.substring(10)), "Checking to measure - " + JSON.stringify(measure));
}
}
});
this.testCase({
name: "Test with direct doPerf() usage with defaults",
test: () => {
const manager = new PerfMarkMeasureManager();
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test1", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.test1", this._marks[0]);
});
Assert.equal(1, this._marks.length);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.test1", this._measures[0].name);
Assert.equal("ai.prfmrk.test1", this._measures[0].from);
Assert.equal(undefined, this._measures[0].to);
}
});
this.testCase({
name: "Test with direct doPerf(): Specific enable start marks",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.test", this._marks[0]);
});
Assert.equal(1, this._marks.length);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.test", this._measures[0].name);
Assert.equal("ai.prfmrk.test", this._measures[0].from);
Assert.equal(undefined, this._measures[0].to);
}
});
this.testCase({
name: "Test with direct doPerf(): Specific enable start marks with unique",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
uniqueNames: true
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.0.test", this._marks[0]);
});
Assert.equal(1, this._marks.length);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.0.test", this._measures[0].name);
Assert.equal("ai.prfmrk.0.test", this._measures[0].from);
Assert.equal(undefined, this._measures[0].to);
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(2, this._marks.length);
Assert.equal("ai.prfmrk.1.test2", this._marks[1]);
});
Assert.equal(2, this._marks.length);
Assert.equal(2, this._measures.length);
Assert.equal("ai.prfmsr.1.test2", this._measures[1].name);
Assert.equal("ai.prfmrk.1.test2", this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
}
});
this.testCase({
name: "Test with direct doPerf(): with start and end marks",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.test", this._marks[0]);
});
Assert.equal(2, this._marks.length);
Assert.equal("ai.prfmrk-end.test", this._marks[1]);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.test", this._measures[0].name);
Assert.equal("ai.prfmrk.test", this._measures[0].from);
Assert.equal("ai.prfmrk-end.test", this._measures[0].to);
}
});
this.testCase({
name: "Test with direct doPerf(): with start and end marks with unique",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true,
uniqueNames: true
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.0.test", this._marks[0]);
});
Assert.equal(2, this._marks.length);
Assert.equal("ai.prfmrk-end.0.test", this._marks[1]);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.0.test", this._measures[0].name);
Assert.equal("ai.prfmrk.0.test", this._measures[0].from);
Assert.equal("ai.prfmrk-end.0.test", this._measures[0].to);
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(3, this._marks.length);
Assert.equal("ai.prfmrk.1.test2", this._marks[2]);
});
Assert.equal(4, this._marks.length);
Assert.equal("ai.prfmrk-end.1.test2", this._marks[3]);
Assert.equal(2, this._measures.length);
Assert.equal("ai.prfmsr.1.test2", this._measures[1].name);
Assert.equal("ai.prfmrk.1.test2", this._measures[1].from);
Assert.equal("ai.prfmrk-end.1.test2", this._measures[1].to);
}
});
this.testCase({
name: "Test with direct doPerf(): Disable Marks",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: false
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(0, this._marks.length);
});
Assert.equal(0, this._marks.length);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.test2", this._measures[0].name);
Assert.equal(undefined, this._measures[0].from);
Assert.equal(undefined, this._measures[0].to);
}
});
this.testCase({
name: "Test with direct doPerf(): Disable Marks with unique",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: false,
uniqueNames: true
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(0, this._marks.length);
});
Assert.equal(0, this._marks.length);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.0.test2", this._measures[0].name);
Assert.equal(undefined, this._measures[0].from);
Assert.equal(undefined, this._measures[0].to);
doPerf(manager, () => "test3", (perfEvent) => {
Assert.equal(0, this._marks.length);
});
Assert.equal(0, this._marks.length);
Assert.equal(2, this._measures.length);
Assert.equal("ai.prfmsr.1.test3", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
}
});
this.testCase({
name: "Test with direct doPerf(): Disable Measures",
test: () => {
const manager = new PerfMarkMeasureManager({
useMeasures: false
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test3", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.test3", this._marks[0]);
});
Assert.equal(1, this._marks.length);
Assert.equal(0, this._measures.length);
}
});
this.testCase({
name: "Test with direct doPerf(): Disable Measures with unique",
test: () => {
const manager = new PerfMarkMeasureManager({
useMeasures: false,
uniqueNames: true
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test3", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.0.test3", this._marks[0]);
});
Assert.equal(1, this._marks.length);
Assert.equal(0, this._measures.length);
doPerf(manager, () => "test4", (perfEvent) => {
Assert.equal(2, this._marks.length);
Assert.equal("ai.prfmrk.1.test4", this._marks[1]);
});
Assert.equal(2, this._marks.length);
Assert.equal(0, this._measures.length);
}
});
this.testCase({
name: "Test with direct doPerf(): with mark name map",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true,
markNameMap: {
"test": "mapped1",
"test3": "mapped3"
}
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.mapped1", this._marks[0]);
});
Assert.equal(2, this._marks.length);
Assert.equal("ai.prfmrk-end.mapped1", this._marks[1]);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.mapped1", this._measures[0].name);
Assert.equal("ai.prfmrk.mapped1", this._measures[0].from);
Assert.equal("ai.prfmrk-end.mapped1", this._measures[0].to);
// Unmapped name is dropped
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(2, this._marks.length);
});
Assert.equal(2, this._marks.length);
Assert.equal(1, this._measures.length);
doPerf(manager, () => "test3", (perfEvent) => {
Assert.equal(3, this._marks.length);
Assert.equal("ai.prfmrk.mapped3", this._marks[2]);
});
Assert.equal(4, this._marks.length);
Assert.equal("ai.prfmrk-end.mapped3", this._marks[3]);
Assert.equal(2, this._measures.length);
Assert.equal("ai.prfmsr.mapped3", this._measures[1].name);
Assert.equal("ai.prfmrk.mapped3", this._measures[1].from);
Assert.equal("ai.prfmrk-end.mapped3", this._measures[1].to);
}
});
this.testCase({
name: "Test with direct doPerf(): with mark name map with unique",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true,
uniqueNames: true,
markNameMap: {
"test": "mapped1",
"test3": "mapped3"
}
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.0.mapped1", this._marks[0]);
});
Assert.equal(2, this._marks.length);
Assert.equal("ai.prfmrk-end.0.mapped1", this._marks[1]);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.0.mapped1", this._measures[0].name);
Assert.equal("ai.prfmrk.0.mapped1", this._measures[0].from);
Assert.equal("ai.prfmrk-end.0.mapped1", this._measures[0].to);
// Unmapped name is dropped
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(2, this._marks.length);
});
Assert.equal(2, this._marks.length);
Assert.equal(1, this._measures.length);
doPerf(manager, () => "test3", (perfEvent) => {
Assert.equal(3, this._marks.length);
Assert.equal("ai.prfmrk.2.mapped3", this._marks[2]);
});
Assert.equal(4, this._marks.length);
Assert.equal("ai.prfmrk-end.2.mapped3", this._marks[3]);
Assert.equal(2, this._measures.length);
Assert.equal("ai.prfmsr.2.mapped3", this._measures[1].name);
Assert.equal("ai.prfmrk.2.mapped3", this._measures[1].from);
Assert.equal("ai.prfmrk-end.2.mapped3", this._measures[1].to);
}
});
this.testCase({
name: "Test with direct doPerf(): with mark name map and measure map",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true,
markNameMap: {
"test": "mapped1",
"test3": "mapped3"
},
measureNameMap: {
"test": "measure1",
"test2": "measure2"
}
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.mapped1", this._marks[0]);
});
Assert.equal(2, this._marks.length);
Assert.equal("ai.prfmrk-end.mapped1", this._marks[1]);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.measure1", this._measures[0].name);
Assert.equal("ai.prfmrk.mapped1", this._measures[0].from);
Assert.equal("ai.prfmrk-end.mapped1", this._measures[0].to);
// Unmapped name is dropped
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(2, this._marks.length);
});
Assert.equal(2, this._marks.length);
Assert.equal(2, this._measures.length);
Assert.equal("ai.prfmsr.measure2", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
doPerf(manager, () => "test3", (perfEvent) => {
Assert.equal(3, this._marks.length);
Assert.equal("ai.prfmrk.mapped3", this._marks[2]);
});
Assert.equal(4, this._marks.length);
Assert.equal("ai.prfmrk-end.mapped3", this._marks[3]);
Assert.equal(2, this._measures.length);
Assert.equal("ai.prfmsr.measure2", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
}
});
this.testCase({
name: "Test with direct doPerf(): with mark name map and measure map with unique",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true,
uniqueNames: true,
markNameMap: {
"test": "mapped1",
"test3": "mapped3"
},
measureNameMap: {
"test": "measure1",
"test2": "measure2"
}
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("ai.prfmrk.0.mapped1", this._marks[0]);
});
Assert.equal(2, this._marks.length);
Assert.equal("ai.prfmrk-end.0.mapped1", this._marks[1]);
Assert.equal(1, this._measures.length);
Assert.equal("ai.prfmsr.0.measure1", this._measures[0].name);
Assert.equal("ai.prfmrk.0.mapped1", this._measures[0].from);
Assert.equal("ai.prfmrk-end.0.mapped1", this._measures[0].to);
// Unmapped name is dropped
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(2, this._marks.length);
});
Assert.equal(2, this._marks.length);
Assert.equal(2, this._measures.length);
Assert.equal("ai.prfmsr.1.measure2", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
doPerf(manager, () => "test3", (perfEvent) => {
Assert.equal(3, this._marks.length);
Assert.equal("ai.prfmrk.2.mapped3", this._marks[2]);
});
Assert.equal(4, this._marks.length);
Assert.equal("ai.prfmrk-end.2.mapped3", this._marks[3]);
Assert.equal(2, this._measures.length);
Assert.equal("ai.prfmsr.1.measure2", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
}
});
this.testCase({
name: "Test with direct doPerf(): with mark name map, measure map and prefixes",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true,
markPrefix: "tst.mark.",
markEndPrefix: "tst.markend.",
measurePrefix: "tst.measure.",
markNameMap: {
"test": "mapped1",
"test3": "mapped3"
},
measureNameMap: {
"test": "measure1",
"test2": "measure2"
}
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("tst.mark.mapped1", this._marks[0]);
});
Assert.equal(2, this._marks.length);
Assert.equal("tst.markend.mapped1", this._marks[1]);
Assert.equal(1, this._measures.length);
Assert.equal("tst.measure.measure1", this._measures[0].name);
Assert.equal("tst.mark.mapped1", this._measures[0].from);
Assert.equal("tst.markend.mapped1", this._measures[0].to);
// Unmapped name is dropped
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(2, this._marks.length);
});
Assert.equal(2, this._marks.length);
Assert.equal(2, this._measures.length);
Assert.equal("tst.measure.measure2", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
doPerf(manager, () => "test3", (perfEvent) => {
Assert.equal(3, this._marks.length);
Assert.equal("tst.mark.mapped3", this._marks[2]);
});
Assert.equal(4, this._marks.length);
Assert.equal("tst.markend.mapped3", this._marks[3]);
Assert.equal(2, this._measures.length);
Assert.equal("tst.measure.measure2", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
}
});
this.testCase({
name: "Test with direct doPerf(): with mark name map and measure map with unique",
test: () => {
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true,
uniqueNames: true,
markPrefix: "tst.mark.",
markEndPrefix: "tst.markend.",
measurePrefix: "tst.measure.",
markNameMap: {
"test": "mapped1",
"test3": "mapped3"
},
measureNameMap: {
"test": "measure1",
"test2": "measure2"
}
});
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(1, this._marks.length);
Assert.equal("tst.mark.0.mapped1", this._marks[0]);
});
Assert.equal(2, this._marks.length);
Assert.equal("tst.markend.0.mapped1", this._marks[1]);
Assert.equal(1, this._measures.length);
Assert.equal("tst.measure.0.measure1", this._measures[0].name);
Assert.equal("tst.mark.0.mapped1", this._measures[0].from);
Assert.equal("tst.markend.0.mapped1", this._measures[0].to);
// Unmapped name is dropped
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(2, this._marks.length);
});
Assert.equal(2, this._marks.length);
Assert.equal(2, this._measures.length);
Assert.equal("tst.measure.1.measure2", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
doPerf(manager, () => "test3", (perfEvent) => {
Assert.equal(3, this._marks.length);
Assert.equal("tst.mark.2.mapped3", this._marks[2]);
});
Assert.equal(4, this._marks.length);
Assert.equal("tst.markend.2.mapped3", this._marks[3]);
Assert.equal(2, this._measures.length);
Assert.equal("tst.measure.1.measure2", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
}
});
this.testCase({
name: "Test with direct doPerf(): with mark name map and measure map with unique using notification manager",
test: () => {
let perfEvents: IPerfEvent[] = [];
const manager = new PerfMarkMeasureManager({
useMarks: true,
useEndMarks: true,
uniqueNames: true,
markPrefix: "tst.mark.",
markEndPrefix: "tst.markend.",
measurePrefix: "tst.measure.",
markNameMap: {
"test": "mapped1",
"test3": "mapped3"
},
measureNameMap: {
"test": "measure1",
"test2": "measure2"
}
},
{
perfEvent: (perfEvent) => {
perfEvents.push(perfEvent);
}
} as INotificationManager);
Assert.equal(0, perfEvents.length);
Assert.equal(0, this._marks.length);
doPerf(manager, () => "test", (perfEvent) => {
Assert.equal(0, perfEvents.length);
Assert.equal(1, this._marks.length);
Assert.equal("tst.mark.0.mapped1", this._marks[0]);
});
Assert.equal(2, this._marks.length);
Assert.equal("tst.markend.0.mapped1", this._marks[1]);
Assert.equal(1, this._measures.length);
Assert.equal("tst.measure.0.measure1", this._measures[0].name);
Assert.equal("tst.mark.0.mapped1", this._measures[0].from);
Assert.equal("tst.markend.0.mapped1", this._measures[0].to);
Assert.equal(1, perfEvents.length);
Assert.equal("test", perfEvents[0].name);
// Unmapped name is dropped
doPerf(manager, () => "test2", (perfEvent) => {
Assert.equal(2, this._marks.length);
});
Assert.equal(2, this._marks.length);
Assert.equal(2, this._measures.length);
Assert.equal("tst.measure.1.measure2", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
Assert.equal(2, perfEvents.length);
Assert.equal("test2", perfEvents[1].name);
doPerf(manager, () => "test3", (perfEvent) => {
Assert.equal(3, this._marks.length);
Assert.equal("tst.mark.2.mapped3", this._marks[2]);
});
Assert.equal(4, this._marks.length);
Assert.equal("tst.markend.2.mapped3", this._marks[3]);
Assert.equal(2, this._measures.length);
Assert.equal("tst.measure.1.measure2", this._measures[1].name);
Assert.equal(undefined, this._measures[1].from);
Assert.equal(undefined, this._measures[1].to);
Assert.equal(3, perfEvents.length);
Assert.equal("test3", perfEvents[2].name);
}
});
}
}
class ChannelPlugin implements IPlugin {
public isFlushInvoked = false;
public isTearDownInvoked = false;
public isResumeInvoked = false;
public isPauseInvoked = false;
public identifier = "Sender";
public priority: number = 1001;
constructor() {
this.processTelemetry = this._processTelemetry.bind(this);
}
public pause(): void {
this.isPauseInvoked = true;
}
public resume(): void {
this.isResumeInvoked = true;
}
public teardown(): void {
this.isTearDownInvoked = true;
}
flush(async?: boolean, callBack?: () => void): void {
this.isFlushInvoked = true;
if (callBack) {
callBack();
}
}
public processTelemetry(env: ITelemetryItem) {}
setNextPlugin(next: any) {
// no next setup
}
public initialize = (config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain) => {
}
private _processTelemetry(env: ITelemetryItem) {
}
} | the_stack |
import { GlobalCarrier, ExternalArgs } from "../interfaces";
import { getKeyStart, getKeyLength } from "./hashmapUtils";
import { stringEncodeInto } from "../stringEncodeInto";
import {
compareStringOrNumberEntriesInPlace,
readNumberOrString,
} from "../store";
import { ENTRY_TYPE } from "../entry-types";
import {
initLinkedList,
linkedListItemInsert,
linkedListItemRemove,
linkedListLowLevelIterator,
linkedListGetValue,
} from "../linkedList/linkedList";
import {
number_size,
string_size,
number_set_all,
string_set_all,
number_value_place,
number_value_ctor,
typeOnly_type_get,
string_charsPointer_get,
hashmap_set_all,
hashmap_CAPACITY_get,
hashmap_ARRAY_POINTER_get,
hashmap_USED_CAPACITY_set,
hashmap_USED_CAPACITY_get,
hashmapNode_KEY_POINTER_get,
hashmapNode_NEXT_NODE_POINTER_place,
hashmapNode_NEXT_NODE_POINTER_get,
hashmapNode_VALUE_POINTER_place,
hashmap_LINKED_LIST_POINTER_get,
hashmap_LINKED_LIST_SIZE_set,
hashmap_LINKED_LIST_SIZE_get,
hashmapNode_set_all,
hashmap_ARRAY_POINTER_set,
hashmap_CAPACITY_set,
hashmapNode_NEXT_NODE_POINTER_set,
hashmap_size,
hashmapNode_size,
hashmapNode_LINKED_LIST_ITEM_POINTER_get,
string_bytesLength_get,
linkedList_END_POINTER_get,
hashmapNode_VALUE_POINTER_get,
} from "../generatedStructs";
import type { Heap } from "../../structsGenerator/consts";
import { stringLengthV2 } from "../stringLengthV2";
import {
hashUint8CodeInPlace,
hashCodeExternalValue,
} from "./hashFunctionsStuff";
export function createHashMap(
carrier: GlobalCarrier,
/**
* number of buckets
*/
initialCapacity = 10
) {
const { heap, allocator } = carrier;
const hashMapMemory = allocator.calloc(hashmap_size);
const arrayMemory = allocator.calloc(
initialCapacity * Uint32Array.BYTES_PER_ELEMENT
);
const linkedListPointer = initLinkedList(carrier);
hashmap_set_all(
heap,
hashMapMemory,
arrayMemory,
linkedListPointer,
0,
initialCapacity,
0
);
return hashMapMemory;
}
/**
* todo: on initial hashmap creating, add fast-path to add values in the beginning of buckets,
* because we know that we won't have duplicate keys
* @returns pointer to 32bit you can use.
*/
export function hashMapInsertUpdateKeyIsPointerReturnNode(
externalArgs: ExternalArgs,
carrier: GlobalCarrier,
mapPointer: number,
keyPointer: number
) {
const { heap, allocator } = carrier;
// allocate all possible needed memory upfront, so we won't oom in the middle of something
// in case of overwrite, we will not need this memory
const memoryForNewNode = allocator.calloc(hashmapNode_size);
let keyDataMemoryStart: number;
let keyDataMemoryLength: number;
if (typeOnly_type_get(heap, keyPointer) === ENTRY_TYPE.NUMBER) {
keyDataMemoryStart = keyPointer + number_value_place;
keyDataMemoryLength = number_value_ctor.BYTES_PER_ELEMENT;
} else {
keyDataMemoryLength = string_bytesLength_get(heap, keyPointer);
keyDataMemoryStart = string_charsPointer_get(heap, keyPointer);
}
const bucket =
hashUint8CodeInPlace(heap.u8, keyDataMemoryStart, keyDataMemoryLength) %
hashmap_CAPACITY_get(heap, mapPointer);
const bucketStartPointer =
hashmap_ARRAY_POINTER_get(heap, mapPointer) +
bucket * Uint32Array.BYTES_PER_ELEMENT;
let ptrToPtrToSaveTheNodeTo = bucketStartPointer;
let iteratedNodePointer =
heap.u32[ptrToPtrToSaveTheNodeTo / Uint32Array.BYTES_PER_ELEMENT];
// todo: share code with hashMapNodeLookup?
while (
iteratedNodePointer !== 0 &&
!compareStringOrNumberEntriesInPlace(
carrier.heap,
hashmapNode_KEY_POINTER_get(heap, iteratedNodePointer),
keyPointer
)
) {
ptrToPtrToSaveTheNodeTo =
iteratedNodePointer + hashmapNode_NEXT_NODE_POINTER_place;
iteratedNodePointer = hashmapNode_NEXT_NODE_POINTER_get(
heap,
iteratedNodePointer
);
}
// bucket was empty, first item added to bucket
if (ptrToPtrToSaveTheNodeTo === bucketStartPointer) {
hashmap_USED_CAPACITY_set(
heap,
mapPointer,
hashmap_USED_CAPACITY_get(heap, mapPointer) + 1
);
}
// found node with same key, return same pointer
if (iteratedNodePointer !== 0) {
// no need this memory
allocator.free(memoryForNewNode);
return iteratedNodePointer;
} else {
iteratedNodePointer = memoryForNewNode;
hashmapNode_set_all(
heap,
iteratedNodePointer,
0,
0,
keyPointer,
linkedListItemInsert(
carrier,
hashmap_LINKED_LIST_POINTER_get(heap, mapPointer),
memoryForNewNode
)
);
heap.u32[ptrToPtrToSaveTheNodeTo / Uint32Array.BYTES_PER_ELEMENT] =
memoryForNewNode;
hashmap_LINKED_LIST_SIZE_set(
heap,
mapPointer,
hashmap_LINKED_LIST_SIZE_get(heap, mapPointer) + 1
);
if (
shouldRehash(
hashmap_CAPACITY_get(heap, mapPointer),
hashmap_USED_CAPACITY_get(heap, mapPointer),
externalArgs.hashMapLoadFactor
)
) {
hashMapRehash(
carrier,
mapPointer,
hashmap_CAPACITY_get(heap, mapPointer) * 2
);
}
return iteratedNodePointer;
}
}
/**
* @returns pointer to 32bit you can use.
*/
export function hashMapInsertUpdate(
externalArgs: ExternalArgs,
carrier: GlobalCarrier,
mapPointer: number,
externalKeyValue: number | string
) {
const { heap, allocator } = carrier;
// allocate all possible needed memory upfront, so we won't oom in the middle of something
// in case of overwrite, we will not need this memory
const memoryForNewNode = allocator.calloc(hashmapNode_size);
let keyMemoryEntryPointer;
let keyDataMemoryStart: number;
let keyDataMemoryLength: number;
if (typeof externalKeyValue === "number") {
keyMemoryEntryPointer = allocator.calloc(number_size);
number_set_all(
carrier.heap,
keyMemoryEntryPointer,
ENTRY_TYPE.NUMBER,
externalKeyValue
);
keyDataMemoryStart = keyMemoryEntryPointer + number_value_place;
keyDataMemoryLength = number_value_ctor.BYTES_PER_ELEMENT;
} else {
keyMemoryEntryPointer = allocator.calloc(string_size);
keyDataMemoryLength = stringLengthV2(externalKeyValue);
keyDataMemoryStart = allocator.calloc(keyDataMemoryLength);
stringEncodeInto(carrier.heap.u8, keyDataMemoryStart, externalKeyValue);
string_set_all(
carrier.heap,
keyMemoryEntryPointer,
ENTRY_TYPE.STRING,
1,
keyDataMemoryLength,
keyDataMemoryStart
);
}
const bucket =
hashUint8CodeInPlace(heap.u8, keyDataMemoryStart, keyDataMemoryLength) %
hashmap_CAPACITY_get(heap, mapPointer);
const bucketStartPointer =
hashmap_ARRAY_POINTER_get(heap, mapPointer) +
bucket * Uint32Array.BYTES_PER_ELEMENT;
let ptrToPtrToSaveTheNodeTo = bucketStartPointer;
let iteratedNodePointer =
heap.u32[ptrToPtrToSaveTheNodeTo / Uint32Array.BYTES_PER_ELEMENT];
// todo: share code with hashMapNodeLookup?
while (
iteratedNodePointer !== 0 &&
!compareStringOrNumberEntriesInPlace(
carrier.heap,
hashmapNode_KEY_POINTER_get(heap, iteratedNodePointer),
keyMemoryEntryPointer
)
) {
ptrToPtrToSaveTheNodeTo =
iteratedNodePointer + hashmapNode_NEXT_NODE_POINTER_place;
iteratedNodePointer = hashmapNode_NEXT_NODE_POINTER_get(
heap,
iteratedNodePointer
);
}
// bucket was empty, first item added to bucket
if (ptrToPtrToSaveTheNodeTo === bucketStartPointer) {
hashmap_USED_CAPACITY_set(
heap,
mapPointer,
hashmap_USED_CAPACITY_get(heap, mapPointer) + 1
);
}
// found node with same key, return same pointer
if (iteratedNodePointer !== 0) {
// we don't need the new memory
// @todo Free here also the string data
if (
typeOnly_type_get(carrier.heap, keyMemoryEntryPointer) ===
ENTRY_TYPE.STRING
) {
allocator.free(
string_charsPointer_get(carrier.heap, keyMemoryEntryPointer)
);
}
// we don't need to new memory
allocator.free(keyMemoryEntryPointer);
allocator.free(memoryForNewNode);
return iteratedNodePointer + hashmapNode_VALUE_POINTER_place;
} else {
iteratedNodePointer = memoryForNewNode;
hashmapNode_set_all(
heap,
iteratedNodePointer,
0,
0,
keyMemoryEntryPointer,
linkedListItemInsert(
carrier,
hashmap_LINKED_LIST_POINTER_get(heap, mapPointer),
memoryForNewNode
)
);
heap.u32[ptrToPtrToSaveTheNodeTo / Uint32Array.BYTES_PER_ELEMENT] =
memoryForNewNode;
hashmap_LINKED_LIST_SIZE_set(
heap,
mapPointer,
hashmap_LINKED_LIST_SIZE_get(heap, mapPointer) + 1
);
if (
shouldRehash(
hashmap_CAPACITY_get(heap, mapPointer),
hashmap_USED_CAPACITY_get(heap, mapPointer),
externalArgs.hashMapLoadFactor
)
) {
hashMapRehash(
carrier,
mapPointer,
hashmap_CAPACITY_get(heap, mapPointer) * 2
);
}
return iteratedNodePointer + hashmapNode_VALUE_POINTER_place;
}
}
/**
* @returns pointer of the pointer to the found node
*/
export function hashMapNodeLookup(
heap: Heap,
mapPointer: number,
externalKeyValue: number | string
) {
const bucket =
hashCodeExternalValue(externalKeyValue) %
hashmap_CAPACITY_get(heap, mapPointer);
const bucketStartPtrToPtr =
hashmap_ARRAY_POINTER_get(heap, mapPointer) +
bucket * Uint32Array.BYTES_PER_ELEMENT;
let ptrToPtr = bucketStartPtrToPtr;
let iteratedNode =
heap.u32[bucketStartPtrToPtr / Uint32Array.BYTES_PER_ELEMENT];
while (iteratedNode !== 0) {
const keyValue = readNumberOrString(
heap,
hashmapNode_KEY_POINTER_get(heap, iteratedNode)
);
if (keyValue === externalKeyValue) {
return ptrToPtr;
}
ptrToPtr = iteratedNode + hashmapNode_NEXT_NODE_POINTER_place;
iteratedNode = hashmapNode_NEXT_NODE_POINTER_get(heap, iteratedNode);
}
return 0;
}
export function hashMapValueLookup(
heap: Heap,
mapPointer: number,
externalKeyValue: number | string
) {
const nodePtrToPtr = hashMapNodeLookup(heap, mapPointer, externalKeyValue);
if (nodePtrToPtr === 0) {
return 0;
}
return (
heap.u32[nodePtrToPtr / Uint32Array.BYTES_PER_ELEMENT] +
hashmapNode_VALUE_POINTER_place
);
}
/**
* @returns the value pointer of the deleted key
*/
export function hashMapDelete(
carrier: GlobalCarrier,
mapPointer: number,
externalKeyValue: number | string
) {
const { heap, allocator } = carrier;
const foundNodePtrToPtr = hashMapNodeLookup(
heap,
mapPointer,
externalKeyValue
);
if (foundNodePtrToPtr === 0) {
return 0;
}
const nodeToDeletePointer =
heap.u32[foundNodePtrToPtr / Uint32Array.BYTES_PER_ELEMENT];
const valuePointer = nodeToDeletePointer + hashmapNode_VALUE_POINTER_place;
linkedListItemRemove(
carrier,
hashmapNode_LINKED_LIST_ITEM_POINTER_get(heap, nodeToDeletePointer)
);
// remove node from bucket
heap.u32[foundNodePtrToPtr / Uint32Array.BYTES_PER_ELEMENT] =
hashmapNode_NEXT_NODE_POINTER_get(heap, nodeToDeletePointer);
if (
typeOnly_type_get(
heap,
hashmapNode_KEY_POINTER_get(heap, nodeToDeletePointer)
) === ENTRY_TYPE.STRING
) {
allocator.free(
string_charsPointer_get(
heap,
hashmapNode_KEY_POINTER_get(heap, nodeToDeletePointer)
)
);
}
allocator.free(hashmapNode_KEY_POINTER_get(heap, nodeToDeletePointer));
allocator.free(nodeToDeletePointer);
hashmap_LINKED_LIST_SIZE_set(
heap,
mapPointer,
hashmap_LINKED_LIST_SIZE_get(heap, mapPointer) - 1
);
return valuePointer;
}
/**
*
* return pointer to the next node
*/
export function hashMapLowLevelIterator(
heap: Heap,
mapPointer: number,
nodePointerIteratorToken: number
) {
let tokenToUseForLinkedListIterator = 0;
if (nodePointerIteratorToken !== 0) {
tokenToUseForLinkedListIterator = hashmapNode_LINKED_LIST_ITEM_POINTER_get(
heap,
nodePointerIteratorToken
);
}
const pointerToNextLinkedListItem = linkedListLowLevelIterator(
heap,
hashmap_LINKED_LIST_POINTER_get(heap, mapPointer),
tokenToUseForLinkedListIterator
);
if (pointerToNextLinkedListItem === 0) {
return 0;
}
return linkedListGetValue(heap, pointerToNextLinkedListItem);
}
export function hashMapNodePointerToValue(nodePointer: number) {
return nodePointer + hashmapNode_VALUE_POINTER_place;
}
export function hashMapNodePointerToKey(heap: Heap, nodePointer: number) {
return hashmapNode_KEY_POINTER_get(heap, nodePointer);
}
export function hashMapSize(heap: Heap, mapPointer: number) {
return hashmap_LINKED_LIST_SIZE_get(heap, mapPointer);
}
export function hashMapCapacity(heap: Heap, mapPointer: number) {
return hashmap_CAPACITY_get(heap, mapPointer);
}
export function hashMapGetPointersToFreeV2(
heap: Heap,
hashmapPointer: number,
leafAddresses: Set<number>,
addressesToProcessQueue: number[]
) {
leafAddresses.add(hashmapPointer);
leafAddresses.add(hashmap_ARRAY_POINTER_get(heap, hashmapPointer));
leafAddresses.add(hashmap_LINKED_LIST_POINTER_get(heap, hashmapPointer));
leafAddresses.add(
linkedList_END_POINTER_get(
heap,
hashmap_LINKED_LIST_POINTER_get(heap, hashmapPointer)
)
);
let nodeIterator = 0;
while (
(nodeIterator = hashMapLowLevelIterator(
heap,
hashmapPointer,
nodeIterator
)) !== 0
) {
leafAddresses.add(nodeIterator);
leafAddresses.add(
hashmapNode_LINKED_LIST_ITEM_POINTER_get(heap, nodeIterator)
);
addressesToProcessQueue.push(
hashmapNode_KEY_POINTER_get(heap, nodeIterator),
hashmapNode_VALUE_POINTER_get(heap, nodeIterator)
);
}
}
function hashMapRehash(
carrier: GlobalCarrier,
hashmapPointer: number,
newCapacity: number
) {
const { heap, allocator } = carrier;
// we don't use re alloc because we don't need the old values
allocator.free(hashmap_ARRAY_POINTER_get(heap, hashmapPointer));
const biggerArray = carrier.allocator.calloc(
newCapacity * Uint32Array.BYTES_PER_ELEMENT
);
hashmap_ARRAY_POINTER_set(heap, hashmapPointer, biggerArray);
hashmap_CAPACITY_set(heap, hashmapPointer, newCapacity);
hashmap_USED_CAPACITY_set(heap, hashmapPointer, 0);
let pointerToNode = 0;
while (
(pointerToNode = hashMapLowLevelIterator(
heap,
hashmapPointer,
pointerToNode
)) !== 0
) {
hashMapRehashInsert(heap, hashmapPointer, pointerToNode);
}
}
function hashMapRehashInsert(
heap: Heap,
hashmapPointer: number,
nodePointer: number
) {
const bucket =
hashUint8CodeInPlace(
heap.u8,
getKeyStart(heap, hashmapNode_KEY_POINTER_get(heap, nodePointer)),
getKeyLength(heap, hashmapNode_KEY_POINTER_get(heap, nodePointer))
) % hashmap_CAPACITY_get(heap, hashmapPointer);
const bucketStartPointer =
hashmap_ARRAY_POINTER_get(heap, hashmapPointer) +
bucket * Uint32Array.BYTES_PER_ELEMENT;
const prevFirstNodeInBucket =
heap.u32[bucketStartPointer / Uint32Array.BYTES_PER_ELEMENT];
heap.u32[bucketStartPointer / Uint32Array.BYTES_PER_ELEMENT] = nodePointer;
if (prevFirstNodeInBucket !== 0) {
hashmapNode_NEXT_NODE_POINTER_set(heap, nodePointer, prevFirstNodeInBucket);
} else {
hashmapNode_NEXT_NODE_POINTER_set(heap, nodePointer, 0);
hashmap_USED_CAPACITY_set(
heap,
hashmapPointer,
hashmap_USED_CAPACITY_get(heap, hashmapPointer) + 1
);
}
}
function shouldRehash(
buckets: number,
fullBuckets: number,
loadFactor: number
) {
// add proportion check?
// nodesCount
return fullBuckets / buckets > loadFactor;
}
export function* hashmapNodesPointerIterator(heap: Heap, mapPointer: number) {
let iteratorToken = 0;
while (
(iteratorToken = hashMapLowLevelIterator(
heap,
mapPointer,
iteratorToken
)) !== 0
) {
yield iteratorToken;
}
} | the_stack |
import { rsDecode } from './reedsolomon';
import { BitMatrix } from '../BitMatrix';
import { Version, VERSIONS } from './version';
import { bytesDecode, DecodeResult } from './decode';
import { getMaskFunc } from '../../common/MaskPattern';
import { ErrorCorrectionLevel } from '../../common/ErrorCorrectionLevel';
export { DecodeResult };
function numBitsDiffering(x: number, y: number): number {
let z = x ^ y;
let bitCount = 0;
while (z) {
bitCount++;
z &= z - 1;
}
return bitCount;
}
function pushBit(bit: boolean, byte: number): number {
return (byte << 1) | +bit;
}
interface FormatInformation {
dataMask: number;
errorCorrectionLevel: ErrorCorrectionLevel;
}
interface FormatItem {
bits: number;
formatInfo: FormatInformation;
}
const FORMAT_INFO_TABLE: FormatItem[] = [
{ bits: 0x5412, formatInfo: { errorCorrectionLevel: 0, dataMask: 0 } },
{ bits: 0x5125, formatInfo: { errorCorrectionLevel: 0, dataMask: 1 } },
{ bits: 0x5e7c, formatInfo: { errorCorrectionLevel: 0, dataMask: 2 } },
{ bits: 0x5b4b, formatInfo: { errorCorrectionLevel: 0, dataMask: 3 } },
{ bits: 0x45f9, formatInfo: { errorCorrectionLevel: 0, dataMask: 4 } },
{ bits: 0x40ce, formatInfo: { errorCorrectionLevel: 0, dataMask: 5 } },
{ bits: 0x4f97, formatInfo: { errorCorrectionLevel: 0, dataMask: 6 } },
{ bits: 0x4aa0, formatInfo: { errorCorrectionLevel: 0, dataMask: 7 } },
{ bits: 0x77c4, formatInfo: { errorCorrectionLevel: 1, dataMask: 0 } },
{ bits: 0x72f3, formatInfo: { errorCorrectionLevel: 1, dataMask: 1 } },
{ bits: 0x7daa, formatInfo: { errorCorrectionLevel: 1, dataMask: 2 } },
{ bits: 0x789d, formatInfo: { errorCorrectionLevel: 1, dataMask: 3 } },
{ bits: 0x662f, formatInfo: { errorCorrectionLevel: 1, dataMask: 4 } },
{ bits: 0x6318, formatInfo: { errorCorrectionLevel: 1, dataMask: 5 } },
{ bits: 0x6c41, formatInfo: { errorCorrectionLevel: 1, dataMask: 6 } },
{ bits: 0x6976, formatInfo: { errorCorrectionLevel: 1, dataMask: 7 } },
{ bits: 0x1689, formatInfo: { errorCorrectionLevel: 2, dataMask: 0 } },
{ bits: 0x13be, formatInfo: { errorCorrectionLevel: 2, dataMask: 1 } },
{ bits: 0x1ce7, formatInfo: { errorCorrectionLevel: 2, dataMask: 2 } },
{ bits: 0x19d0, formatInfo: { errorCorrectionLevel: 2, dataMask: 3 } },
{ bits: 0x0762, formatInfo: { errorCorrectionLevel: 2, dataMask: 4 } },
{ bits: 0x0255, formatInfo: { errorCorrectionLevel: 2, dataMask: 5 } },
{ bits: 0x0d0c, formatInfo: { errorCorrectionLevel: 2, dataMask: 6 } },
{ bits: 0x083b, formatInfo: { errorCorrectionLevel: 2, dataMask: 7 } },
{ bits: 0x355f, formatInfo: { errorCorrectionLevel: 3, dataMask: 0 } },
{ bits: 0x3068, formatInfo: { errorCorrectionLevel: 3, dataMask: 1 } },
{ bits: 0x3f31, formatInfo: { errorCorrectionLevel: 3, dataMask: 2 } },
{ bits: 0x3a06, formatInfo: { errorCorrectionLevel: 3, dataMask: 3 } },
{ bits: 0x24b4, formatInfo: { errorCorrectionLevel: 3, dataMask: 4 } },
{ bits: 0x2183, formatInfo: { errorCorrectionLevel: 3, dataMask: 5 } },
{ bits: 0x2eda, formatInfo: { errorCorrectionLevel: 3, dataMask: 6 } },
{ bits: 0x2bed, formatInfo: { errorCorrectionLevel: 3, dataMask: 7 } }
];
function buildFunctionPatternMask(version: Version): BitMatrix {
const dimension = 17 + 4 * version.versionNumber;
const matrix = BitMatrix.createEmpty(dimension, dimension);
matrix.setRegion(0, 0, 9, 9, true); // Top left finder pattern + separator + format
matrix.setRegion(dimension - 8, 0, 8, 9, true); // Top right finder pattern + separator + format
matrix.setRegion(0, dimension - 8, 9, 8, true); // Bottom left finder pattern + separator + format
// Alignment patterns
for (const x of version.alignmentPatternCenters) {
for (const y of version.alignmentPatternCenters) {
if (!((x === 6 && y === 6) || (x === 6 && y === dimension - 7) || (x === dimension - 7 && y === 6))) {
matrix.setRegion(x - 2, y - 2, 5, 5, true);
}
}
}
matrix.setRegion(6, 9, 1, dimension - 17, true); // Vertical timing pattern
matrix.setRegion(9, 6, dimension - 17, 1, true); // Horizontal timing pattern
if (version.versionNumber > 6) {
matrix.setRegion(dimension - 11, 0, 3, 6, true); // Version info, top right
matrix.setRegion(0, dimension - 11, 6, 3, true); // Version info, bottom left
}
return matrix;
}
function readCodewords(matrix: BitMatrix, version: Version, formatInfo: FormatInformation): number[] {
const dimension = matrix.height;
const maskFunc = getMaskFunc(formatInfo.dataMask);
const functionPatternMask = buildFunctionPatternMask(version);
let bitsRead = 0;
let currentByte = 0;
const codewords: number[] = [];
// Read columns in pairs, from right to left
let readingUp = true;
for (let columnIndex = dimension - 1; columnIndex > 0; columnIndex -= 2) {
if (columnIndex === 6) {
// Skip whole column with vertical alignment pattern;
columnIndex--;
}
for (let i = 0; i < dimension; i++) {
const y = readingUp ? dimension - 1 - i : i;
for (let columnOffset = 0; columnOffset < 2; columnOffset++) {
const x = columnIndex - columnOffset;
if (!functionPatternMask.get(x, y)) {
bitsRead++;
let bit = matrix.get(x, y);
if (maskFunc(x, y)) {
bit = !bit;
}
currentByte = pushBit(bit, currentByte);
if (bitsRead === 8) {
// Whole bytes
codewords.push(currentByte);
bitsRead = 0;
currentByte = 0;
}
}
}
}
readingUp = !readingUp;
}
return codewords;
}
function readVersion(matrix: BitMatrix): Version | null {
const dimension = matrix.height;
const provisionalVersion = Math.floor((dimension - 17) / 4);
if (provisionalVersion <= 6) {
// 6 and under dont have version info in the QR code
return VERSIONS[provisionalVersion - 1];
}
let topRightVersionBits = 0;
for (let y = 5; y >= 0; y--) {
for (let x = dimension - 9; x >= dimension - 11; x--) {
topRightVersionBits = pushBit(matrix.get(x, y), topRightVersionBits);
}
}
let bottomLeftVersionBits = 0;
for (let x = 5; x >= 0; x--) {
for (let y = dimension - 9; y >= dimension - 11; y--) {
bottomLeftVersionBits = pushBit(matrix.get(x, y), bottomLeftVersionBits);
}
}
let bestDifference = Infinity;
let bestVersion: Version | null = null;
for (const version of VERSIONS) {
if (version.infoBits === topRightVersionBits || version.infoBits === bottomLeftVersionBits) {
return version;
}
let difference = numBitsDiffering(topRightVersionBits, version.infoBits);
if (difference < bestDifference) {
bestVersion = version;
bestDifference = difference;
}
difference = numBitsDiffering(bottomLeftVersionBits, version.infoBits);
if (difference < bestDifference) {
bestVersion = version;
bestDifference = difference;
}
}
// We can tolerate up to 3 bits of error since no two version info codewords will
// differ in less than 8 bits.
if (bestDifference <= 3) {
return bestVersion;
}
return null;
}
function readFormatInformation(matrix: BitMatrix): FormatInformation | null {
let topLeftFormatInfoBits = 0;
for (let x = 0; x <= 8; x++) {
if (x !== 6) {
// Skip timing pattern bit
topLeftFormatInfoBits = pushBit(matrix.get(x, 8), topLeftFormatInfoBits);
}
}
for (let y = 7; y >= 0; y--) {
if (y !== 6) {
// Skip timing pattern bit
topLeftFormatInfoBits = pushBit(matrix.get(8, y), topLeftFormatInfoBits);
}
}
const dimension = matrix.height;
let topRightBottomRightFormatInfoBits = 0;
for (let y = dimension - 1; y >= dimension - 7; y--) {
// bottom left
topRightBottomRightFormatInfoBits = pushBit(matrix.get(8, y), topRightBottomRightFormatInfoBits);
}
for (let x = dimension - 8; x < dimension; x++) {
// top right
topRightBottomRightFormatInfoBits = pushBit(matrix.get(x, 8), topRightBottomRightFormatInfoBits);
}
let bestDifference = Infinity;
let bestFormatInfo: FormatInformation | null = null;
for (const { bits, formatInfo } of FORMAT_INFO_TABLE) {
if (bits === topLeftFormatInfoBits || bits === topRightBottomRightFormatInfoBits) {
return formatInfo;
}
let difference = numBitsDiffering(topLeftFormatInfoBits, bits);
if (difference < bestDifference) {
bestFormatInfo = formatInfo;
bestDifference = difference;
}
if (topLeftFormatInfoBits !== topRightBottomRightFormatInfoBits) {
// also try the other option
difference = numBitsDiffering(topRightBottomRightFormatInfoBits, bits);
if (difference < bestDifference) {
bestFormatInfo = formatInfo;
bestDifference = difference;
}
}
}
// Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits differing means we found a match
if (bestDifference <= 3) {
return bestFormatInfo;
}
return null;
}
interface DataBlock {
codewords: number[];
numDataCodewords: number;
}
function getDataBlocks(codewords: number[], version: Version, errorCorrectionLevel: number): DataBlock[] | null {
const dataBlocks: DataBlock[] = [];
const ecInfo = version.errorCorrectionLevels[errorCorrectionLevel];
let totalCodewords = 0;
ecInfo.ecBlocks.forEach(block => {
for (let i = 0; i < block.numBlocks; i++) {
dataBlocks.push({ numDataCodewords: block.dataCodewordsPerBlock, codewords: [] });
totalCodewords += block.dataCodewordsPerBlock + ecInfo.ecCodewordsPerBlock;
}
});
// In some cases the QR code will be malformed enough that we pull off more or less than we should.
// If we pull off less there's nothing we can do.
// If we pull off more we can safely truncate
if (codewords.length < totalCodewords) {
return null;
}
codewords = codewords.slice(0, totalCodewords);
const shortBlockSize = ecInfo.ecBlocks[0].dataCodewordsPerBlock;
// Pull codewords to fill the blocks up to the minimum size
for (let i = 0; i < shortBlockSize; i++) {
for (const dataBlock of dataBlocks) {
dataBlock.codewords.push(codewords.shift() as number);
}
}
// If there are any large blocks, pull codewords to fill the last element of those
if (ecInfo.ecBlocks.length > 1) {
const smallBlockCount = ecInfo.ecBlocks[0].numBlocks;
const largeBlockCount = ecInfo.ecBlocks[1].numBlocks;
for (let i = 0; i < largeBlockCount; i++) {
dataBlocks[smallBlockCount + i].codewords.push(codewords.shift() as number);
}
}
// Add the rest of the codewords to the blocks. These are the error correction codewords.
while (codewords.length > 0) {
for (const dataBlock of dataBlocks) {
dataBlock.codewords.push(codewords.shift() as number);
}
}
return dataBlocks;
}
function decodeMatrix(matrix: BitMatrix): DecodeResult | null {
const version = readVersion(matrix);
if (version === null) {
return null;
}
const formatInfo = readFormatInformation(matrix);
if (formatInfo === null) {
return null;
}
const codewords = readCodewords(matrix, version, formatInfo);
const dataBlocks = getDataBlocks(codewords, version, formatInfo.errorCorrectionLevel);
if (dataBlocks === null) {
return null;
}
// Count total number of data bytes
const totalBytes = dataBlocks.reduce((a, b) => a + b.numDataCodewords, 0);
const resultBytes = new Uint8ClampedArray(totalBytes);
let resultIndex = 0;
for (const dataBlock of dataBlocks) {
const correctedBytes = rsDecode(dataBlock.codewords, dataBlock.codewords.length - dataBlock.numDataCodewords);
if (correctedBytes === null) {
return null;
}
for (let i = 0; i < dataBlock.numDataCodewords; i++) {
resultBytes[resultIndex++] = correctedBytes[i];
}
}
try {
return bytesDecode(resultBytes, version.versionNumber, formatInfo.errorCorrectionLevel);
} catch {
return null;
}
}
export function decode(matrix: BitMatrix): DecodeResult | null {
const result = decodeMatrix(matrix);
if (result !== null) {
return result;
}
// Decoding didn't work, try mirroring the QR across the topLeft -> bottomRight line.
for (let x = 0; x < matrix.width; x++) {
for (let y = x + 1; y < matrix.height; y++) {
if (matrix.get(x, y) !== matrix.get(y, x)) {
matrix.set(x, y, !matrix.get(x, y));
matrix.set(y, x, !matrix.get(y, x));
}
}
}
return decodeMatrix(matrix);
} | the_stack |
import debounce from 'lodash-es/debounce';
import Vue, { PropType } from 'vue';
import Delete16 from '@carbon/icons-vue/es/delete/16';
import Download16 from '@carbon/icons-vue/es/download/16';
import Settings16 from '@carbon/icons-vue/es/settings/16';
import createVueBindingsFromProps from '../../../.storybook/vue/create-vue-bindings-from-props';
import BXBtn from '../button/button';
import { TABLE_SORT_DIRECTION } from './table-header-cell';
import { rows as demoRows, rowsMany as demoRowsMany, columns as demoColumns, sortInfo as demoSortInfo } from './stories/data';
import { TDemoTableColumn, TDemoTableRow, TDemoSortInfo } from './stories/types';
import {
Default as baseDefault,
expandable as baseExpandable,
sortable as baseSortable,
sortableWithPagination as baseSortableWithPagination,
} from './data-table-story';
export { default } from './data-table-story';
/**
* @param row A table row.
* @param searchString A search string.
* @returns `true` if the given table row matches the given search string.
*/
const doesRowMatchSearchString = (row: TDemoTableRow, searchString: string) =>
Object.keys(row).some(key => key !== 'id' && String(row[key] ?? '').indexOf(searchString) >= 0);
/**
* The map of how sorting direction affects sorting order.
*/
const collationFactors = {
[TABLE_SORT_DIRECTION.ASCENDING]: 1,
[TABLE_SORT_DIRECTION.DESCENDING]: -1,
};
/**
* A class to manage table states, like selection and sorting.
* DEMONSTRATION-PURPOSE ONLY.
* Data/state handling in data table tends to involve lots of application-specific logics
* and thus abstracting everything in a library won't be a good return on investment
* vs. letting users copy code here and implement features that fit their needs.
*/
Vue.component('bx-ce-demo-data-table', {
props: {
/**
* The element ID.
*/
id: String,
/**
* The color scheme.
*/
colorScheme: String,
/**
* The g11n collator to use.
*/
collator: {
default: () => new Intl.Collator(),
},
/**
* Data table columns.
*/
columns: Array as PropType<TDemoTableColumn[]>,
/**
* Data table rows.
*/
rows: Array as PropType<TDemoTableRow[]>,
/**
* Table sorting info.
*/
sortInfo: Object as PropType<TDemoSortInfo>,
/**
* `true` if the the table should support selection UI.
*/
hasSelection: Boolean,
/**
* Number of items per page.
*/
pageSize: Number,
/**
* `true` if the the table should use the compact version of the UI.
*/
size: String,
/**
* The row number where current page start with, index that starts with zero.
*/
start: {
type: Number,
default: 0,
},
},
data: (): {
currentSortInfo?: TDemoSortInfo;
currentStart?: number;
currentPageSize?: number;
handleChangeSearchString: ((() => void) & { cancel(): void }) | void;
searchString: string;
selectedAllInFiltered: boolean;
selectedRowsCountInFiltered: number;
uniqueId: string;
} => ({
/**
* Number of items per page reflecting user-initiated changes.
*/
currentPageSize: undefined,
/**
* The table sorting info reflecting user-initiated changes.
*/
currentSortInfo: undefined,
/**
* The row number where current page start with reflecting user-initiated changes, index that starts with zero.
*/
currentStart: undefined,
/**
* The debounced handler for user-initiated change in search string.
*/
handleChangeSearchString: undefined,
/**
* The search string.
*/
searchString: '',
/**
* `true` if all filtered rows are selected.
*/
selectedAllInFiltered: false,
/**
* The count of the selected filtered rows.
*/
selectedRowsCountInFiltered: 0,
/**
* Unique ID used for ID refs.
*/
uniqueId: Math.random()
.toString(36)
.slice(2),
}),
computed: {
adjustedStart() {
// Referring to another computed property
// @ts-ignore
const { currentStart, currentPageSize, filteredRows } = this;
const { length: count } = filteredRows;
return count === 0 || currentStart! < count
? currentStart!
: Math.max(currentStart! - Math.ceil((currentStart! - count) / currentPageSize!) * currentPageSize!, 0);
},
/**
* @returns A ID prefix for table selection checkbox names.
*/
selectionId() {
const { id: elementId, uniqueId } = this;
return `__bx-ce-demo-data-table_${elementId || uniqueId}`;
},
/**
* @returns The filtered rows.
*/
filteredRows() {
const { rows, searchString } = this;
return !searchString ? rows : rows.filter(row => doesRowMatchSearchString(row, searchString));
},
/**
* @returns The sorted/windowed rows.
*/
rowsInUse() {
// Referring to another computed property
// @ts-ignore
const { currentSortInfo, adjustedStart, currentPageSize = Infinity, filteredRows } = this;
const { columnId: sortColumnId, direction: sortDirection } = currentSortInfo!;
return sortDirection === TABLE_SORT_DIRECTION.NONE
? filteredRows.slice(adjustedStart, adjustedStart! + currentPageSize!)
: filteredRows
.slice()
.sort((lhs, rhs) => collationFactors[sortDirection] * (this as any).compare(lhs[sortColumnId!], rhs[sortColumnId!]))
.slice(adjustedStart, adjustedStart! + currentPageSize!);
},
},
watch: {
pageSize(current: number) {
this.currentPageSize = current;
},
sortInfo(current: TDemoSortInfo) {
this.currentSortInfo = current;
},
start(current: number) {
this.currentStart = current;
},
rows() {
// Vue method reference
// @ts-ignore
this.recomputeSelected();
},
},
filters: {
/**
* @param rowId A row ID.
* @param hasSelection `true` if the table has selection support.
* @param selectionId The unique ID of the table for selection.
* @returns The checkbox ID for row selection.
*/
filterRowSelectionId(rowId: string, hasSelection: boolean, selectionId: string) {
return !hasSelection ? undefined : rowId && `${selectionId}_${rowId}`;
},
/**
* @param column A table column.
* @param sortInfo The table sorting options.
* @returns The table sort direction of the given table column.
*/
filterSortDirection(column: TDemoTableColumn, { columnId, direction }: TDemoSortInfo) {
const { id, sortCycle } = column;
if (!sortCycle) {
return undefined;
}
return id === columnId ? direction : TABLE_SORT_DIRECTION.NONE;
},
},
methods: {
/**
* @param lhs A value.
* @param rhs Another value.
* @returns
* * `0` if the given two values are equal
* * A negative value to sort `lhs` to an index lower than `rhs`
* * A positive value to sort `rhs` to an index lower than `lhs`
*/
compare(lhs, rhs) {
if (typeof lhs === 'number' && typeof rhs === 'number') {
return lhs - rhs;
}
return (this as any).collator.compare(lhs, rhs);
},
/**
* Handles Cancel button in batch action bar.
*/
handleCancelSelection() {
const { searchString } = this;
this.rows!.forEach(row => {
if (!searchString || doesRowMatchSearchString(row, searchString)) {
row.selected = false;
}
});
this.selectedRowsCountInFiltered = 0;
this.selectedAllInFiltered = false;
},
/**
* Handles user-initiated change in search string.
*/
handleChangeSearchStringImpl({ detail }: CustomEvent) {
this.searchString = detail.value;
// Vue method reference
// @ts-ignore
this.recomputeSelected();
},
/**
* Handles an event to change in selection of rows, fired from `<bx-table-row>`.
* @param event The event.
*/
// @ts-ignore: Template-only ref
handleChangeSelection({ defaultPrevented, detail, target }: CustomEvent) {
if (!defaultPrevented) {
const { rowId: changedRowId } = (target as HTMLElement).dataset;
const { selected } = detail;
this.rows!.forEach(row => {
if (Number(changedRowId) === row.id) {
row.selected = selected;
}
});
// Vue method reference
// @ts-ignore
this.recomputeSelected();
}
},
/**
* Handles an event to change in selection of all rows, fired from `<bx-table-header-row>`.
* @param event The event.
*/
handleChangeSelectionAll({ defaultPrevented, detail }: CustomEvent) {
if (!defaultPrevented) {
const { selected } = detail;
this.rows!.forEach(row => {
if (doesRowMatchSearchString(row, this.searchString)) {
row.selected = selected;
}
});
// Vue method reference
// @ts-ignore
this.recomputeSelected();
}
},
/**
* Handles an event to sort rows, fired from `<bx-table-header-cell>`.
* @param event The event.
*/
handleChangeSort({ defaultPrevented, detail, target }: CustomEvent) {
if (!defaultPrevented) {
const { columnId } = (target as HTMLElement).dataset;
const { sortDirection: direction } = detail;
if (direction === TABLE_SORT_DIRECTION.NONE && columnId !== 'name') {
// Resets the sorting, given non-primary sorting column has got in non-sorting state
this.currentSortInfo = this.sortInfo;
} else {
// Sets the sorting as user desires
this.currentSortInfo = {
columnId: columnId!,
direction,
};
}
}
},
/**
* Handles `bx-pagination-changed-current` event on the pagination UI.
* @param event The event.
*/
handleChangeStart({ detail }: CustomEvent) {
this.currentStart = detail.start;
},
/**
* Handles `bx-pages-select-changed` event on the pagination UI.
* @param event The event.
*/
handleChangePageSize({ detail }: CustomEvent) {
this.currentPageSize = detail.value;
},
/**
* Handles Delete batch action button.
*/
handleDeleteRows() {
const { rows, searchString } = this;
for (let i = rows.length - 1; i >= 0; --i) {
if (rows[i].selected && doesRowMatchSearchString(rows[i], searchString)) {
rows.splice(i, 1);
}
}
this.selectedRowsCountInFiltered = 0;
this.selectedAllInFiltered = false;
},
/**
* Handles Download batch action button.
* @param event The event triggering this action.
*/
handleDownloadRows({ target }: MouseEvent) {
const { searchString } = this;
const blob = new Blob(
[JSON.stringify(this.rows!.filter(row => row.selected && doesRowMatchSearchString(row, searchString)))],
{ type: 'application/json' }
);
(target as BXBtn).href = URL.createObjectURL(blob);
// Vue method reference
// @ts-ignore
this.handleCancelSelection();
},
/**
* Re-computes `selectedRowsCount` and `selectedAllInFiltered` properties.
*/
recomputeSelected() {
// Vue computed property reference
// @ts-ignore
const { filteredRows } = this;
const selectedRowsCount = filteredRows!.filter(row => row.selected).length;
this.selectedRowsCountInFiltered = selectedRowsCount;
this.selectedAllInFiltered = selectedRowsCount > 0 && selectedRowsCount === filteredRows.length;
},
},
components: {
'delete-16': Delete16,
'download-16': Download16,
'settings-16': Settings16,
},
created() {
// Vue method reference
// @ts-ignore
this.recomputeSelected();
this.currentSortInfo = this.sortInfo;
this.currentStart = this.start;
this.currentPageSize = this.pageSize;
if (this.handleChangeSearchString) {
this.handleChangeSearchString.cancel();
}
// Vue method reference
// @ts-ignore
this.handleChangeSearchString = debounce(this.handleChangeSearchStringImpl, 500);
},
destroyed() {
if (this.handleChangeSearchString) {
this.handleChangeSearchString.cancel();
this.handleChangeSearchString = undefined;
}
},
template: `
<div>
<bx-table-toolbar>
<bx-table-batch-actions
:active="hasSelection && !!selectedRowsCountInFiltered"
:selected-rows-count="selectedRowsCountInFiltered"
@bx-table-batch-actions-cancel-clicked="handleCancelSelection"
>
<bx-btn icon-layout="condensed" @click="handleDeleteRows">Delete <delete-16 slot="icon"></delete-16></bx-btn>
<bx-btn icon-layout="condensed" @click="handleDownloadRows" href="javascript:void 0" download="table-data.json">
Download <download-16 slot="icon"></download-16>
</bx-btn>
</bx-table-batch-actions>
<bx-table-toolbar-content :has-batch-actions="hasSelection && !!selectedRowsCountInFiltered">
<bx-table-toolbar-search @bx-search-input="handleChangeSearchString"></bx-table-toolbar-search>
<bx-overflow-menu>
<settings-16 slot="icon"></settings-16>
<bx-overflow-menu-body>
<bx-overflow-menu-item>
Action 1
</bx-overflow-menu-item>
<bx-overflow-menu-item>
Action 2
</bx-overflow-menu-item>
<bx-overflow-menu-item>
Action 3
</bx-overflow-menu-item>
</bx-overflow-menu-body>
</bx-overflow-menu>
<bx-btn>Primary Button</bx-btn>
</bx-table-toolbar-content>
</bx-table-toolbar>
<bx-table
:size="size"
@bx-table-row-change-selection="handleChangeSelection"
@bx-table-change-selection-all="handleChangeSelectionAll"
@bx-table-header-cell-sort="handleChangeSort"
>
<bx-table-head>
<bx-table-header-row
:selected="selectedAllInFiltered"
:selection-name="!hasSelection ? undefined : selectionId"
:selection-value="!hasSelection ? undefined : selectionId"
>
<bx-table-header-cell
v-for="column in columns"
:key="column.id"
:data-column-id="column.id"
:sort-cycle="column.sortCycle"
:sort-direction="column | filterSortDirection(sortInfo)"
>
{{ column.title }}
</bx-table-header-cell>
</bx-table-header-row>
</bx-table-head>
<bx-table-body :color-scheme="colorScheme">
<bx-table-row
v-for="row in rowsInUse"
:key="row.id"
:data-row-id="row.id"
:selected="hasSelection && row.selected"
:selection-name="row.id | filterRowSelectionId(hasSelection, selectionId)"
:selection-value="!hasSelection ? undefined : 'selected'"
>
<bx-table-cell v-for="column in columns" :key="column.id">{{ row[column.id] }}</bx-table-cell>
</bx-table-row>
</bx-table-body>
</bx-table>
<bx-pagination
v-if="currentPageSize !== undefined"
:page-size="currentPageSize"
:start="adjustedStart"
:total="filteredRows.length"
@bx-pagination-changed-current="handleChangeStart"
@bx-page-sizes-select-changed="handleChangePageSize"
>
<bx-page-sizes-select slot="page-sizes-select">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</bx-page-sizes-select>
<bx-pages-select></bx-pages-select>
</bx-pagination>
</div>
`,
});
export const Default = args => ({
template: `
<bx-table :size="size">
<bx-table-head>
<bx-table-header-row>
<bx-table-header-cell>Name</bx-table-header-cell>
<bx-table-header-cell>Protocol</bx-table-header-cell>
<bx-table-header-cell>Port</bx-table-header-cell>
<bx-table-header-cell>Rule</bx-table-header-cell>
<bx-table-header-cell>Attached Groups</bx-table-header-cell>
<bx-table-header-cell>Status</bx-table-header-cell>
</bx-table-header-row>
</bx-table-head>
<bx-table-body :color-scheme="colorScheme">
<bx-table-row>
<bx-table-cell>Load Balancer 1</bx-table-cell>
<bx-table-cell>HTTP</bx-table-cell>
<bx-table-cell>80</bx-table-cell>
<bx-table-cell>Round Robin</bx-table-cell>
<bx-table-cell>Maureen's VM Groups</bx-table-cell>
<bx-table-cell>Active</bx-table-cell>
</bx-table-row>
<bx-table-row>
<bx-table-cell>Load Balancer 2</bx-table-cell>
<bx-table-cell>HTTP</bx-table-cell>
<bx-table-cell>80</bx-table-cell>
<bx-table-cell>Round Robin</bx-table-cell>
<bx-table-cell>Maureen's VM Groups</bx-table-cell>
<bx-table-cell>Active</bx-table-cell>
</bx-table-row>
<bx-table-row>
<bx-table-cell>Load Balancer 3</bx-table-cell>
<bx-table-cell>HTTP</bx-table-cell>
<bx-table-cell>80</bx-table-cell>
<bx-table-cell>Round Robin</bx-table-cell>
<bx-table-cell>Maureen's VM Groups</bx-table-cell>
<bx-table-cell>Active</bx-table-cell>
</bx-table-row>
</bx-table-body>
</bx-table>
`,
...createVueBindingsFromProps({ ...args?.['bx-table'], ...args?.['bx-table-body'] }),
});
Object.assign(Default, baseDefault);
export const expandable = args => {
const { props = {}, methods = {} } = createVueBindingsFromProps({
...args?.['bx-table'],
...args?.['bx-table-body'],
});
return {
template: `
<bx-table
:size="size"
@bx-table-row-expando-toggled-all="handleExpandRowAll"
@bx-table-row-expando-toggled="handleExpandRow"
>
<bx-table-head>
<bx-table-header-expand-row>
<bx-table-header-cell>Name</bx-table-header-cell>
<bx-table-header-cell>Protocol</bx-table-header-cell>
<bx-table-header-cell>Port</bx-table-header-cell>
<bx-table-header-cell>Rule</bx-table-header-cell>
<bx-table-header-cell>Attached Groups</bx-table-header-cell>
<bx-table-header-cell>Status</bx-table-header-cell>
</bx-table-header-expand-row>
</bx-table-head>
<bx-table-body :zebra="zebra">
<bx-table-expand-row>
<bx-table-cell>Load Balancer 1</bx-table-cell>
<bx-table-cell>HTTP</bx-table-cell>
<bx-table-cell>80</bx-table-cell>
<bx-table-cell>Round Robin</bx-table-cell>
<bx-table-cell>Maureen's VM Groups</bx-table-cell>
<bx-table-cell>Active</bx-table-cell>
</bx-table-expand-row>
<bx-table-expanded-row colspan="7">
<h1>Expandable row content</h1>
<p>Description here</p>
</bx-table-expanded-row>
<bx-table-expand-row>
<bx-table-cell>Load Balancer 2</bx-table-cell>
<bx-table-cell>HTTP</bx-table-cell>
<bx-table-cell>80</bx-table-cell>
<bx-table-cell>Round Robin</bx-table-cell>
<bx-table-cell>Maureen's VM Groups</bx-table-cell>
<bx-table-cell>Active</bx-table-cell>
</bx-table-expand-row>
<bx-table-expanded-row colspan="7">
<h1>Expandable row content</h1>
<p>Description here</p>
</bx-table-expanded-row>
<bx-table-expand-row>
<bx-table-cell>Load Balancer 3</bx-table-cell>
<bx-table-cell>HTTP</bx-table-cell>
<bx-table-cell>80</bx-table-cell>
<bx-table-cell>Round Robin</bx-table-cell>
<bx-table-cell>Maureen's VM Groups</bx-table-cell>
<bx-table-cell>Active</bx-table-cell>
</bx-table-expand-row>
<bx-table-expanded-row colspan="7">
<h1>Expandable row content</h1>
<p>Description here</p>
</bx-table-expanded-row>
</bx-table-body>
</bx-table>
`,
props,
methods: {
...methods,
handleExpandRowAll(event) {
const { currentTarget, detail } = event;
const rows = currentTarget.querySelectorAll('bx-table-expand-row');
Array.prototype.forEach.call(rows, row => {
row.expanded = detail.expanded;
});
},
handleExpandRow(event) {
const { currentTarget } = event;
const headerRow = currentTarget.querySelector('bx-table-header-expand-row');
const rows = currentTarget.querySelectorAll('bx-table-expand-row');
headerRow.expanded = Array.prototype.every.call(rows, row => row.expanded);
},
},
};
};
Object.assign(expandable, baseExpandable);
export const sortable = args => {
const { props = {}, methods = {} } = createVueBindingsFromProps({
...args?.['bx-table'],
...args?.['bx-table-body'],
...args?.['bx-table-row'],
...args?.['bx-header-cell'],
});
return {
template: `
<!-- TODO: Figure out how to style <bx-ce-demo-data-table> -->
<!-- Refer to <bx-ce-demo-data-table> implementation at the top for details -->
<bx-ce-demo-data-table
:rows="demoRows"
:color-scheme="colorScheme"
:columns="demoColumns"
:sortInfo="demoSortInfo"
:hasSelection="hasSelection"
:size="size"
@bx-table-row-change-selection="handleBeforeChangeSelection"
@bx-table-change-selection-all="handleBeforeChangeSelection"
@bx-table-header-cell-sort="handleBeforeSort"
></bx-ce-demo-data-table>
`,
data: () => ({
demoRows,
demoColumns,
demoSortInfo,
}),
props,
methods: (({ onBeforeChangeSelection, onBeforeChangeSelectionAll, onBeforeSort, ...rest }) => {
const handleBeforeChangeSelection = (event: CustomEvent) => {
if (event.type === 'bx-table-change-selection-all') {
onBeforeChangeSelectionAll(event);
} else {
onBeforeChangeSelection(event);
}
};
return {
...rest,
handleBeforeChangeSelection,
handleBeforeSort: onBeforeSort,
};
})(methods),
};
};
Object.assign(sortable, baseSortable);
export const sortableWithPagination = args => {
const { props = {}, methods = {} } = createVueBindingsFromProps({
...args?.['bx-table'],
...args?.['bx-table-body'],
...args?.['bx-table-row'],
...args?.['bx-header-cell'],
});
return {
template: `
<!-- TODO: Figure out how to style <bx-ce-demo-data-table> -->
<!-- Refer to <bx-ce-demo-data-table> implementation at the top for details -->
<bx-ce-demo-data-table
:rows="demoRows"
:columns="demoColumns"
:sortInfo="demoSortInfo"
:color-scheme="colorScheme"
:hasSelection="hasSelection"
:pageSize="5"
:size="size"
:start="0"
@bx-table-row-change-selection="handleBeforeChangeSelection"
@bx-table-change-selection-all="handleBeforeChangeSelection"
@bx-table-header-cell-sort="handleBeforeSort"
></bx-ce-demo-data-table>
`,
data: () => ({
demoRows: demoRowsMany,
demoColumns,
demoSortInfo,
}),
props,
methods: (({ onBeforeChangeSelection, onBeforeChangeSelectionAll, onBeforeSort, ...rest }) => {
const handleBeforeChangeSelection = (event: CustomEvent) => {
if (event.type === 'bx-table-change-selection-all') {
onBeforeChangeSelectionAll(event);
} else {
onBeforeChangeSelection(event);
}
};
return {
...rest,
handleBeforeChangeSelection,
handleBeforeSort: onBeforeSort,
};
})(methods),
};
};
Object.assign(sortableWithPagination, baseSortableWithPagination); | the_stack |
import {
Animatible,
getAnimatibleName,
AnimationEaseCurves,
AnimationProp,
AnimationWrapMode,
AssetContainer,
Context,
EaseCurve,
Guid,
Track
} from '..';
import {
ExportedPromise,
Like,
Patchable,
readPath
} from '../internal';
import { AnimationInternal } from './animationInternal';
/** Options for [[Animation.AnimateTo]]. */
export type AnimateToOptions<T extends Animatible> = {
/** The amount of time in seconds it takes to reach the [[destination]] value. */
duration: number;
/** A collection of property values that should be animated, and the desired final values. */
destination: Partial<Like<T>>;
/** How the values should approach their destinations. Defaults to [[AnimationEaseCurves.Linear]]. */
easing?: EaseCurve;
}
/** A serialized animation definition */
export interface AnimationLike {
/** Generated unique ID of this animation */
id: Guid;
/** The non-unique name of this animation */
name: string;
/** The server time (in milliseconds since the UNIX epoch) when the animation was started */
basisTime: number;
/** The current playback time, based on basis time and speed */
time: number;
/** Playback speed multiplier */
speed: number;
/** When multiple animations play together, this is the relative strength of this instance */
weight: number;
/** What happens when the animation hits the last frame */
wrapMode: AnimationWrapMode;
/** Convenience property for calling [[play]] or [[stop]] */
isPlaying: boolean;
/** The ID of the AnimationData bound to this animation */
dataId: Readonly<Guid>;
/** The IDs of the objects targeted by this animation */
targetIds: Readonly<Guid[]>;
/**
* The length in seconds of the animation. Only populated for animations without data.
* See [[dataId]] and [[AnimationData.duration]].
*/
duration: number;
}
/** A runtime animation */
export class Animation implements AnimationLike, Patchable<AnimationLike> {
/** @hidden */
public internal = new AnimationInternal(this);
private _id: Guid;
/** @inheritdoc */
public get id() { return this._id; }
private _name: string;
/** @inheritdoc */
public get name() { return this._name; }
public set name(val) {
this._name = val;
this.animationChanged('name');
}
private _basisTime = 0;
/** @inheritdoc */
public get basisTime(): number {
if (this.isPlaying && this.speed !== 0) {
return this._basisTime;
} else if (this.speed !== 0) {
return Math.max(0, Date.now() - Math.floor(this.time * 1000 / this.speed));
} else {
return 0;
}
}
public set basisTime(val) {
if (this._basisTime !== val) {
this._basisTime = Math.max(0, val);
this._time = (Date.now() - this._basisTime) * this.speed / 1000;
this.animationChanged('basisTime');
this.animationChanged('time');
}
}
private _time = 0;
/** @inheritdoc */
public get time(): number {
if (!this.isPlaying || this.speed === 0) {
return this._time;
} else {
return (Date.now() - this.basisTime) * this.speed / 1000;
}
}
public set time(val) {
if (this._time !== val) {
this._time = val;
if (this.speed !== 0) {
this._basisTime = Math.max(0, Date.now() - Math.floor(this._time * 1000 / this.speed));
} else {
this._basisTime = 0;
}
this.animationChanged('time');
this.animationChanged('basisTime');
}
}
/** [[time]], correcting for overruns from looping animations. Is always between 0 and [[duration]]. */
public get normalizedTime() {
const dur = this._duration || this.data?.duration() || 0;
let time = this.time % dur;
if (time < 0) {
time += dur;
}
return time;
}
private _speed = 1;
/** @inheritdoc */
public get speed() { return this._speed; }
public set speed(val) {
const curTime = this.time;
this._speed = val;
this.animationChanged('speed');
// recompute stored times such that there is continuity pre- and post-speed change
if (this.isPlaying && this._speed !== 0) {
this._basisTime = Math.max(0, Date.now() - Math.floor(curTime * 1000 / this.speed));
this.animationChanged('basisTime');
} else {
this._time = curTime;
this.animationChanged('time');
}
}
private _weight = 0;
/** @inheritdoc */
public get weight() { return this._weight; }
public set weight(val) {
// Getter for time converts the internal _basisTime var into the corresponding offset time,
// so reassigning it writes this converted time back into the internal _time var.
// This is needed so the paused state is stored correctly.
if (val === 0) {
// eslint-disable-next-line no-self-assign
this.time = this.time;
}
this._weight = val;
this.animationChanged('weight');
}
private _wrapMode = AnimationWrapMode.Once;
/** @inheritdoc */
public get wrapMode() { return this._wrapMode; }
public set wrapMode(val) {
this._wrapMode = val;
this.animationChanged('wrapMode');
}
private _dataId: Guid;
/** @inheritdoc */
public get dataId() { return this._dataId; }
/** The keyframe data bound to this animation */
public get data() { return this.context.asset(this._dataId)?.animationData; }
private _targetIds: Guid[] = [];
/** @inheritdoc */
public get targetIds() { return Object.freeze([...this._targetIds]); }
/** The list of actors targeted by this animation. */
public get targetActors() {
return this.targetIds.map(id => this.context.actor(id)).filter(a => !!a);
}
/** The list of animations targeted by this animation. */
/* public get targetAnimations() {
return this.targetIds.map(id => this.context.animation(id)).filter(a => !!a);
}*/
/** The list of materials targeted by this animation. */
/* public get targetMaterials() {
return this.targetIds.map(id => this.context.asset(id)?.material).filter(a => !!a);
}*/
private _duration: number;
/** @inheritdoc */
public get duration() { return this._duration; }
/**
* Determine if this animation is playing based on the animation's weight. Setting this property calls
* [[play]] and [[stop]] internally.
*/
public get isPlaying() { return this.weight > 0; }
public set isPlaying(val) {
if (val) {
this.play();
} else {
this.stop();
}
}
/** The list of other animations that target this animation, by ID. */
/* public get targetingAnimations() {
return this.context.animations
.filter(anim => anim.targetIds.includes(this.id))
.reduce(
(map, anim) => {
map.set(anim.id, anim);
return map;
},
new Map<Guid, Animation>()
) as ReadonlyMap<Guid, Animation>;
}*/
/** The list of other animations that target this animation, by name. */
/* public get targetingAnimationsByName() {
return this.context.animations
.filter(anim => anim.targetIds.includes(this.id) && anim.name)
.reduce(
(map, anim) => {
map.set(anim.name, anim);
return map;
},
new Map<string, Animation>()
) as ReadonlyMap<string, Animation>;
}*/
/** INTERNAL USE ONLY. Animations are created by loading prefabs with animations on them. */
public constructor(private context: Context, id: Guid) {
this._id = id;
}
/**
* Play the animation by setting its weight to `1`.
* @param reset If true, restart the animation from the beginning.
* Defaults to `true` when `wrapMode` is `Once`, and `false` otherwise.
*/
public play(reset: boolean = null) {
// no-op if already playing
if (this.isPlaying) { return; }
const realReset = reset === true || reset === null && this.wrapMode === AnimationWrapMode.Once;
// can't compute basis time with a zero speed, just leave it where it was
if (this.speed === 0 && realReset) {
this.time = 0;
} else if (this.speed !== 0) {
// Getter for basis time converts the internal _time var into the corresponding basis time,
// so reassigning it writes this converted time back into the internal _basisTime var.
this.basisTime = (realReset ? Date.now() : this.basisTime)
// start slightly in the future so we don't always skip over part of the animation.
+ Math.floor(this.context.conn.quality.latencyMs.value / 1000);
}
this.weight = 1;
}
/**
* Halt the running animation by setting its weight to `0`. Has no effect if the animation is already stopped.
*/
public stop() {
// no-op if already stopped
if (!this.isPlaying) { return; }
this.weight = 0;
}
private _finished: ExportedPromise = null;
/** @returns A promise that resolves when the animation completes. This only occurs if the wrap mode is set
* to "Once". The promise is not resolved if the animation is stopped manually.
*/
public finished(): Promise<void> {
if (this._finished) {
return this._finished.original;
}
const promise = new Promise<void>((resolve, reject) => {
this._finished = { resolve, reject };
});
this._finished.original = promise;
return promise;
}
/**
* Tells whether this animation is an orphan, i.e. its data has been unloaded, or it has no live targets.
* @returns Whether this animation is an orphan.
*/
public isOrphan() {
// anim is unregistered
return this.context.animation(this.id) === null ||
// data is unloaded
(this.dataId && !this.data) ||
// all targets are destroyed/unloaded/unregistered
this.targetIds.every(id =>
this.context.actor(id) === null /*&&
this.context.asset(id) === null &&
this.context.animation(id) === null*/);
}
/** Destroy this animation. */
public delete() {
this.context.internal.destroyAnimation(this.id);
}
/** @hidden */
public toJSON(): AnimationLike {
return {
id: this.id,
name: this.name,
basisTime: this._basisTime,
time: this._time,
speed: this.speed,
weight: this.weight,
wrapMode: this.wrapMode,
isPlaying: this.isPlaying,
dataId: this.dataId,
targetIds: this.targetIds,
duration: this.duration
};
}
/** @hidden */
public copy(patch: Partial<AnimationLike>): this {
if (!patch) { return this; }
this.internal.observing = false;
if (patch.name !== undefined) { this.name = patch.name; }
if (patch.wrapMode) { this.wrapMode = patch.wrapMode; }
if (patch.speed !== undefined) { this.speed = patch.speed; }
if (patch.isPlaying !== undefined) { this.isPlaying = patch.isPlaying; }
if (patch.weight !== undefined) { this.weight = patch.weight; }
if (patch.basisTime !== undefined) { this.basisTime = patch.basisTime; }
if (patch.time !== undefined) { this.time = patch.time; }
if (patch.dataId) { this._dataId = patch.dataId as Guid; }
if (patch.targetIds) { this._targetIds = [...patch.targetIds]; }
if (patch.duration !== undefined) { this._duration = patch.duration; }
this.internal.observing = true;
if (patch.weight === 0 && this._finished) {
this._finished.resolve();
}
return this;
}
private animationChanged(...path: string[]) {
if (this.internal.observing) {
this.context.internal.incrementGeneration();
this.internal.patch = this.internal.patch ?? {} as Partial<AnimationLike>;
readPath(this, this.internal.patch, ...path);
}
}
/**
* Animate an object's properties to a desired final state.
* @param context A valid MRE context.
* @param object The object to animate. Must be either an [[Actor]], an [[Animation]], or a [[Material]].
* @param options How the object should animate.
*/
public static async AnimateTo<T extends Animatible>(
context: Context,
object: T,
options: AnimateToOptions<T>
): Promise<void> {
const tracks = [];
const typeString = getAnimatibleName(object);
if (!typeString) {
throw new Error(`Attempting to animate non-animatible object`);
}
/** Should this object be sent whole instead of by properties */
function isCompleteObject(obj: any) {
return (obj.x !== undefined && obj.y !== undefined && obj.z !== undefined)
|| (obj.r !== undefined && obj.g !== undefined && obj.b !== undefined);
}
/** Recursively search for fields with destinations.
* NOTE: This is all untyped because JS doesn't support types at runtime.
* The function definition guarantees correct types anyway, so shouldn't be a problem.
*/
(function buildTracksRecursively(target: any, path: string) {
for (const field in target) {
if (typeof target[field] === 'object' && !isCompleteObject(target[field])) {
buildTracksRecursively(target[field], `${path}/${field}`);
} else {
// generate a track for each property
tracks.push({
target: `${path}/${field}`,
// generate a single keyframe for the destination
keyframes: [{
time: options.duration,
value: target[field]
}],
easing: options.easing !== undefined ? options.easing : AnimationEaseCurves.Linear
});
}
}
})(options.destination, `${typeString}:target`);
// create the animation data
const ac = new AssetContainer(context);
const data = ac.createAnimationData('temp', {
// force type assumptions
tracks: (tracks as unknown) as Array<Track<AnimationProp>>
});
// bind to the object and play immediately
const anim = await data.bind({ target: object }, {
isPlaying: true,
wrapMode: AnimationWrapMode.Once
});
await anim.finished();
ac.unload();
}
} | the_stack |
export const None = Symbol("None");
export type Option<T> = ((s: (val: T) => T) => T) | typeof None;
export type Some<T> = (val: T) => Option<T>;
export const Some: <T>(val: T) => Option<T> = (val) => (s) => s(val);
export type Result<T, E> = (o: (val: T) => E, s: (val: symbol) => E) => E;
export type Err<T> = T;
export const Err: <A, B>(val: symbol) => Result<A, B> =
(val: symbol) => (_, g) =>
g(val);
export const Ok: <T, E>(val: T) => Result<T, E> = (val) => (f, _) => f(val);
/**
* A generic function with one argument.
*/
export type OneArgFn<T, U> = (value: T) => U;
/**
* A generic function without arguments.
*/
export type NoArgFn<T> = () => T;
/**
* A generic variable for use in match statments.
*/
export const Var = Symbol("Variable");
/**
* A default case for use in match statments.
*/
export const Default = Symbol("Default");
/**
* Returns the contained Ok or Some value.
* Note: Only use if value is not an Err or None as this will throw an error (see unwrap_or).
*
* @param value An `Option<T>` or `Result<T>`.
*/
export function unwrap<T, U>(value: Option<T> | Result<T, U>): T {
if ((value as Option<T>) === None) throw `unwrap on None.`;
else if (
typeof value == "function" &&
(value.toString() === "(s) => s(val)" ||
value.toString() === "(f, _) => f(val)" ||
value.toString() === "(_, g) => g(val)")
) {
return (value as Result<T, T>)(
(val) => val as T,
(val) => {
throw `unwrap on ${val.toString()}.`;
}
);
} else return value as unknown as T;
}
/**
* Either returns the contained Ok/Some value or returns fallback value.
*
* @param value An `Option<T>` or `Result<T,U>`.
* @param fallback Afallback value.
*/
export function unwrapOr<T, U, F>(
value: Option<T> | Result<T, U>,
fallback: F
): T | F {
if ((value as Option<T>) === None) return fallback;
else if (
typeof value == "function" &&
(value.toString() === "(s) => s(val)" ||
value.toString() === "(f, _) => f(val)" ||
value.toString() === "(_, g) => g(val)")
) {
return (value as Result<T, T>)(
(val) => val as T,
() => fallback as unknown as T
);
} else return value as unknown as T;
}
/**
* Returns the contained Some value or computes new value from function.
*
* @param value An `Option<T>` or `Result<T>`.
* @param fn
*/
export function unwrapOrElse<T, U, F>(
value: Option<T> | Result<T, U>,
fn: NoArgFn<F>
): T | F {
if ((value as Option<T>) === None) return fn();
else if (
typeof value == "function" &&
(value.toString() === "(s) => s(val)" ||
value.toString() === "(f, _) => f(val)" ||
value.toString() === "(_, g) => g(val)")
) {
return (value as Result<T, T>)(
(val) => val as T,
() => fn() as unknown as T
);
} else return value as unknown as T;
}
/**
* Maps a Result Option to a new value, leaving Error or None values untouched.
*
* @param value An `Option<T>` or `Result<T>`.
* @param fn
*/
export function map<T, U, F>(
value: Option<T> | Result<T, U>,
fn: OneArgFn<T, F>
): Option<T> | Result<T, U> | T {
if ((value as Option<T>) === None) return value;
else if (
typeof value == "function" &&
(value.toString() === "(s) => s(val)" ||
value.toString() === "(f, _) => f(val)" ||
value.toString() === "(_, g) => g(val)")
) {
return (value as Result<T, T>)(
(val) => fn(val) as unknown as T,
() => value as unknown as T
);
} else return fn(value as unknown as T) as unknown as T;
}
/**
* Either computes a new value or returns fallback value if Err or None.
*
* @param value An `Option<T>` or `Result<T,U>`.
* @param fallback A fallback value.
* @param fn
*/
export function mapOr<T, U, F, E>(
value: Option<T> | Result<T, U>,
fallback: E,
fn: OneArgFn<T, F>
): T | E {
if ((value as Option<T>) === None) return fallback;
else if (
typeof value == "function" &&
(value.toString() === "(s) => s(val)" ||
value.toString() === "(f, _) => f(val)" ||
value.toString() === "(_, g) => g(val)")
) {
return (value as Result<T, T>)(
(val) => fn(val) as unknown as T,
() => fallback as unknown as T
);
} else return fn(value as unknown as T) as unknown as T;
}
/**
* Asserts whether given value is None
*
* @param value A value that is either `Some(T)` or `None`.
*/
export function isNone<T>(value: Option<T>): value is typeof None {
return value === None;
}
/**
* Asserts whether given value is Some.
*
* @param value A value that is either `Some(T)` or `None`.
*/
export function isSome<T>(value: Option<T>): boolean {
return value !== None;
}
/**
* Asserts whether given value is an Error.
*
* @param value A value that is either `Ok` or an `Err`.
*/
export function isErr<T>(value: Result<T, T>): boolean {
return value(
() => false as unknown as T,
() => true as unknown as T
) as unknown as boolean;
}
/**
* Asserts whether given value is Ok.
*
* @param value A value that is either `Ok` or an `Err`.
*/
export function isOk<T>(value: Result<T, T>): boolean {
return value(
() => true as unknown as T,
() => false as unknown as T
) as unknown as boolean;
}
function getDetails<T>(value: unknown): {
callStack: Array<string>;
value: T;
} {
const callStack: Array<string> = [];
let val = value;
// Filter through optional functions until a value is obtained
while (
typeof val == "function" &&
(val.toString() === "(s) => s(val)" ||
val.toString() === "(f, _) => f(val)" ||
val.toString() === "(_, g) => g(val)")
) {
callStack.push(val.toString());
val(
(v: unknown) => (val = v),
(v: unknown) => (val = v)
);
}
if (val == None) callStack.push("None");
if (val == Var) callStack.push("Var");
return { callStack: callStack, value: val as T };
}
/**
* Get the contanied value regardless of whether it is None or Err.
*
* @param value an `Option<T>` or `Result<T,U>`.
*/
export function peek<T>(value: unknown): T {
return getDetails(value).value as T;
}
/**
* A non-exhaustive rust-style match statment.
* Use of generic Var and Default case is pemitted.
*
* @param value An `Option<T>` or `Result<T,U>`.
* @param cases An array of arrays ach containing two elements, a case to match against and a function to run.
*/
export function match<T, U, O>(
value: T,
cases: Array<[Result<U, U> | Option<U> | unknown, OneArgFn<U, O>]>
): void | O {
const valueDetails = getDetails(value);
let found = false;
for (const c of cases) {
const caseDetails = getDetails(c[0]);
if (
JSON.stringify(valueDetails) == JSON.stringify(caseDetails) ||
JSON.stringify([...valueDetails.callStack, "Var"]) ===
JSON.stringify(caseDetails.callStack) ||
(!found && caseDetails.value === Default)
) {
const result = c[1](valueDetails.value as U);
if (result !== undefined) return result;
found = true;
}
}
}
/**
* An exhaustive rust-style match statment.
* Use of generic Var is permitted.
* Note: Function will throw an error if all possible branches are not covered.
*
* @param value An `Option<T>` or `Result<T,U>`.
* @param cases An array of arrays ach containing two elements, a case to match against and a function to run.
*/
export function eMatch<T, U, O>(
value: T,
cases: Array<[Result<U, U> | Option<U> | unknown, OneArgFn<U, O>]>
): void | O {
// Finds all posible cases
function findAllCases<T>(callStack: Array<string>): Array<Array<string>> {
let cases: Array<Array<string>> = [["Var"]];
callStack.reverse().forEach((e) => {
if (e != "Var")
if (e == "(s) => s(val)" || e == "None") {
cases = cases.map((c) => {
return ["(s) => s(val)", ...c];
});
cases.push(["None"]);
} else {
cases = cases.map((c) => {
return ["(f, _) => f(val)", ...c];
});
cases.push(["(_, g) => g(val)", "Var"]);
}
});
// re-revere as this function is called by-value
callStack.reverse();
return cases;
}
// Pretty prints a call stack
function prettyPrint<T>(callStack?: Array<string>, value?: T): string {
const m = new Map<string, string>([
["None", "None"],
["Var", "Var"],
["(s) => s(val)", "Some("],
["(f, _) => f(val)", "Ok("],
["(_, g) => g(val)", "Err("],
]);
let str = "";
callStack?.forEach((e) => {
str += m.get(e);
});
if (callStack?.length !== 0) {
if (
value !== undefined &&
(value as unknown) !==
(callStack as string[])[(callStack as string[]).length - 1]
) {
if (typeof value == "symbol") {
if (value !== Var && value !== None) str += "Symbol";
} else str += JSON.stringify(value);
}
for (let i = 0; i < (callStack as string[]).length; i++) {
str += ")";
}
} else str += `${value}`;
return str;
}
const valueDetails = getDetails(value);
let possibleCases = findAllCases(valueDetails.callStack);
// Test that branches are exhustive
for (const c of cases) {
possibleCases = possibleCases.filter(
(e) =>
JSON.stringify(e) !== JSON.stringify(getDetails(c[0]).callStack)
);
}
// Throw error if cases are non-exhaustive
if (possibleCases.length !== 0) {
let err = `Missing Branches. Case${
possibleCases.length !== 1 ? "s" : ""
}: `;
possibleCases.forEach((e) => {
err += `${prettyPrint(e)}, `;
});
throw `${err}${possibleCases.length === 1 ? "is" : "are"} not covered.`;
}
for (const c of cases) {
const caseDetails = getDetails(c[0]);
if (
JSON.stringify(valueDetails) === JSON.stringify(caseDetails) ||
JSON.stringify([...valueDetails.callStack, "Var"]) ===
JSON.stringify(caseDetails.callStack)
) {
const result = c[1](valueDetails.value as U);
if (result !== undefined) return result;
}
}
} | the_stack |
import React from 'react';
import { ReactD3GraphViz } from '@hikeman/react-graphviz';
import { Row, Col, Card, Popover, Button, Divider, Progress, Modal, Tooltip} from 'antd';
import axios from 'axios';
import { config } from 'ice';
import { GraphvizOptions } from 'd3-graphviz';
import GenerateSchema from 'generate-schema';
import Form from '@rjsf/material-ui';
import {SchemaForm, FormButtonGroup, FormEffectHooks, Submit} from '@formily/antd'
import { merge } from 'rxjs'
import { Input, Select, Upload, Switch } from '@formily/antd-components'
import { ModelStructure, FinetuneConfig, DEFAULT_FINETUNE_CONFIG, DEFAULT_CONFIG_SCHEMA } from './utils/type'
// eslint-disable-next-line @typescript-eslint/no-var-requires
const mockStructure = require('./utils/mock.json');
const defaultOptions: GraphvizOptions = {
fit: true,
height: 700,
width: 800,
zoom: true,
zoomScaleExtent: [0.5, 20],
zoomTranslateExtent: [[-2000, -20000], [1000, 1000]]
};
const components = {
Input,
Select,
Upload,
Switch
}
const { onFieldValueChange$, onFieldInit$ } = FormEffectHooks
type VisualizerProps = { match: any };
type VisualizerState = {
X: number;
Y: number;
currentX: number;
currentY: number;
graphData: string;
isLoaded: boolean;
isValidating: boolean;
modelStructure: ModelStructure;
finetuneConfig: FinetuneConfig;
visible: boolean;
currentLayerName: string;
currentLayerInfo: object;
layerSchema: object;
configSchema: object;
seconds: number;
};
export default class Visualizer extends React.Component<VisualizerProps, VisualizerState> {
constructor(props) {
super(props);
this.state = {
X: 0,
Y: 0,
currentX: 0,
currentY: 0,
seconds: 60,
graphData: '',
isLoaded: false,
isValidating: false,
modelStructure: { layer: {}, connection: {}},
finetuneConfig: DEFAULT_FINETUNE_CONFIG,
visible: false,
currentLayerName: '',
currentLayerInfo: {},
layerSchema: {},
configSchema: DEFAULT_CONFIG_SCHEMA
};
this.timer = 0;
this.showLayerInfo = this.showLayerInfo.bind(this);
this.layerSubmit = this.layerSubmit.bind(this);
this.onMouseMove = this.onMouseMove.bind(this);
this.onLayerChange = this.onLayerChange.bind(this);
this.onConfigChange = this.onConfigChange.bind(this);
this.onClickValidate = this.onClickValidate.bind(this);
this.countDown = this.countDown.bind(this);
}
public async componentDidMount() {
const id: string = this.props.match.params.id;
const graph = await axios.get(`${config.visualizerURL}/${id}`);
this.setState({
isLoaded: true,
graphData: graph.data.dot,
modelStructure: mockStructure
});
}
/**
* update layer info
* @param layer event
*/
public onLayerChange(layer: any){
const properties = {...this.state.layerSchema.properties}
Object.keys(properties).forEach(
(property) => {
properties[property].default = layer.formData[property]
}
)
}
/**
* update finetine job config
* TODO add more config options
* @param e event
*/
public onConfigChange = (config: any)=>{
this.setState(
prevState =>
{
const newConfig = prevState.finetuneConfig
// eslint-disable-next-line @typescript-eslint/camelcase
newConfig.data_module = { ...config.formData, ...newConfig.data_module};
return {finetuneConfig:prevState.finetuneConfig}
}
)
}
/**
* record the mouse position
* @param e event
*/
public onMouseMove(e: any) {
this.setState({ currentX: e.screenX, currentY: e.screenY });
}
/**
* submit finetune job and modified model structures
*/
public configSubmit = async () => {
// submit model structure
const layers = this.state.modelStructure.layer
const updatedLayers = Object.keys(layers).reduce(function (r, e) {
if (layers[e].op_ !== 'E') {
r[e] = layers[e]
}
return r;
}, {})
// TODO add connection update info
const submittedStructure: ModelStructure = { 'layer': updatedLayers, 'connection': {} }
let res = await axios.patch(`${config.structureRefractorURL}/${this.props.match.params.id}`, submittedStructure)
// TODO submit training job
const newConfig = {...this.state.finetuneConfig}
newConfig.model = res.data.id;
res = await axios.post(config.trainerURL, newConfig)
Modal.success({
title: 'Finetune Job Created',
content:
<h6>Your finetune job is submitted successfully<br />
You can visit the following link to check the training status<br />
<a href='/jobs'>Job: {res.data.id}</a>
</h6>
});
}
/**
* update model layer information after submit
*/
public layerSubmit = (layer: any) => {
const modifyMark = { op_: 'M' }
const newConfig = { ...this.state.currentLayerInfo, ...layer.formData, ...modifyMark }
const newStructure = { ...this.state.modelStructure }
newStructure.layer[this.state.currentLayerName] = newConfig
// close the form
this.setState({ visible: false });
}
/**
* display layer settings form after click on the graph
* TODO add default value
*
* @param title layer title
*
*/
public showLayerInfo = (title: string) => {
// TODO validation check of model layer name
if (title.includes('.weight') || title.includes('.bias')) {
const layerName: string = title.replace('.weight', '').replace('.bias', '');
const layersInfo: object = this.state.modelStructure.layer;
if (layerName in layersInfo && layerName !== this.state.currentLayerName) {
const layerInfo = { ...layersInfo[layerName] }
this.setState({ currentLayerInfo: layersInfo[layerName] })
this.setState({ currentLayerName: layerName })
delete layerInfo.op_;
delete layerInfo.type_;
const schema = GenerateSchema.json(`Layer ${layerName}`, layerInfo)
delete schema.$schema
Object.keys(schema.properties).forEach(
(property) =>{
schema.properties[property].default = layerInfo[property]
}
)
// eslint-disable-next-line react/no-access-state-in-setstate
this.setState({ X: this.state.currentX, Y: this.state.currentY })
this.setState({ layerSchema: schema, visible: true, currentLayerName: layerName })
}
}
}
/**
* display data during validating process
*/
public onClickValidate = () =>{
// TODO: pass parameters to validator
this.setState({isValidating: true})
this.setState({seconds: 60})
this.timer = setInterval(this.countDown, 1000);
}
// refer to https://stackoverflow.com/a/40887181
public countDown() {
this.setState(
prevState =>({ seconds: prevState.seconds - 1 })
)
if (this.state.seconds === 0) {
clearInterval(this.timer);
this.setState({isValidating: false})
// TODO: get validate accuracy
}
}
public render() {
return (
<div onMouseMove={this.onMouseMove}>
<Row gutter={16}>
<Col span={15}>
<Card bordered={false}>
<h5 className="MuiTypography-root MuiTypography-h5">Model Structure</h5>
<Divider />
<div id="graphviz">
<Popover
content={
<div>
<Form
schema={this.state.layerSchema}
onSubmit={this.layerSubmit}
onChange={this.onLayerChange}
/>
</div>
}
title="Modify Layer Paramaters"
visible={this.state.visible}
placement="rightTop"
autoAdjustOverflow
overlayStyle={{left: this.state.X + 200, top: this.state.Y - 400}}
overlayInnerStyle={{width: 350, height: 600, overflowY: 'scroll'}}
/>
<ReactD3GraphViz
dot={this.state.isLoaded ? this.state.graphData : 'graph {}'}
options={defaultOptions}
onClick={this.showLayerInfo}
/>
</div>
</Card>
</Col>
<Col span={7} offset={1}>
<Card bordered={false}>
{/* TODO customize the config form */}
<SchemaForm
labelCol={8}
wrapperCol={10}
components={components}
onSubmit={this.configSubmit}
schema={this.state.configSchema}
effects={({ setFieldState }) => {
merge(onFieldValueChange$('dataset'), onFieldInit$('dataset')).subscribe(
fieldState => {
setFieldState('upload', state => {
state.visible = fieldState.value === 'Customized'
})
}
)
}}
>
<div style={{ display: this.state.isValidating || this.state.seconds===0 ? '' : 'none' }}>
<Row>
<span>
Validation Accuracy :
{this.state.seconds===0?
`${0.00} %` // TODO replace with ajax data
: ' In Progress '
}
</span>
</Row>
<Row justify="center" style={{width: '100%'}}>
<Progress
percent={100 - this.state.seconds/60*100}
format={()=>`${this.state.seconds} s`}
/>
</Row>
</div>
<FormButtonGroup offset={2}>
<Tooltip placement="bottom" title="Submit and run finetune Job">
<Submit
type="default"
size="large"
htmlType="submit"
style={{ width: 150 }}
disabled={this.state.isValidating}
>
Start Training
</Submit>
</Tooltip>
<Tooltip placement="bottom" title="Validate accuracy of modified model structure">
<Button
type="default"
size="large"
onClick={this.onClickValidate}
disabled={this.state.isValidating}
style={{ width: 150 }}
>
Fast Validate
</Button>
</Tooltip>
</FormButtonGroup>
</SchemaForm>
</Card>
</Col>
</Row>
</div>
);
};
}; | the_stack |
import * as React from "react";
import { useState } from "react";
import ServiceAndRequest from "./ServiceAndRequest";
import Messages from "./Messages";
import Setup from "./Setup";
import * as pbActions from "../../lib/local/pbActions";
import { Trie } from "../utils/trieClass";
import { parseService } from "../utils/parseService";
import { CallType, RequestConfig, BaseConfig } from "../../lib/local/grpcHandlerFactory";
import * as cloneDeep from "lodash.clonedeep";
import { any } from "prop-types";
interface LeftProps {
handlerContext: [];
tabKey: string;
tabName: string;
filePath: string;
serviceList: {};
messageList: [];
selectedService: string;
selectedRequest: string;
mode: string;
baseConfig: BaseConfig;
requestConfig: RequestConfig<any>;
configElements: {};
configArguments: { arguments: {} };
messageRecommendations: string[];
messageTrie: Trie;
messageTrieInput: string;
requestRecommendations: string[];
requestTrie: Trie;
requestTrieInput: string;
serviceRecommendations: string[];
serviceTrie: Trie;
serviceTrieInput: string;
cleanConfigArgs: { arguments: {} };
getTabState: (state: LeftProps) => { type: string; payload: LeftProps };
updateTabNames: (o: { val: string; tabKey: string }) => void;
setGRPCResponse: ({response: string, tabKey}) => any;
}
enum Mode {
SHOW_SERVICE = "SERVICE_AND_REQUEST",
SHOW_MESSAGES = "MESSAGES",
SHOW_SETUP = "SETUP",
}
export const LeftFactory = (props: LeftProps) => {
let closureState: LeftProps;
if (!closureState) {
closureState = {
tabKey: props.tabKey,
getTabState: props.getTabState,
updateTabNames: props.updateTabNames,
tabName: "New Connection",
handlerContext: [],
filePath: "Upload your proto file to get started",
serviceList: {},
messageList: [],
selectedService: "",
selectedRequest: "",
mode: "SERVICE_AND_REQUEST",
baseConfig: { grpcServerURI: "", packageDefinition: null, packageName: "", serviceName: "", onErrCb: (err) => props.setGRPCResponse({response: err, tabKey: props.tabKey}) },
requestConfig: { requestName: "", callType: null, argument: {}, callbacks: null },
configElements: {},
configArguments: { arguments: {} },
cleanConfigArgs: { arguments: {} },
messageRecommendations: [],
messageTrie: new Trie(),
messageTrieInput: "",
requestRecommendations: [],
requestTrie: new Trie(),
requestTrieInput: "",
serviceRecommendations: [],
serviceTrie: new Trie(),
serviceTrieInput: "",
};
}
function Left(props: LeftProps) {
// state management
const [state, updateState] = useState(closureState);
closureState = state;
state.getTabState({ ...cloneDeep(closureState) });
// user input management
const handleRequestClick = (payload: { service: string; request: string }) => {
const { requestStream, responseStream } = state.serviceList[payload.service][payload.request];
let newConnectType: CallType;
if (requestStream && responseStream) {
newConnectType = CallType.BIDI_STREAM;
} else if (!requestStream && !responseStream) {
newConnectType = CallType.UNARY_CALL;
} else if (requestStream && !responseStream) {
newConnectType = CallType.CLIENT_STREAM;
} else if (!requestStream && responseStream) {
newConnectType = CallType.SERVER_STREAM;
} else {
// @ts-ignore
newConnectType = "ERROR";
}
const newConfigArguments = { arguments: {} };
const newConfigElements = { arguments: {} };
// mutates newConfigArgs and newConfigEles to reflect the proto file
parseService(
state.serviceList[payload.service][payload.request].requestType.type,
newConfigArguments.arguments,
newConfigElements.arguments,
state,
);
updateState({
...state,
selectedService: payload.service,
selectedRequest: payload.request,
configArguments: newConfigArguments,
cleanConfigArgs: cloneDeep(newConfigArguments),
configElements: newConfigElements,
baseConfig: {
...state.baseConfig,
packageName: payload.service.match(/(.+)\./)[1],
serviceName: payload.service.match(/\.(.+)/)[1],
},
requestConfig: {
...state.requestConfig,
requestName: payload.request,
callType: newConnectType,
},
});
};
const handleServiceClick = (payload: { service: string }) => {
//deselects service upon clicking outside of service list
if (payload.service === "") {
updateState({
...state,
selectedService: "",
selectedRequest: "",
baseConfig: { ...state.baseConfig, packageName: "", serviceName: "" },
requestConfig: { ...state.requestConfig, requestName: "", callType: null },
});
}
updateState({
...state,
selectedService: payload.service,
baseConfig: {
...state.baseConfig,
packageName: payload.service.match(/(.+)\./)[1],
serviceName: payload.service.match(/\.(.+)/)[1],
},
});
};
const handleServiceTrie = (val: string) =>
updateState({
...state,
serviceTrieInput: val,
serviceRecommendations: state.serviceTrie.recommend(val),
});
const handleMessageTrie = val =>
updateState({
...state,
messageTrieInput: val,
messageRecommendations: state.messageTrie.recommend(val),
});
const handleRequestTrie = val =>
updateState({
...state,
requestTrieInput: val,
requestRecommendations: state.requestTrie.recommend(val), // NOT YET IMPLEMENTED
});
const handleIPInput = val =>
updateState({
...state,
baseConfig: { ...state.baseConfig, grpcServerURI: val },
});
const handleTabNameChange = val => {
state.updateTabNames({
val: val,
tabKey: state.tabKey,
});
updateState({
...state,
tabName: val,
});
};
const handleProtoUpload = (file: FileList) => {
// handle file
const filePath = file[0].path;
const packageDefinition = pbActions.loadProtoFile(filePath);
if (packageDefinition instanceof Error) {
state.baseConfig.onErrCb(packageDefinition);
throw new Error("Cannot load protofile");
}
const { protoServices, protoMessages } = pbActions.parsePackageDefinition(packageDefinition);
// populate tries
const newServiceTrie = new Trie();
newServiceTrie.insertArrayOfWords(Object.keys(protoServices));
let requestWordsArr: string[] = [];
Object.keys(protoServices).forEach(service => {
requestWordsArr = [...requestWordsArr, ...Object.keys(protoServices[service])];
});
const newRequestTrie = new Trie();
newRequestTrie.insertArrayOfWords(requestWordsArr);
const newMessageTrie = new Trie();
newMessageTrie.insertArrayOfWords(Object.keys(protoMessages));
updateState({
...state,
filePath: filePath,
serviceList: protoServices,
messageList: protoMessages,
serviceTrie: newServiceTrie,
requestTrie: newRequestTrie,
messageTrie: newMessageTrie,
baseConfig: { ...state.baseConfig, packageDefinition: packageDefinition },
});
};
const handleRepeatedClick = payload => {
const keys = payload.id.split(".").slice(1);
function findNestedValue(context, keyArray, clean = false) {
// base case
if (keyArray.length === 1) {
return context;
}
// recu case
if (keyArray[0].match("@")) {
const loc = clean ? 0 : Number(keyArray[0].match(/\d+$/)[0]);
let con = keyArray[0];
con = con.match(/(.+)@/)[1];
return findNestedValue(context[con][loc], keyArray.slice(1), clean);
} else {
return findNestedValue(context[keyArray[0]], keyArray.slice(1), clean);
}
}
// find the correct location
const context = findNestedValue(state.configArguments.arguments, keys);
const cleanContext = findNestedValue(state.cleanConfigArgs.arguments, keys, true);
const baseKey = keys[keys.length - 1].match(/(.+)@/)[1];
const baseLoc = Number(keys[keys.length - 1].match(/\d+$/)[0]);
if (payload.request === "add") {
context[baseKey][context[baseKey].length] = cloneDeep(cleanContext[baseKey][0]);
// context[baseKey][context[baseKey].length - 1] = "";
}
if (payload.request === "remove") {
for (let i = baseLoc; i < context[baseKey].length - 1; i++) {
context[baseKey][i] = context[baseKey][i + 1];
}
context[baseKey].pop();
}
const newConfigArguments = cloneDeep(state.configArguments);
updateState({
...state,
configArguments: newConfigArguments,
});
};
const handleConfigInput = payload => {
const keys = payload.id.split(".").slice(1);
function findNestedValue(context, keyArray) {
// base case
if (keyArray.length === 1) {
return context;
}
// recu case
if (keyArray[0].match("@")) {
const loc = Number(keyArray[0].match(/\d+$/)[0]);
let con = keyArray[0];
con = con.match(/(.+)@/)[1];
return findNestedValue(context[con][loc], keyArray.slice(1));
} else {
return findNestedValue(context[keyArray[0]], keyArray.slice(1));
}
}
// find the correct location
const context = findNestedValue(state.configArguments.arguments, keys);
if (keys[keys.length - 1].includes("@")) {
const key = keys[keys.length - 1].match(/(.+)@/)[1];
const pos = Number(keys[keys.length - 1].match(/\d+$/)[0]);
context[key][pos] = payload.value;
} else {
context[keys[keys.length - 1]] = payload.value;
}
const newConfigArguments = cloneDeep(state.configArguments);
updateState({
...state,
configArguments: newConfigArguments,
});
};
// mode management
const setMode = val => updateState({ ...state, mode: val });
let mode: React.ReactComponentElement<any, {}>;
if (state.mode === Mode.SHOW_SERVICE) {
mode = (
<ServiceAndRequest
{...state}
handleServiceTrie={handleServiceTrie}
handleRequestTrie={handleRequestTrie}
handleRequestClick={handleRequestClick}
handleServiceClick={handleServiceClick}
/>
);
}
if (state.mode === Mode.SHOW_MESSAGES) {
mode = <Messages {...state} handleMessageTrie={handleMessageTrie} />;
}
if (state.mode === Mode.SHOW_SETUP) {
mode = <Setup {...state} handleRepeatedClick={handleRepeatedClick} handleConfigInput={handleConfigInput} />;
}
return (
<div id="tab">
<input
className={"tab-header"}
value={state.tabName}
onClick={() => (process.env.NODE_ENV === "development" ? console.log(state) : null)}
onChange={e => handleTabNameChange(e.target.value)}
style={{ color: "black" }}
/>
<div className="input-header">
<div className="address-box">
<h3>Target Server IP</h3>
<input
type="text"
value={state.baseConfig.grpcServerURI}
placeholder=""
onChange={e => handleIPInput(e.target.value)}
/>
</div>
<div className="upload-box">
<h3>Upload .proto file</h3>
<div className="upload-box-contents">
<div className="file-path">{state.filePath}</div>
<div className="file-path-spacer" />
<label className="file-upload">
UPLOAD
<input type="file" className="hide-me" onChange={e => handleProtoUpload(e.target.files)} />
</label>
</div>
</div>
</div>
<div className="tabs">
<button
onClick={() => setMode(Mode.SHOW_SERVICE)}
className={"service-and-request-button " + (state.mode === Mode.SHOW_SERVICE ? "selected" : "")}
>
SERVICES & REQUESTS
</button>
<button
disabled={Object.keys(state.messageList).length ? false : true}
onClick={() => setMode(Mode.SHOW_MESSAGES)}
className={"messages-button " + (state.mode === Mode.SHOW_MESSAGES ? "selected" : "")}
>
MESSAGES
</button>
<button
disabled={state.selectedRequest ? false : true}
onClick={() => setMode(Mode.SHOW_SETUP)}
className={"req-setup-button " + (state.mode === Mode.SHOW_SETUP ? "selected" : "")}
>
REQUEST SETUP
</button>
</div>
<div className="main">{mode}</div>
</div>
);
}
return <Left key={props.tabKey} {...props} />;
}; | the_stack |
import { getTypeAccessorError } from "./utils/errors";
import { Dict, NNil, Maybe, ReturnType } from "./utils/util-types";
import { transform, forEach, reduce } from "lodash";
import * as t from "io-ts";
import * as types from "./utils/types";
import * as Knex from "knex";
import _debug from "debug";
import { GraphQLInputType, GraphQLOutputType } from "graphql";
import { MappedField } from "./MappedField";
import { FieldMapping } from "./FieldMapping";
import { MappedAssociation } from "./MappedAssociation";
import {
deriveDefaultShallowOutputType,
deriveDefaultOutputType,
deriveDefaultShallowInputType,
derivePaginatedOutputType,
} from "./graphql-type-mapper";
import { assertSupportedConnector, globalConnector, assertConnectorConfigured } from "./utils/connector";
import { MemoizeGetter } from "./utils/utils";
import { StoreQueryParams } from "./SingleSourceQueryOperationResolver";
import { ReverseMapper } from "./ReverseMapper";
import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor";
import { DataSourceMapping } from "./DataSourceMapping";
import { deriveMappedDataSourceName, deriveStoredDataSourceName } from "./utils/conventional-naming";
import { deriveDefaultIdOutputType } from "./graphql-type-mapper";
const debug = _debug("greldal:MappedDataSource");
type AssociationsIn<T extends DataSourceMapping> = ReturnType<NNil<T["associations"]>>;
type FieldsIn<T extends DataSourceMapping> = ReturnType<NNil<T["fields"]>>;
type AssociationKeysIn<T extends DataSourceMapping> = keyof AssociationsIn<T>;
type FieldKeysIn<T extends DataSourceMapping> = keyof FieldsIn<T>;
type AssociatedDataSource<T extends DataSourceMapping, K extends AssociationKeysIn<T>> = AssociationsIn<T>[K]["target"];
type ShallowEntityType<T extends DataSourceMapping> = { [K in FieldKeysIn<T>]: FieldsIn<T>[K]["Type"] };
type NestedEntityType<T extends DataSourceMapping> = ShallowEntityType<T> &
{ [K in AssociationKeysIn<T>]: AssociatedDataSource<T, K>["EntityType"] };
/**
* Represents mapping between a relational data source and associated GraphQL types
* originating from the schema of this data source.
*
* @api-category MapperClass
*/
export class MappedDataSource<T extends DataSourceMapping = any> {
fields: Dict<MappedField>;
associations: Dict<MappedAssociation>;
constructor(private mapping: T) {
this.fields = mapping.fields ? mapping.fields(this) : {};
this.associations = mapping.associations ? mapping.associations(this) : {};
debug(
"Mapped data source with name: %s, fields: %O, associations: %O",
this.mappedName,
Object.keys(this.fields),
Object.keys(this.associations),
);
if (mapping.connector) {
assertSupportedConnector(mapping.connector);
}
}
/**
* Knex instance used to connect to data source.
*
* This can be a data-source specific connector (if provided in the mapping configuration), and if not,
* will fall back to global connector.
*
* Throws if a connector is not found.
*/
get connector(): Knex {
return assertConnectorConfigured(this.mapping.connector || globalConnector);
}
/**
* Get a knex query builder for this data source
*
* This internally aliases tables for ease of reverse-mapping.
*/
rootQueryBuilder(aliasHierarchyVisitor?: Maybe<AliasHierarchyVisitor>): Knex.QueryBuilder {
if (this.mapping.rootQuery) return this.mapping.rootQuery(aliasHierarchyVisitor);
return aliasHierarchyVisitor
? this.connector(`${this.storedName} as ${aliasHierarchyVisitor.alias}`)
: this.connector(this.storedName);
}
/**
* Get list of fields representing columns covered by primary key constraint
*/
get primaryFields() {
return Object.values<MappedField<any>>(this.fields).filter(f => f.isPrimary);
}
get primaryColumnNames() {
return this.primaryFields.map(f => f.sourceColumn!);
}
/**
* Name of the GraphQL output type representing an entity from this data source. Also used in other GraphQL output
* types for this data source.
*/
@MemoizeGetter
get mappedName() {
return deriveMappedDataSourceName(this.mapping.name);
}
/**
* Name of the GraphQL output type representing a shallow entity (containing only fields and not associations) from this data source.
*/
@MemoizeGetter
get shallowMappedName() {
return `Shallow${this.mappedName}`;
}
/**
* Name of the table/view backing this data source
*/
@MemoizeGetter
get storedName() {
return deriveStoredDataSourceName(this.mapping.name);
}
/**
* Name of the GraphQL output type representing a page container that wraps page specific metadata along with
* entities in the page (in a paginated query)
*/
@MemoizeGetter
get pageContainerName() {
return `${this.mappedName}PageContainer`;
}
/**
* Name of the GraphQL output type representing a page container that wraps page specific metadata along with
* shallow entities in the page (in a paginated query)
*/
@MemoizeGetter
get shallowPageContainerName() {
return `${this.shallowMappedName}PageContainer`;
}
/**
* Name of the GraphQL output type representing a page that wraps a subset of result entities (in a paginated query)
*/
@MemoizeGetter
get pageName() {
return `${this.mappedName}Page`;
}
/**
* Name of the GraphQL output type representing a page that wraps a subset of shallow result entities (in a paginated query)
*/
@MemoizeGetter
get shallowPageName() {
return `${this.shallowMappedName}Page`;
}
/**
* List of names of the columns in the data source which are mapped through the fields in the data source mapping
*
* It is not necessary that all columns of backing table are covered by fields of the data source.
*/
@MemoizeGetter
get storedColumnNames(): string[] {
return transform(
this.fields,
(result: string[], field: MappedField<MappedDataSource<T>, FieldMapping<any, any>>) => {
if (field.isMappedFromColumn) {
result.push(field.sourceColumn!);
}
},
[],
);
}
/**
* io-ts type props for field properties of a member entity
*/
@MemoizeGetter
get shallowEntityTypeSpecProps(): Dict<types.AnyTypeSpec> {
return transform(this.fields, (result, field, name) => {
result[name] = field.typeSpec;
return result;
});
}
/**
* io-ts type props for association properties of a member entity
*/
@MemoizeGetter
get associationTypeSpecProps(): Dict<types.AnyTypeSpec> {
const result: Dict<types.AnyTypeSpec> = {};
forEach(this.associations, (association, name) => {
result[name] = association.target.entityType;
});
return transform(
this.associations,
(result: t.Props, association: MappedAssociation<MappedDataSource<T>>, name: string) => {
result[name] = association.target.entityType;
},
{},
);
}
/**
* io-ts type props for all properties (from fields and associations)
*/
@MemoizeGetter
get entityTypeSpecProps(): Dict<types.AnyTypeSpec> {
return {
...this.shallowEntityTypeSpecProps,
...this.associationTypeSpecProps,
};
}
/**
* io-ts runtime type for shallow member entity (excludes associations) from this data source.
*/
@MemoizeGetter
get shallowEntityTypeSpec() {
return types.object(`Shallow${this.mappedName}`, this.shallowEntityTypeSpecProps);
}
/**
* io-ts runtime type for member entity from this data source.
*/
@MemoizeGetter
get entityTypeSpec() {
return types.object(this.mappedName, this.entityTypeSpecProps);
}
/**
* Getter to extract static type of Shallow member entity
*
* This is only useful in maped types. Throws if invoked directly.
*/
get ShallowEntityType(): ShallowEntityType<T> {
throw getTypeAccessorError("ShallowEntityType", "MappedDataSource");
}
/**
* Getter to extract static type of member entity
*
* This is only useful in maped types. Throws if invoked directly.
*/
get EntityType(): NestedEntityType<T> {
throw getTypeAccessorError("NestedEntityType", "MappedDataSource");
}
/**
* Getter to extract static type of the mapping used to configure the data source
*
* This is only useful in maped types. Throws if invoked directly.
*/
get MappingType(): T {
throw getTypeAccessorError("MappingType", "MappedDataSource");
}
/**
* Get the default GraphQL output type for a member entity
*/
@MemoizeGetter
get defaultOutputType(): GraphQLOutputType {
return deriveDefaultOutputType(this);
}
/**
* Get the output type for the response ofa paginated response performed against this data source
*/
@MemoizeGetter
get paginatedOutputType() {
return derivePaginatedOutputType(this.pageContainerName, this.pageName, this.defaultOutputType);
}
/**
* Get the output type for the response of a paginated query (for shallow entities) performed against this data source
*/
@MemoizeGetter
get paginatedShallowOutputType() {
return derivePaginatedOutputType(
this.shallowPageContainerName,
this.shallowPageName,
this.defaultShallowOutputType,
);
}
/**
* Get the default GraphQL input type for a shallow member entity (excludes associations)
*/
@MemoizeGetter
get defaultShallowInputType(): GraphQLInputType {
debug("Deriving default shallow input type for: ", this.mappedName);
return deriveDefaultShallowInputType(this);
}
/**
* Get the default GraphQL output type for a shallow member entity (excludes associations)
*/
@MemoizeGetter
get defaultShallowOutputType(): GraphQLOutputType {
return deriveDefaultShallowOutputType(this);
}
@MemoizeGetter
get defaultIdOutputType(): GraphQLOutputType {
return deriveDefaultIdOutputType(this);
}
/**
* Maps member entities (what the application interacts with) to rows (in the format the persistence layer expects)
*/
mapEntitiesToRows(entities: ShallowEntityType<T>[]): Dict[] {
return entities.map(entity =>
reduce<ShallowEntityType<T>, Dict>(
entity,
(result: Dict, val, key: any) => {
const field = this.fields[key];
if (field) {
return field.updatePartialRow(result, val);
}
return result;
},
{},
),
);
}
/**
* Reverse map the rows obtained from the data source (the persistence layer) to member entities (what the application interacts with)
*/
mapRowsToEntities(rows: Dict[], storeParams: StoreQueryParams<MappedDataSource<T>>) {
return new ReverseMapper(storeParams).reverseMap(rows);
}
/**
* Reverse map the rows obtained from the data source (the persistence layer) to shallow member entities
* (what the application interacts with)
*
* This does not deal with mapping of associations, so is relatively cheaper than mapRowsToEntities
*/
mapRowsToShallowEntities(rows: Dict[]) {
return rows.map(row => {
const mappedRow: Dict = {};
for (const [, field] of Object.entries<MappedField<MappedDataSource<T>, FieldMapping<any, any>>>(
this.fields,
)) {
mappedRow[field.mappedName] = field.getValue(row);
}
return mappedRow;
});
}
/**
* Given a query (entity field name -> value mapping), translates it into a query that the persistence
* layer can process by mapping entity field names to source column names.
*/
mapQueryParams(whereArgs: Dict, aliasHierarchyVisitor: AliasHierarchyVisitor) {
const whereParams: Dict = {};
Object.entries(whereArgs).forEach(([name, arg]) => {
const field: MappedField = (this.fields as any)[name];
if (field) {
whereParams[`${aliasHierarchyVisitor.alias}.${field.sourceColumn}`] = arg;
return;
}
});
return whereParams;
}
}
/**
* Used to map a relational data source using specified configuration (of type [DataSourceMapping](api:DataSourceMapping)).
*
* Refer the guide on [Mapping Data Sources](guide:mapping-data-sources) for detailed explanation and examples.
*
* @api-category PrimaryAPI
*/
export const mapDataSource = <T extends DataSourceMapping>(mapping: T) => new MappedDataSource<T>(mapping); | the_stack |
module es {
export enum LoopType {
none,
restartFromBeginning,
pingpong
}
export enum TweenState {
running,
paused,
complete
}
export abstract class Tween<T> implements ITweenable, ITween<T> {
protected _target: ITweenTarget<T>;
protected _isFromValueOverridden: boolean;
protected _fromValue: T;
protected _toValue: T;
protected _easeType: EaseType;
protected _shouldRecycleTween: boolean = true;
protected _isRelative: boolean;
protected _completionHandler: (tween: ITween<T>) => void;
protected _loopCompleteHandler: (tween: ITween<T>) => void;
protected _nextTween: ITweenable;
protected _tweenState: TweenState = TweenState.complete;
private _isTimeScaleIndependent: boolean;
protected _delay: number;
protected _duration: number;
protected _timeScale: number = 1;
protected _elapsedTime: number;
protected _loopType: LoopType;
protected _loops: number;
protected _delayBetweenLoops: number;
private _isRunningInReverse: boolean;
public context: any;
public setEaseType(easeType: EaseType): ITween<T> {
this._easeType = easeType;
return this;
}
public setDelay(delay: number): ITween<T> {
this._delay = delay;
this._elapsedTime = -this._delay;
return this;
}
public setDuration(duration: number): ITween<T> {
this._duration = duration;
return this;
}
public setTimeScale(timeSclae: number): ITween<T> {
this._timeScale = timeSclae;
return this;
}
public setIsTimeScaleIndependent(): ITween<T> {
this._isTimeScaleIndependent = true;
return this;
}
public setCompletionHandler(completeHandler: (tween: ITween<T>) => void): ITween<T> {
this._completionHandler = completeHandler;
return this;
}
public setLoops(loopType: LoopType, loops: number = 1, delayBetweenLoops: number = 0): ITween<T> {
this._loopType = loopType;
this._delayBetweenLoops = delayBetweenLoops;
if (loops < 0)
loops = -1;
if (loopType == LoopType.pingpong)
loops = loops * 2;
this._loops = loops;
return this;
}
public setLoopCompletionHanlder(loopCompleteHandler: (tween: ITween<T>) => void): ITween<T> {
this._loopCompleteHandler = loopCompleteHandler;
return this;
}
public setFrom(from: T): ITween<T> {
this._isFromValueOverridden = true;
this._fromValue = from;
return this;
}
public prepareForReuse(from: T, to: T, duration: number): ITween<T> {
this.initialize(this._target, to, duration);
return this;
}
public setRecycleTween(shouldRecycleTween: boolean): ITween<T> {
this._shouldRecycleTween = shouldRecycleTween;
return this;
}
public abstract setIsRelative(): ITween<T>;
public setContext(context): ITween<T> {
this.context = context;
return this;
}
public setNextTween(nextTween: ITweenable): ITween<T> {
this._nextTween = nextTween;
return this;
}
public tick(): boolean {
if (this._tweenState == TweenState.paused)
return false;
// 当我们进行循环时,我们会在0和持续时间之间限制数值
let elapsedTimeExcess = 0;
if (!this._isRunningInReverse && this._elapsedTime >= this._duration) {
elapsedTimeExcess = this._elapsedTime - this._duration;
this._elapsedTime = this._duration;
this._tweenState = TweenState.complete;
} else if (this._isRunningInReverse && this._elapsedTime <= 0) {
elapsedTimeExcess = 0 - this._elapsedTime;
this._elapsedTime = 0;
this._tweenState = TweenState.complete;
}
// 当我们延迟开始tween的时候,经过的时间会是负数,所以不要更新这个值。
if (this._elapsedTime >= 0 && this._elapsedTime <= this._duration) {
this.updateValue();
}
// 如果我们有一个loopType,并且我们是Complete(意味着我们达到了0或持续时间)处理循环。
// handleLooping将采取任何多余的elapsedTime,并将其因子化,并在必要时调用udpateValue来保持tween的完美准确性
if (this._loopType != LoopType.none && this._tweenState == TweenState.complete && this._loops != 0) {
this.handleLooping(elapsedTimeExcess);
}
let deltaTime = this._isTimeScaleIndependent ? Time.unscaledDeltaTime : Time.deltaTime;
deltaTime *= this._timeScale;
// 我们需要减去deltaTime
if (this._isRunningInReverse)
this._elapsedTime -= deltaTime;
else
this._elapsedTime += deltaTime;
if (this._tweenState == TweenState.complete) {
this._completionHandler && this._completionHandler(this);
// 如果我们有一个nextTween,把它添加到TweenManager中,这样它就可以开始运行了
if (this._nextTween != null) {
this._nextTween.start();
this._nextTween = null;
}
return true;
}
return false;
}
public recycleSelf() {
if (this._shouldRecycleTween) {
this._target = null;
this._nextTween = null;
}
}
public isRunning(): boolean {
return this._tweenState == TweenState.running;
}
public start() {
if (!this._isFromValueOverridden)
this._fromValue = this._target.getTweenedValue();
if (this._tweenState == TweenState.complete) {
this._tweenState = TweenState.running;
TweenManager.addTween(this);
}
}
public pause() {
this._tweenState = TweenState.paused;
}
public resume() {
this._tweenState = TweenState.running;
}
public stop(bringToCompletion: boolean = false) {
this._tweenState = TweenState.complete;
if (bringToCompletion) {
// 如果我们逆向运行,我们在0处结束,否则我们进入持续时间
this._elapsedTime = this._isRunningInReverse ? 0 : this._duration;
this._loopType = LoopType.none;
this._loops = 0;
// TweenManager将在下一个tick上进行删除处理
} else {
TweenManager.removeTween(this);
}
}
public jumpToElapsedTime(elapsedTime) {
this._elapsedTime = MathHelper.clamp(elapsedTime, 0, this._duration);
this.updateValue();
}
/**
* 反转当前的tween,如果是向前走,就会向后走,反之亦然
*/
public reverseTween() {
this._isRunningInReverse = !this._isRunningInReverse;
}
/**
* 当通过StartCoroutine调用时,这将一直持续到tween完成
*/
public * waitForCompletion() {
while (this._tweenState != TweenState.complete)
yield null;
}
public getTargetObject() {
return this._target.getTargetObject();
}
private resetState() {
this.context = null;
this._completionHandler = this._loopCompleteHandler = null;
this._isFromValueOverridden = false;
this._isTimeScaleIndependent = false;
this._tweenState = TweenState.complete;
// TODO: 我认为在没有得到用户同意的情况下,我们绝对不应该从_shouldRecycleTween=false。需要研究和思考
// this._shouldRecycleTween = true;
this._isRelative = false;
this._easeType = TweenManager.defaultEaseType;
if (this._nextTween != null) {
this._nextTween.recycleSelf();
this._nextTween = null;
}
this._delay = 0;
this._duration = 0;
this._timeScale = 1;
this._elapsedTime = 0;
this._loopType = LoopType.none;
this._delayBetweenLoops = 0;
this._loops = 0;
this._isRunningInReverse = false;
}
/**
* 将所有状态重置为默认值,并根据传入的参数设置初始状态。
* 这个方法作为一个切入点,这样Tween子类就可以调用它,这样tweens就可以被回收。
* 当回收时,构造函数不会再被调用,所以这个方法封装了构造函数要做的事情
* @param target
* @param to
* @param duration
*/
public initialize(target: ITweenTarget<T>, to: T, duration: number) {
// 重置状态,以防我们被回收
this.resetState();
this._target = target;
this._toValue = to;
this._duration = duration;
}
/**
* 处理循环逻辑
* @param elapsedTimeExcess
*/
private handleLooping(elapsedTimeExcess: number) {
this._loops--;
if (this._loopType == LoopType.pingpong) {
this.reverseTween();
}
if (this._loopType == LoopType.restartFromBeginning || this._loops % 2 == 0) {
this._loopCompleteHandler && this._completionHandler(this);
}
// 如果我们还有循环要处理,就把我们的状态重置为Running,这样我们就可以继续处理它们了
if (this._loops != 0) {
this._tweenState = TweenState.running;
// 现在,我们需要设置我们的经过时间,并考虑到我们的elapsedTimeExcess
if (this._loopType == LoopType.restartFromBeginning) {
this._elapsedTime = elapsedTimeExcess - this._delayBetweenLoops;
} else {
if (this._isRunningInReverse)
this._elapsedTime += this._delayBetweenLoops - elapsedTimeExcess;
else
this._elapsedTime = elapsedTimeExcess - this._delayBetweenLoops;
}
// 如果我们有一个elapsedTimeExcess,并且没有delayBetweenLoops,则更新该值
if (this._delayBetweenLoops == 0 && elapsedTimeExcess > 0) {
this.updateValue();
}
}
}
protected abstract updateValue();
}
} | the_stack |
/*
* ---------------------------------------------------------
* Copyright(C) Microsoft Corporation. All rights reserved.
* ---------------------------------------------------------
*
* ---------------------------------------------------------
* Generated file, DO NOT EDIT
* ---------------------------------------------------------
*/
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import * as restm from 'typed-rest-client/RestClient';
import vsom = require('./VsoClient');
import basem = require('./ClientApiBases');
import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces');
import ProjectAnalysisInterfaces = require("./interfaces/ProjectAnalysisInterfaces");
export interface IProjectAnalysisApi extends basem.ClientApiBase {
getProjectLanguageAnalytics(project: string): Promise<ProjectAnalysisInterfaces.ProjectLanguageAnalytics>;
getProjectActivityMetrics(project: string, fromDate: Date, aggregationType: ProjectAnalysisInterfaces.AggregationType): Promise<ProjectAnalysisInterfaces.ProjectActivityMetrics>;
getGitRepositoriesActivityMetrics(project: string, fromDate: Date, aggregationType: ProjectAnalysisInterfaces.AggregationType, skip: number, top: number): Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics[]>;
getRepositoryActivityMetrics(project: string, repositoryId: string, fromDate: Date, aggregationType: ProjectAnalysisInterfaces.AggregationType): Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics>;
}
export class ProjectAnalysisApi extends basem.ClientApiBase implements IProjectAnalysisApi {
constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions) {
super(baseUrl, handlers, 'node-ProjectAnalysis-api', options);
}
public static readonly RESOURCE_AREA_ID = "7658fa33-b1bf-4580-990f-fac5896773d3";
/**
* @param {string} project - Project ID or project name
*/
public async getProjectLanguageAnalytics(
project: string
): Promise<ProjectAnalysisInterfaces.ProjectLanguageAnalytics> {
return new Promise<ProjectAnalysisInterfaces.ProjectLanguageAnalytics>(async (resolve, reject) => {
let routeValues: any = {
project: project
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"projectanalysis",
"5b02a779-1867-433f-90b7-d23ed5e33e57",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<ProjectAnalysisInterfaces.ProjectLanguageAnalytics>;
res = await this.rest.get<ProjectAnalysisInterfaces.ProjectLanguageAnalytics>(url, options);
let ret = this.formatResponse(res.result,
ProjectAnalysisInterfaces.TypeInfo.ProjectLanguageAnalytics,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* @param {string} project - Project ID or project name
* @param {Date} fromDate
* @param {ProjectAnalysisInterfaces.AggregationType} aggregationType
*/
public async getProjectActivityMetrics(
project: string,
fromDate: Date,
aggregationType: ProjectAnalysisInterfaces.AggregationType
): Promise<ProjectAnalysisInterfaces.ProjectActivityMetrics> {
if (fromDate == null) {
throw new TypeError('fromDate can not be null or undefined');
}
if (aggregationType == null) {
throw new TypeError('aggregationType can not be null or undefined');
}
return new Promise<ProjectAnalysisInterfaces.ProjectActivityMetrics>(async (resolve, reject) => {
let routeValues: any = {
project: project
};
let queryValues: any = {
fromDate: fromDate,
aggregationType: aggregationType,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"projectanalysis",
"e40ae584-9ea6-4f06-a7c7-6284651b466b",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<ProjectAnalysisInterfaces.ProjectActivityMetrics>;
res = await this.rest.get<ProjectAnalysisInterfaces.ProjectActivityMetrics>(url, options);
let ret = this.formatResponse(res.result,
ProjectAnalysisInterfaces.TypeInfo.ProjectActivityMetrics,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Retrieves git activity metrics for repositories matching a specified criteria.
*
* @param {string} project - Project ID or project name
* @param {Date} fromDate - Date from which, the trends are to be fetched.
* @param {ProjectAnalysisInterfaces.AggregationType} aggregationType - Bucket size on which, trends are to be aggregated.
* @param {number} skip - The number of repositories to ignore.
* @param {number} top - The number of repositories for which activity metrics are to be retrieved.
*/
public async getGitRepositoriesActivityMetrics(
project: string,
fromDate: Date,
aggregationType: ProjectAnalysisInterfaces.AggregationType,
skip: number,
top: number
): Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics[]> {
if (fromDate == null) {
throw new TypeError('fromDate can not be null or undefined');
}
if (aggregationType == null) {
throw new TypeError('aggregationType can not be null or undefined');
}
if (skip == null) {
throw new TypeError('skip can not be null or undefined');
}
if (top == null) {
throw new TypeError('top can not be null or undefined');
}
return new Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics[]>(async (resolve, reject) => {
let routeValues: any = {
project: project
};
let queryValues: any = {
fromDate: fromDate,
aggregationType: aggregationType,
'$skip': skip,
'$top': top,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"projectanalysis",
"df7fbbca-630a-40e3-8aa3-7a3faf66947e",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<ProjectAnalysisInterfaces.RepositoryActivityMetrics[]>;
res = await this.rest.get<ProjectAnalysisInterfaces.RepositoryActivityMetrics[]>(url, options);
let ret = this.formatResponse(res.result,
ProjectAnalysisInterfaces.TypeInfo.RepositoryActivityMetrics,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* @param {string} project - Project ID or project name
* @param {string} repositoryId
* @param {Date} fromDate
* @param {ProjectAnalysisInterfaces.AggregationType} aggregationType
*/
public async getRepositoryActivityMetrics(
project: string,
repositoryId: string,
fromDate: Date,
aggregationType: ProjectAnalysisInterfaces.AggregationType
): Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics> {
if (fromDate == null) {
throw new TypeError('fromDate can not be null or undefined');
}
if (aggregationType == null) {
throw new TypeError('aggregationType can not be null or undefined');
}
return new Promise<ProjectAnalysisInterfaces.RepositoryActivityMetrics>(async (resolve, reject) => {
let routeValues: any = {
project: project,
repositoryId: repositoryId
};
let queryValues: any = {
fromDate: fromDate,
aggregationType: aggregationType,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"projectanalysis",
"df7fbbca-630a-40e3-8aa3-7a3faf66947e",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<ProjectAnalysisInterfaces.RepositoryActivityMetrics>;
res = await this.rest.get<ProjectAnalysisInterfaces.RepositoryActivityMetrics>(url, options);
let ret = this.formatResponse(res.result,
ProjectAnalysisInterfaces.TypeInfo.RepositoryActivityMetrics,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
} | the_stack |
import { NodePath, types as t, builders as b, utils as u, is, Scope } from 'estree-toolkit';
import { builtinModules } from 'module';
const hasProp = (prop: string, obj: Record<string, unknown>) => (
Object.prototype.hasOwnProperty.call(obj, prop)
)
const isRequireFunc = (node: t.CallExpression, scope: Scope) => (
is.identifier(node.callee, { name: 'require' }) &&
node.arguments.length === 1 &&
is.literal(node.arguments[0], { value: (v) => typeof v === 'string' }) &&
!scope.hasBinding('require')
);
const isModuleExports = (node: t.MemberExpression, scope: Scope) => (
is.identifier(node.object, { name: 'module' }) &&
(
node.computed
? is.literal(node.property, { value: 'exports' })
: is.identifier(node.property, { name: 'exports' })
) &&
!scope.hasBinding('module')
);
const export__cjsModuleTrue = () => b.exportNamedDeclaration(
b.variableDeclaration(
'const',
[b.variableDeclarator(b.identifier('__cjsModule'), b.literal(true))]
)
);
export const transformCommonJSToES6 = (programPath: NodePath<t.Program>, id: string) => {
// Most of variables are initialized lazily
let importIdx = 0;
let importIdentifierMap: Record<string, t.Identifier>;
let modImports: t.ImportDeclaration[];
let exportIdx = 0;
let exportIdentifierMap: Record<string, t.Identifier>;
// There can be only one `export * from ''`
let exportAll: t.ExportAllDeclaration;
let exportAllParent: NodePath;
let modExports: t.ExportSpecifier[];
let insertAfters: [NodePath, t.Node][];
let interopFuncIdentifier: t.Identifier;
// If `exports.<member> = value;` is used
let usedExports: boolean;
// If `module.exports.<member> = value;` is used
let usedModuleExports: boolean;
let is__esModule: boolean;
const fixRequireCallExpression = (path: NodePath<t.CallExpression>) => {
const importPath = (path.node.arguments[0] as t.Literal).value as string;
const importIdentifier = (importIdentifierMap ||= {})[importPath] ||
b.identifier(`imported_${importIdx++}_${id}`);
// Don't resolve built-in modules like path, fs, etc.
if (builtinModules.includes(importPath)) return;
if (!hasProp(importPath, importIdentifierMap)) {
importIdentifierMap[importPath] = importIdentifier;
(modImports ||= []).push(
b.importDeclaration(
[b.importNamespaceSpecifier(importIdentifier)],
b.literal(importPath)
)
);
}
path.replaceWith(
b.callExpression(
(interopFuncIdentifier ||= b.identifier(`__commonJS_${id}`)),
[importIdentifier]
)
);
}
programPath.traverse({
CallExpression(path) {
if (isRequireFunc(path.node, path.scope)) {
const parentPath = path.parentPath;
if (
is.assignmentExpression(parentPath.node) &&
is.memberExpression(parentPath.node.left) &&
isModuleExports(parentPath.node.left, parentPath.scope)
) {
// module.exports = require('something')
// This is handled by the MemberExpression function
return;
}
fixRequireCallExpression(path);
}
},
MemberExpression(path) {
const { parentPath } = path;
let exportIdentifier: t.Identifier;
let exportName: string;
let usedExportType: 'module.exports' | 'exports';
if (
is.callExpression(parentPath) &&
is.identifier(path.node.object, { name: 'Object' }) &&
is.identifier(path.node.property, { name: 'defineProperty' }) &&
(
(
is.identifier(parentPath.node.arguments[0], { name: 'exports' }) &&
!parentPath.scope.hasBinding('exports')
) || (
is.memberExpression(parentPath.node.arguments[0]) &&
isModuleExports(parentPath.node.arguments[0], parentPath.scope)
)
) &&
is.literal(parentPath.node.arguments[1], { value: '__esModule' }) &&
is.objectExpression(parentPath.node.arguments[2]) &&
parentPath.node.arguments[2].properties.some((n) => (
is.property(n) &&
is.identifier(n.key, { name: 'value' }) &&
is.literal(n.value, { value: true }) &&
!n.computed && !n.shorthand
))
) {
// Object.defineProperty(exports, '__esModule', { value: true });
// Object.defineProperty(module.exports, '__esModule', { value: true });
is__esModule = true;
parentPath.remove();
return;
}
if (isModuleExports(path.node, path.scope)) {
const markUsedModuleExports = () => {
usedModuleExports = true;
usedExportType = 'module.exports';
}
if (
is.memberExpression(parentPath.node) &&
(
parentPath.node.computed
? is.literal(parentPath.node.property, { value: (v) => typeof v === 'string' })
: true
)
) {
// module.exports.any
exportName = (parentPath.node.property as t.Identifier).name ||
(parentPath.node.property as t.Literal).value as string;
if (
exportName === '__esModule' &&
is.assignmentExpression(parentPath.parentPath) &&
u.evaluateTruthy(parentPath.parentPath.get('right'))
) {
// module.exports.__esModule = <truthyValue>;
is__esModule = true;
}
markUsedModuleExports();
} else if (
is.assignmentExpression(parentPath) &&
(
is.program(parentPath.parentPath) ||
(
is.expressionStatement(parentPath.parentPath) &&
is.program(parentPath.parentPath.parentPath)
)
) &&
is.callExpression(parentPath.node.right) &&
isRequireFunc(parentPath.node.right, parentPath.scope)
) {
// module.exports = require('some/code');
/*
Code can be like this
```
module.exports.item1 = 0;
module.exports.item2 = 0;
module.exports = require('some');
```
Now `module.export.item{1,2}` are no longer available,
this mean `module.exports = require()` basically resets other exports,
so we are going to do the same
*/
exportAll = b.exportAllDeclaration(
b.literal((parentPath.node.right.arguments[0] as t.Literal).value)
);
exportAllParent = parentPath;
// Reset previous exports
exportIdx = 0;
exportIdentifierMap = null;
modExports = null;
insertAfters = null;
} else {
markUsedModuleExports();
}
} else if (
is.identifier(path.node.object, { name: 'exports' }) &&
!path.scope.hasBinding('exports')
) {
exportName = (path.node.property as t.Identifier).name ||
(path.node.property as t.Literal).value as string;
if (
exportName === '__esModule' &&
is.assignmentExpression(parentPath) &&
u.evaluateTruthy(parentPath.get('right'))
) {
// exports.__esModule = <truthyValue>;
is__esModule = true;
}
usedExports = true;
usedExportType = 'exports';
}
if (
exportName &&
exportName !== '__esModule' &&
/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(exportName)
) {
exportIdentifier = (exportIdentifierMap ||= {})[exportName] ||
b.identifier(`export_${exportIdx++}_${id}`);
(insertAfters ||= []).push([
path.findParent((p) => is.expressionStatement(p)),
b.expressionStatement(
b.assignmentExpression(
'=',
exportIdentifier,
b.memberExpression(
usedExportType === 'module.exports'
? b.memberExpression(b.identifier('module'), b.identifier('exports'))
: b.identifier('exports'),
b.identifier(exportName)
)
)
)
]);
if (!hasProp(exportName, exportIdentifierMap)) {
exportIdentifierMap[exportName] = exportIdentifier;
(modExports ||= []).push(
b.exportSpecifier(exportIdentifier, b.identifier(exportName))
);
}
}
},
});
const hasOtherExports = programPath.get('body').some((p: NodePath) => is.exportDeclaration(p));
if (insertAfters) insertAfters.forEach(([path, toInsert]) => path && path.insertAfter([toInsert]));
if (exportAll) {
if (exportIdentifierMap) {
fixRequireCallExpression(exportAllParent.get<t.CallExpression>('right'));
} else {
exportAllParent.remove();
}
}
if (exportIdentifierMap) {
const exportIdentifiers = Object.values(exportIdentifierMap);
programPath.unshiftContainer('body', [
b.variableDeclaration(
'let',
exportIdentifiers.map((name) => b.variableDeclarator(name))
)
]);
}
if (usedModuleExports) {
programPath.unshiftContainer('body', [
b.variableDeclaration(
'const',
[
b.variableDeclarator(
b.identifier('module'),
b.objectExpression([
b.property(
'init',
b.identifier('exports'),
usedExports ? b.identifier('exports') : b.objectExpression([]),
false,
usedExports
)
])
)
]
)
]);
}
if (usedExports) {
programPath.unshiftContainer('body', [
b.variableDeclaration(
'const',
[
b.variableDeclarator(
b.identifier('exports'),
b.objectExpression([])
)
]
)
]);
}
if (modImports) programPath.unshiftContainer('body', modImports);
if (modExports) programPath.pushContainer('body', [b.exportNamedDeclaration(null, modExports)]);
if (exportAll) programPath.pushContainer('body', [exportAll]);
const shouldExportDefaultFromExportAll = !exportIdentifierMap && exportAll &&
!is__esModule && !modExports && !hasOtherExports;
if (shouldExportDefaultFromExportAll) {
const namespaceIdentifier = b.identifier(`for_default_${id}`);
const defaultExportIdentifier = b.identifier(`default_export_${id}`);
programPath.unshiftContainer('body', [
b.importDeclaration(
[b.importNamespaceSpecifier(namespaceIdentifier)],
b.literal(exportAll.source.value)
),
b.variableDeclaration(
'let',
[b.variableDeclarator(defaultExportIdentifier)]
)
]);
programPath.pushContainer('body', [
b.ifStatement(
b.binaryExpression(
'in',
b.literal('default'),
namespaceIdentifier
),
b.expressionStatement(
b.assignmentExpression(
'=',
defaultExportIdentifier,
b.memberExpression(
namespaceIdentifier,
b.literal('default'),
true
)
)
)
),
b.exportDefaultDeclaration(defaultExportIdentifier)
]);
}
if (
/* Not exporting default if default is already exported --> */ !shouldExportDefaultFromExportAll &&
(exportIdentifierMap ? !hasProp('default', exportIdentifierMap) : true) &&
!is__esModule && (usedModuleExports || usedExports)
) {
programPath.pushContainer('body', [
b.exportDefaultDeclaration(
usedModuleExports
? b.memberExpression(b.identifier('module'), b.identifier('exports'))
: b.identifier('exports')
),
export__cjsModuleTrue()
]);
}
if (interopFuncIdentifier) {
programPath.unshiftContainer('body', [
b.variableDeclaration(
'const',
[
b.variableDeclarator(
interopFuncIdentifier,
b.arrowFunctionExpression(
[b.identifier('mod')],
b.conditionalExpression(
b.memberExpression(b.identifier('mod'), b.identifier('__cjsModule')),
b.memberExpression(b.identifier('mod'), b.literal('default'), true),
b.identifier('mod')
)
)
)
]
)
]);
}
} | the_stack |
import fs from 'fs';
import path from 'path';
import { globalBeforeEach } from '../../../../__jest__/before-each';
import { database as db } from '../../../../common/database';
import { selectFileOrFolder } from '../../../../common/select-file-or-folder';
import * as models from '../../../../models';
import * as modals from '../../../../ui/components/modals';
import { loadMethods as _loadMethods, loadMethodsFromPath as _loadMethodsFromPath } from '../../proto-loader';
import * as protoManager from '../index';
const loadMethods = _loadMethods as jest.Mock;
const loadMethodsFromPath = _loadMethodsFromPath as jest.Mock;
jest.mock('../../../../common/select-file-or-folder', () => ({
selectFileOrFolder: jest.fn(),
}));
jest.mock('../../../../ui/components/modals');
jest.mock('../../proto-loader');
describe('protoManager', () => {
const selectFileOrFolderMock = selectFileOrFolder as jest.Mock;
beforeEach(() => {
globalBeforeEach();
jest.resetAllMocks();
});
describe('addFile', () => {
it('should not create database entry if file loading canceled', async () => {
// Arrange
const cbMock = jest.fn();
const w = await models.workspace.create();
selectFileOrFolderMock.mockResolvedValue({
canceled: true,
});
// Act
await protoManager.addFile(w._id, cbMock);
// Assert
expect(cbMock).not.toHaveBeenCalled();
const pf = await models.protoFile.getByParentId(w._id);
expect(pf).toBeNull();
expect(selectFileOrFolderMock).toHaveBeenCalledWith({
itemTypes: ['file'],
extensions: ['proto'],
});
});
it('should not create database entry if file loading throws error', async () => {
// Arrange
const cbMock = jest.fn();
const w = await models.workspace.create();
const error = new Error();
selectFileOrFolderMock.mockRejectedValue(error);
// Act
await protoManager.addFile(w._id, cbMock);
// Assert
expect(cbMock).not.toHaveBeenCalled();
const pf = await models.protoFile.getByParentId(w._id);
expect(pf).toBeNull();
expect(modals.showError).toHaveBeenCalledWith({
error,
});
});
it('should not create database entry if methods cannot be parsed', async () => {
// Arrange
const cbMock = jest.fn();
const w = await models.workspace.create();
const error = new Error();
const filePath = 'path';
selectFileOrFolderMock.mockResolvedValue({
filePath,
});
loadMethodsFromPath.mockRejectedValue(error);
// Act
await protoManager.addFile(w._id, cbMock);
// Assert
expect(cbMock).not.toHaveBeenCalled();
const pf = await models.protoFile.getByParentId(w._id);
expect(pf).toBeNull();
expect(modals.showError).toHaveBeenCalledWith({
title: 'Invalid Proto File',
message: `The file ${filePath} and could not be parsed`,
error,
});
});
it('should create database entry', async () => {
// Arrange
const cbMock = jest.fn();
const w = await models.workspace.create();
const filePath = 'filename.proto';
selectFileOrFolderMock.mockResolvedValue({
filePath,
});
loadMethodsFromPath.mockResolvedValue(undefined);
const fsReadFileSpy = jest.spyOn(fs.promises, 'readFile');
const contents = 'contents';
fsReadFileSpy.mockResolvedValue(contents);
// Act
await protoManager.addFile(w._id, cbMock);
// Assert
const pf = await models.protoFile.getByParentId(w._id);
expect(cbMock).toHaveBeenCalledWith(pf?._id);
expect(pf?.name).toBe(filePath);
expect(pf?.protoText).toBe(contents);
});
});
describe('updateFile', () => {
it('should update database entry', async () => {
// Arrange
const cbMock = jest.fn();
const w = await models.workspace.create();
const pf = await models.protoFile.create({
parentId: w._id,
});
const filePath = 'filename.proto';
selectFileOrFolderMock.mockResolvedValue({
filePath,
});
loadMethodsFromPath.mockResolvedValue(undefined);
const fsReadFileSpy = jest.spyOn(fs.promises, 'readFile');
const contents = 'contents';
fsReadFileSpy.mockResolvedValue(contents);
// Act
await protoManager.updateFile(pf, cbMock);
// Assert
expect(cbMock).toHaveBeenCalledWith(pf._id);
const updatedPf = await models.protoFile.getById(pf._id);
expect(updatedPf?.name).toBe(filePath);
expect(updatedPf?.protoText).toBe(contents);
});
});
describe('renameFile', () => {
it('should rename the file', async () => {
// Arrange
const w = await models.workspace.create();
const pf = await models.protoFile.create({
parentId: w._id,
name: 'original',
});
// Act
const updatedName = 'updated';
await protoManager.renameFile(pf, updatedName);
// Assert
const updatedPf = await models.protoFile.getById(pf._id);
expect(updatedPf?.name).toBe(updatedName);
});
});
describe('deleteFile', () => {
it('should alert the user before deleting a file', async () => {
// Arrange
const w = await models.workspace.create();
const pf = await models.protoFile.create({
parentId: w._id,
name: 'pfName.proto',
});
const cbMock = jest.fn();
// Act
await protoManager.deleteFile(pf, cbMock);
const showAlertCallArg = (modals.showAlert as jest.Mock).mock.calls[0][0];
expect(showAlertCallArg.title).toBe('Delete pfName.proto');
await showAlertCallArg.onConfirm();
// Assert
expect(cbMock).toHaveBeenCalledWith(pf._id);
await expect(models.protoFile.getById(pf._id)).resolves.toBeNull();
});
});
describe('deleteDirectory', () => {
it('should alert the user before deleting a directory', async () => {
// Arrange
const w = await models.workspace.create();
const pd = await models.protoDirectory.create({
parentId: w._id,
name: 'pdName',
});
const pf1 = await models.protoFile.create({
parentId: pd._id,
name: 'pfName1.proto',
});
const pf2 = await models.protoFile.create({
parentId: pd._id,
name: 'pfName2.proto',
});
const cbMock = jest.fn();
// Act
await protoManager.deleteDirectory(pd, cbMock);
const showAlertCallArg = (modals.showAlert as jest.Mock).mock.calls[0][0];
expect(showAlertCallArg.title).toBe('Delete pdName');
await showAlertCallArg.onConfirm();
// Assert
expect(cbMock).toHaveBeenCalledWith(expect.arrayContaining([pf1._id, pf2._id]));
await expect(models.protoDirectory.getById(pd._id)).resolves.toBeNull();
await expect(models.protoFile.getById(pf1._id)).resolves.toBeNull();
await expect(models.protoFile.getById(pf2._id)).resolves.toBeNull();
});
});
describe('addDirectory', () => {
let dbBufferChangesIndefinitelySpy: any | jest.Mock<any, any>;
let dbFlushChangesSpy: any | jest.Mock<any, any>;
beforeEach(() => {
dbBufferChangesIndefinitelySpy = jest.spyOn(db, 'bufferChangesIndefinitely');
dbFlushChangesSpy = jest.spyOn(db, 'flushChanges');
});
afterEach(() => {
expect(dbBufferChangesIndefinitelySpy).toHaveBeenCalled();
expect(dbFlushChangesSpy).toHaveBeenCalled();
dbBufferChangesIndefinitelySpy.mockRestore();
dbFlushChangesSpy.mockRestore();
});
it('should not create database entries if loading canceled', async () => {
// Arrange
const w = await models.workspace.create();
selectFileOrFolderMock.mockResolvedValue({
canceled: true,
});
// Act
await protoManager.addDirectory(w._id);
// Assert
await expect(models.protoDirectory.all()).resolves.toHaveLength(0);
await expect(models.protoFile.all()).resolves.toHaveLength(0);
});
it('should not create database entry if file loading throws error', async () => {
// Arrange
const w = await models.workspace.create();
const error = new Error();
selectFileOrFolderMock.mockRejectedValue(error);
// Act
await protoManager.addDirectory(w._id);
// Assert
await expect(models.protoDirectory.all()).resolves.toHaveLength(0);
await expect(models.protoFile.all()).resolves.toHaveLength(0);
expect(modals.showError).toHaveBeenCalledWith({
error,
});
expect(dbFlushChangesSpy).toHaveBeenCalledWith(expect.any(Number), true);
});
it('should show alert if no directory was created', async () => {
// Arrange
const w = await models.workspace.create();
const filePath = path.join(__dirname, '../../__fixtures__/', 'library', 'empty');
selectFileOrFolderMock.mockResolvedValue({
filePath,
});
// Act
await protoManager.addDirectory(w._id);
// Assert
await expect(models.protoDirectory.all()).resolves.toHaveLength(0);
await expect(models.protoFile.all()).resolves.toHaveLength(0);
expect(modals.showAlert).toHaveBeenCalledWith({
title: 'No files found',
message: `No .proto files were found under ${filePath}.`,
});
});
it('should delete database entries if there is an error while ingesting', async () => {
// Arrange
const w = await models.workspace.create();
const filePath = path.join(__dirname, '../../__fixtures__/', 'simulate-error');
selectFileOrFolderMock.mockResolvedValue({
filePath,
});
// Should error when loading the 6th file
const error = new Error('should-error.proto could not be loaded');
const fsPromisesReadFileSpy = jest.spyOn(fs.promises, 'readFile');
fsPromisesReadFileSpy
.mockResolvedValueOnce('contents of 1.proto')
.mockResolvedValueOnce('contents of 2.proto')
.mockResolvedValueOnce('contents of 3.proto')
.mockResolvedValueOnce('contents of 4.proto')
.mockResolvedValueOnce('contents of 5.proto')
.mockRejectedValueOnce(error);
// Act
await protoManager.addDirectory(w._id);
// Assert
await expect(models.protoDirectory.all()).resolves.toHaveLength(0);
await expect(models.protoFile.all()).resolves.toHaveLength(0);
// Expect rollback
expect(dbFlushChangesSpy).toHaveBeenCalledWith(expect.any(Number), true);
expect(modals.showError).toHaveBeenCalledWith({
title: 'Failed to import',
message: `An unexpected error occurred when reading ${filePath}`,
error,
});
fsPromisesReadFileSpy.mockRestore();
});
it('should delete database entries if there is a parsing error', async () => {
// Arrange
const w = await models.workspace.create();
const filePath = path.join(__dirname, '../../__fixtures__/', 'library', 'nested', 'time');
selectFileOrFolderMock.mockResolvedValue({
filePath,
});
const error = new Error('error');
loadMethods.mockRejectedValue(error);
// Act
await protoManager.addDirectory(w._id);
// Assert
await expect(models.protoDirectory.all()).resolves.toHaveLength(0);
await expect(models.protoFile.all()).resolves.toHaveLength(0);
expect(modals.showError).toHaveBeenCalledWith({
title: 'Invalid Proto File',
message: 'The file time.proto could not be parsed',
error,
});
expect(dbFlushChangesSpy).toHaveBeenCalledWith(expect.any(Number), true);
});
it('should create database entries', async () => {
// Arrange
const w = await models.workspace.create();
const filePath = path.join(__dirname, '../../__fixtures__/', 'library');
selectFileOrFolderMock.mockResolvedValue({
filePath,
});
// Act
await protoManager.addDirectory(w._id);
// Assert
await expect(models.protoDirectory.all()).resolves.toHaveLength(3);
await expect(models.protoFile.all()).resolves.toHaveLength(3); // Each individual entry is not validated here because it is
// too involved to mock everything, and an integration test exists
// which uses this code path. As long as the expected number of
// entities are loaded from the fixture directory, this test is sufficient.
});
});
}); | the_stack |
import * as pulumi from "@pulumi/pulumi";
/**
* A collection of Containers
*/
export interface Containers {
[name: string]: Container;
}
export type HostOperatingSystem = "linux" | "windows";
/**
* HostProperties describes the kind of host where a service or task can run.
*/
export interface HostProperties {
/**
* The operating system of the host.
*
* Default is "linux".
*/
os?: HostOperatingSystem;
}
/**
* Container specifies the metadata for a component of a Service.
*/
export interface Container {
/**
* The image to use for the container. If `image` is specified, but not `build`, the image will be
* pulled from the Docker Hub. If `image` *and* `build` are specified, the `image` controls the
* resulting image tag for the build image that gets pushed.
*/
image?: pulumi.Input<string>;
/**
* Either a path to a folder in which a Docker build should be run to construct the image for this
* Container, or a ContainerBuild object with more detailed build instructions. If `image` is also specified, the
* built container will be tagged with that name, but otherwise will get an auto-generated image name.
*/
build?: string | ContainerBuild;
/**
* The function code to use as the implementation of the contaner. If `function` is specified,
* neither `image` nor `build` are legal.
*/
function?: () => void;
/**
* Optional environment variables to set and make available to the container
* as it is running.
*/
environment?: {[name: string]: pulumi.Input<string>};
/**
* Number of CPUs for the container to use. Maps to the Docker `--cpus` option - see
* https://docs.docker.com/engine/reference/commandline/run.
*/
cpu?: pulumi.Input<number>;
/**
* The maximum amount of memory the container will be allowed to use. Maps to the Docker
* `--memory` option - see
* https://docs.docker.com/engine/reference/commandline/run.
*
* This should be supplied in MB. i.e. A value of 1024 would equal one gigabyte.
*/
memory?: pulumi.Input<number>;
/**
* The amount of memory to reserve for the container, but the container will
* be allowed to use more memory if it's available. At least one of
* `memory` and `memoryReservation` must be specified. Maps to the Docker
* `--memory-reservation` option - see
* https://docs.docker.com/engine/reference/commandline/run.
*
* This should be supplied in MB. i.e. A value of 1024 would equal one gigabyte.
*/
memoryReservation?: pulumi.Input<number>;
/**
* An array of ports to publish from the container. Ports are exposed using the TCP protocol. If the [external]
* flag is true, the port will be exposed to the Internet even if the service is running in a private network.
* Maps to the Docker `--publish` option - see
* https://docs.docker.com/engine/reference/commandline/run.
*/
ports?: ContainerPort[];
/**
* An array of volume mounts, indicating a volume to mount and a path within
* the container at which to mount the volume. Maps to the Docker
* `--volume` option - see
* https://docs.docker.com/engine/reference/commandline/run.
*/
volumes?: ContainerVolumeMount[];
/**
* The command line that is passed to the container. This parameter maps to
* `Cmd` in the [Create a
* container](https://docs.docker.com/engine/reference/api/docker_remote_api_v1.19/#create-a-container)
* section of the [Docker Remote
* API](https://docs.docker.com/engine/reference/api/docker_remote_api_v1.19/)
* and the `COMMAND` parameter to [docker run](https://docs.docker.com/engine/reference/commandline/run/). For more
* information about the Docker `CMD` parameter, go to
* https://docs.docker.com/engine/reference/builder/#cmd.
*/
command?: pulumi.Input<string[]>;
/**
* A key/value map of labels to add to the container. This parameter maps to Labels in the [Create a
* container](https://docs.docker.com/engine/api/v1.27/#operation/ContainerCreate) section of the [Docker Remote
* API](https://docs.docker.com/engine/api/v1.27/) and the --label option to [docker
* run](https://docs.docker.com/engine/reference/run/).
*/
dockerLabels?: pulumi.Input<{[name: string]: string}>;
}
/**
* CacheFrom may be used to specify build stages to use for the Docker build cache. The final image is always
* implicitly included.
*/
export interface CacheFrom {
/**
* An optional list of build stages to use for caching. Each build stage in this list will be built explicitly and
* pushed to the target repository. A given stage's image will be tagged as "[stage-name]".
*/
stages?: string[];
}
/**
* ContainerBuild may be used to specify detailed instructions about how to build a container.
*/
export interface ContainerBuild {
/**
* context is a path to a directory to use for the Docker build context, usually the directory in which the
* Dockerfile resides (although dockerfile may be used to choose a custom location independent of this choice).
* If not specified, the context defaults to the current working directory; if a relative path is used, it
* is relative to the current working directory that Pulumi is evaluating.
*/
context?: string;
/**
* dockerfile may be used to override the default Dockerfile name and/or location. By default, it is assumed
* to be a file named Dockerfile in the root of the build context.
*/
dockerfile?: string;
/**
* An optional map of named build-time argument variables to set during the Docker build. This flag allows you
* to pass built-time variables that can be accessed like environment variables inside the `RUN` instruction.
*/
args?: {[key: string]: string};
/**
* An optional CacheFrom object with information about the build stages to use for the Docker build cache.
* This parameter maps to the --cache-from argument to the Docker CLI. If this parameter is `true`, only the final
* image will be pulled and passed to --cache-from; if it is a CacheFrom object, the stages named therein will
* also be pulled and passed to --cache-from.
*/
cacheFrom?: boolean | CacheFrom;
}
/**
* ContainerPort represents the information about how to expose a container port on a [Service].
*/
export interface ContainerPort {
/**
* The incoming port where the service exposes the endpoint.
*/
port: number;
/**
* The target port on the backing container. Defaults to the value of [port].
*/
targetPort?: number;
/**
* Whether the port should be exposed externally. Defaults to `false`.
*/
external?: boolean;
/**
* The protocol to use for exposing the service:
* * `tcp`: Expose TCP externaly and to the container.
* * `udp`: Expose UDP externally and to the container.
* * `http`: Expose HTTP externally and to the container.
* * `https`: Expose HTTPS externally and HTTP to the container.
*/
protocol?: ContainerProtocol;
}
export type ContainerProtocol = "tcp" | "udp" | "http" | "https";
export interface ContainerVolumeMount {
containerPath: string;
sourceVolume: Volume;
}
export type VolumeKind = "SharedVolume" | "HostPathVolume";
export type Volume = SharedVolume | HostPathVolume;
/**
* A shared volume that can be mounted into one or more containers.
*/
export interface SharedVolume {
kind: "SharedVolume";
/*
* The unique name of the volume.
*/
name: string;
}
export interface SharedVolumeConstructor {
/**
* Construct a new Volume with the given unique name.
*
* @param name The unique name of the volume.
* @param opts A bag of options that controls how this resource behaves.
*/
new (name: string, opts?: pulumi.ResourceOptions): SharedVolume;
}
export let SharedVolume: SharedVolumeConstructor; // tslint:disable-line
/**
* A volume mounted from a path on the host machine.
*
* _Note_: This is an emphemeral volume which will not persist across container restarts or
* across different hosts. This is not something that most containers will need, but it offers
* a powerful escape hatch for some applications.
*/
export interface HostPathVolume {
kind: "HostPathVolume";
/*
* The unique name of the volume.
*/
path: string;
}
export interface HostPathVolumeConstructor {
/**
* Construct a new Volume with the given unique name.
*/
new (path: string): HostPathVolume;
}
export let HostPathVolume: HostPathVolumeConstructor; // tslint:disable-line
/**
* The arguments to construct a Service object. These arguments may include container information, for simple
* single-container scenarios, or you may specify that information using the containers property. If a single container
* is specified in-line, it is implicitly given the name "default".
*/
export interface ServiceArguments extends Container {
/**
* A collection of containers that will be deployed as part of this Service, if there are multiple.
*/
containers?: Containers;
/**
* The number of copies of this Service's containers to deploy and maintain
* as part of the running service. Defaults to `1`.
*/
replicas?: number;
/**
* The properties of the host where this service can run.
*/
host?: HostProperties;
/**
*
* Determines whether the service should wait to fully transition to a new steady state on creation and updates. If
* set to false, the service may complete its deployment before it is fully ready to be used. Defaults to 'true'.
*/
waitForSteadyState?: boolean;
}
export interface Endpoint {
hostname: string;
port: number;
}
export interface Endpoints {
[containerName: string]: {
[port: number]: Endpoint;
};
}
/**
* A persistent service running as part of the Pulumi Cloud application. A
* collection of container specifications are provided to define the compute
* that will run inside this service.
*/
export interface Service {
name: string;
// Inside API
/**
* The exposed hostname and port for connecting to the given containerName
* on the given containerPort.
*/
endpoints: pulumi.Output<Endpoints>;
/**
* The primary endpoint exposed by the service. All endpoints (including this one)
* can also be retrieved by using the 'Service.endpoints' property. Note: this value
* may not be present if the service does not actually expose any endpoints.
*/
defaultEndpoint: pulumi.Output<Endpoint>;
/**
* The exposed hostname and port for connecting to the given containerName
* on the given containerPort. If containerName is not provided, the first
* container in the service is used. If containerPort is not provided, the
* first exposed port is used.
*
* Only usable on the inside.
*/
getEndpoint(containerName?: string, containerPort?: number): Promise<Endpoint>;
}
export interface ServiceConstructor {
/**
* Construct a new Service, which is one or more managed replicas of a group of one or more Containers.
*
* @param name The unique name of the service.
* @param opts A bag of options that controls how this resource behaves.
*/
new (name: string, args: ServiceArguments, opts?: pulumi.ResourceOptions): Service;
}
export let Service: ServiceConstructor; // tslint:disable-line
/**
* Arguments to use for initializing a single run of the Task
*/
export interface TaskRunOptions {
/**
* Optional environment variables to override those set in the container definition.
*/
environment?: Record<string, string>;
/**
* The properties of the host where this task can run.
*/
host?: HostProperties;
}
/**
* A Task represents a container which can be [run] dynamically whenever (and
* as many times as) needed.
*/
export interface Task {
/**
* Run the task, passing in additional task run options.
*/
run(options?: TaskRunOptions): Promise<void>;
}
export interface TaskConstructor {
/**
* Construct a new Task, which is a Container that can be run many times as individual tasks.
*
* @param name The unique name of the task.
* @param container The container specification.
* @param opts A bag of options that controls how this resource behaves.
*/
new (name: string, container: Container, opts?: pulumi.ResourceOptions): Task;
}
export let Task: TaskConstructor; // tslint:disable-line | the_stack |
import auth = require('./auth')
import callbacks = require('./callbacks');
import childProcess = require('child_process');
import crypto = require('crypto');
import fs = require('fs');
import http = require('http');
import httpProxy = require('http-proxy');
import idleTimeout = require('./idleTimeout');
import logging = require('./logging');
import net = require('net');
import path = require('path');
import settings = require('./settings');
import tcp = require('tcp-port-used');
import url = require('url');
import userManager = require('./userManager');
interface JupyterServer {
userId: string;
port: number;
notebooks: string;
childProcess?: childProcess.ChildProcess;
proxy?: httpProxy.ProxyServer;
}
/**
* Jupyter servers key'd by user id (each server is associated with a single user)
*/
var jupyterServers: common.Map<JupyterServer> = {};
var nextJupyterPort = 9000;
var portRetryAttempts = 500;
/**
* Get the next available port and pass it to the given `resolved` callback.
*/
function getNextJupyterPort(attempts: number, resolved: (port: number)=>void, failed: (error: Error)=>void) {
if (attempts < 0) {
var e = new Error('Failed to find a free port after ' + portRetryAttempts + ' attempts.');
logging.getLogger().error(e, 'Failed to find a free port for the Jupyter server');
failed(e);
return;
}
if (nextJupyterPort > 65535) {
// We've exhausted the entire port space. This is an extraordinary circumstance
// so we log an error for it (but still continue).
var e = new Error('Port range exhausted.');
logging.getLogger().error(e, 'Exhausted the entire address space looking for free ports');
nextJupyterPort = 9000;
}
var port = nextJupyterPort;
nextJupyterPort++;
tcp.check(port, "localhost").then(
function(inUse: boolean) {
if (inUse) {
getNextJupyterPort(attempts - 1, resolved, failed);
}
else {
logging.getLogger().info('Returning port %d', port);
resolved(port);
}
},
failed);
}
/**
* Used to make sure no multiple initialization runs happen for the same user
* at same time.
*/
var callbackManager: callbacks.CallbackManager = new callbacks.CallbackManager();
/**
* Templates
*/
const templates: common.Map<string> = {
// These cached templates can be overridden in sendTemplate
'tree': fs.readFileSync(path.join(__dirname, 'templates', 'tree.html'), { encoding: 'utf8' }),
'terminals': fs.readFileSync(path.join(__dirname, 'templates', 'terminals.html'), { encoding: 'utf8' }),
'sessions': fs.readFileSync(path.join(__dirname, 'templates', 'sessions.html'), { encoding: 'utf8' }),
'edit': fs.readFileSync(path.join(__dirname, 'templates', 'edit.html'), { encoding: 'utf8' }),
'nb': fs.readFileSync(path.join(__dirname, 'templates', 'nb.html'), { encoding: 'utf8' })
};
/**
* The application settings instance.
*/
var appSettings: common.AppSettings;
function pipeOutput(stream: NodeJS.ReadableStream, port: number, error: boolean) {
stream.setEncoding('utf8');
stream.on('data', (data: string) => {
// Jupyter generates a polling kernel message once every 3 seconds
// per kernel! This adds too much noise into the log, so avoid
// logging it.
if (data.indexOf('Polling kernel') < 0) {
logging.logJupyterOutput('[' + port + ']: ' + data, error);
}
})
}
function createJupyterServerAtPort(port: number, userId: string, userDir: string) {
var server: JupyterServer = {
userId: userId,
port: port,
notebooks: userDir,
};
function exitHandler(code: number, signal: string): void {
logging.getLogger().error('Jupyter process %d for user %s exited due to signal: %s',
server.childProcess.pid, userId, signal);
delete jupyterServers[server.userId];
}
var secretPath = path.join(appSettings.datalabRoot, '/content/datalab/.config/notary_secret');
var processArgs = appSettings.jupyterArgs.slice().concat([
'--allow-root',
'--port=' + server.port,
'--port-retries=0',
'--notebook-dir="' + server.notebooks + '"',
'--NotebookNotary.algorithm=sha256',
'--NotebookNotary.secret_file=' + secretPath,
'--NotebookApp.base_url=' + appSettings.datalabBasePath,
]);
var notebookEnv: any = process.env;
var processOptions = {
detached: false,
env: notebookEnv
};
server.childProcess = childProcess.spawn('jupyter', processArgs, processOptions);
server.childProcess.on('exit', exitHandler);
logging.getLogger().info('Jupyter process for user %s started with pid %d and args %j',
userId, server.childProcess.pid, processArgs);
// Capture the output, so it can be piped for logging.
pipeOutput(server.childProcess.stdout, server.port, /* error */ false);
pipeOutput(server.childProcess.stderr, server.port, /* error */ true);
// Create the proxy.
var proxyOptions: httpProxy.ProxyServerOptions = {
target: 'http://localhost:' + port + appSettings.datalabBasePath
};
server.proxy = httpProxy.createProxyServer(proxyOptions);
server.proxy.on('proxyRes', responseHandler);
server.proxy.on('error', errorHandler);
tcp.waitUntilUsedOnHost(server.port, "localhost", 100, 15000).then(
function() {
jupyterServers[userId] = server;
logging.getLogger().info('Jupyter server started for %s.', userId);
callbackManager.invokeAllCallbacks(userId, null);
},
function(e) {
logging.getLogger().error(e, 'Failed to start Jupyter server for user %s.', userId);
callbackManager.invokeAllCallbacks(userId, e);
});
}
/**
* Starts the Jupyter server, and then creates a proxy object enabling
* routing HTTP and WebSocket requests to Jupyter.
*/
function createJupyterServer(userId: string, remainingAttempts: number) {
logging.getLogger().info('Checking user dir for %s exists', userId);
var userDir = userManager.getUserDir(userId);
logging.getLogger().info('Checking dir %s exists', userDir);
if (!fs.existsSync(userDir)) {
logging.getLogger().info('Creating user dir %s', userDir);
try {
fs.mkdirSync(userDir, parseInt('0755', 8));
} catch (e) {
// This likely means the disk is not yet ready.
// We'll fall back to /content for now.
logging.getLogger().info('User dir %s does not exist', userDir);
userDir = '/content'
}
}
nextJupyterPort = appSettings.nextJupyterPort;
logging.getLogger().info('Looking for a free port on which to start Jupyter for %s', userId);
getNextJupyterPort(
portRetryAttempts,
function(port: number) {
logging.getLogger().info('Launching Jupyter server for %s at %d', userId, port);
try {
createJupyterServerAtPort(port, userId, userDir);
} catch (e) {
logging.getLogger().error(e, 'Error creating the Jupyter process for user %s', userId);
callbackManager.invokeAllCallbacks(userId, e);
}
},
function(e) {
logging.getLogger().error(e, 'Failed to find a free port');
if (remainingAttempts > 0) {
attemptStartForUser(userId, remainingAttempts - 1);
}
else {
logging.getLogger().error('Failed to start Jupyter server for user %s.', userId);
callbackManager.invokeAllCallbacks(userId, new Error('failed to start jupyter server.'));
}
});
}
function listJupyterServers(): number[] {
var psStdout = '';
try {
psStdout = childProcess.execSync('ps -C jupyter-notebook -o pid=', {}).toString();
} catch (err) {
// In the default case, where there are no jupyter-notebook processes running,
// the 'ps' call will throw an error. We distinguish that case by ignoring
// the error unless the stdout or stderr values are non-empty.
if (err['stdout'] != '' || err['stderr'] != '') {
throw err;
}
}
var jupyterProcesses: number[] = [];
var jupyterProcessIdStrings = psStdout.split('\n');
for (var i in jupyterProcessIdStrings) {
if (jupyterProcessIdStrings[i]) {
var processId = parseInt(jupyterProcessIdStrings[i]);
if (processId != NaN) {
jupyterProcesses.push(processId);
}
}
}
return jupyterProcesses;
}
function killAllJupyterServers() {
var jupyterProcesses = listJupyterServers();
for (var i in jupyterProcesses) {
var processId = jupyterProcesses[i];
logging.getLogger().info('Killing abandoned Jupyter notebook process: %d', processId);
process.kill(processId);
}
}
export function getPort(request: http.ServerRequest): number {
var userId = userManager.getUserId(request);
var server = jupyterServers[userId];
return server ? server.port : 0;
}
export function getInfo(): Array<common.Map<any>> {
var info: Array<common.Map<any>> = [];
for (var n in jupyterServers) {
var jupyterServer = jupyterServers[n];
var serverInfo: common.Map<any> = {
userId: jupyterServer.userId,
port: jupyterServer.port,
notebooks: jupyterServer.notebooks,
pid: jupyterServer.childProcess.pid
};
info.push(serverInfo);
}
return info;
}
function attemptStartForUser(userId: string, remainingAttempts: number) {
try {
createJupyterServer(userId, remainingAttempts);
}
catch (e) {
logging.getLogger().error(e, 'Failed to start Jupyter server for user %s.', userId);
callbackManager.invokeAllCallbacks(userId, e);
}
}
/**
* Starts a jupyter server instance for given user.
*/
export function startForUser(userId: string, cb: common.Callback0) {
var server = jupyterServers[userId];
if (server) {
process.nextTick(function() { cb(null); });
return;
}
if (!callbackManager.checkOngoingAndRegisterCallback(userId, cb)) {
// There is already a start request ongoing. Return now to avoid multiple Jupyter
// processes for the same user.
return;
}
logging.getLogger().info('Starting jupyter server for %s.', userId);
attemptStartForUser(userId, 10);
}
/**
* Initializes the Jupyter server manager.
*/
export function init(settings: common.AppSettings): void {
appSettings = settings;
killAllJupyterServers();
}
/**
* Closes the Jupyter server manager.
*/
export function close(): void {
for (var n in jupyterServers) {
var jupyterServer = jupyterServers[n];
var jupyterProcess = jupyterServer.childProcess;
try {
jupyterProcess.kill('SIGHUP');
}
catch (e) {
}
}
jupyterServers = {};
}
export function handleSocket(request: http.ServerRequest, socket: net.Socket, head: Buffer) {
var userId = userManager.getUserId(request);
var server = jupyterServers[userId];
if (!server) {
// should never be here.
logging.getLogger().error('Jupyter server was not created yet for user %s.', userId);
return;
}
server.proxy.ws(request, socket, head);
idleTimeout.setupResetOnWebSocketRequests(socket);
}
export function handleRequest(request: http.ServerRequest, response: http.ServerResponse) {
var userId = userManager.getUserId(request);
var server = jupyterServers[userId];
if (!server) {
// should never be here.
logging.getLogger().error('Jupyter server was not created yet for user %s.', userId);
response.statusCode = 500;
response.end();
return;
}
var path = url.parse(request.url).pathname;
if (path.indexOf('/sessions') == 0) {
var templateData: common.Map<string> = getBaseTemplateData(request);
sendTemplate('sessions', templateData, response);
return;
}
server.proxy.web(request, response, null);
}
function getBaseTemplateData(request: http.ServerRequest): common.Map<string> {
const userId: string = userManager.getUserId(request);
const reportingEnabled: string = process.env.ENABLE_USAGE_REPORTING;
// TODO: Cache the gcloudAccount value so that we are not
// calling `gcloud` on every page load.
const gcloudAccount : string = auth.getGcloudAccount();
const signedIn = auth.isSignedIn(gcloudAccount);
let templateData: common.Map<string> = {
feedbackId: appSettings.feedbackId,
versionId: appSettings.versionId,
userId: userId,
configUrl: appSettings.configUrl,
knownTutorialsUrl: appSettings.knownTutorialsUrl,
baseUrl: appSettings.datalabBasePath,
reportingEnabled: reportingEnabled,
proxyWebSockets: appSettings.proxyWebSockets,
isSignedIn: signedIn.toString(),
};
if (signedIn) {
templateData['account'] = gcloudAccount;
if (process.env.PROJECT_NUMBER) {
var hash = crypto.createHash('sha256');
hash.update(process.env.PROJECT_NUMBER);
templateData['projectHash'] = hash.digest('hex');
}
}
return templateData;
}
function sendTemplate(key: string, data: common.Map<string>, response: http.ServerResponse) {
let template = templates[key];
// Set this env var to point to source directory for live updates without restart.
const liveTemplatesDir = process.env.DATALAB_LIVE_TEMPLATES_DIR
if (liveTemplatesDir) {
template = fs.readFileSync(path.join(liveTemplatesDir, key + '.html'), { encoding: 'utf8' });
}
// Replace <%name%> placeholders with actual values.
// TODO: Error handling if template placeholders are out-of-sync with
// keys in passed in data object.
const htmlContent = template.replace(/\<\%(\w+)\%\>/g, function(match, name) {
return data[name];
});
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(htmlContent);
}
function responseHandler(proxyResponse: http.ClientResponse,
request: http.ServerRequest, response: http.ServerResponse) {
if (appSettings.allowOriginOverrides.length &&
appSettings.allowOriginOverrides.indexOf(request.headers['origin']) != -1) {
proxyResponse.headers['access-control-allow-origin'] = request.headers['origin'];
proxyResponse.headers['access-control-allow-credentials'] = 'true';
} else if (proxyResponse.headers['access-control-allow-origin'] !== undefined) {
// Delete the allow-origin = * header that is sent (likely as a result of a workaround
// notebook configuration to allow server-side websocket connections that are
// interpreted by Jupyter as cross-domain).
delete proxyResponse.headers['access-control-allow-origin'];
}
if (proxyResponse.statusCode != 200) {
return;
}
// Set a cookie to provide information about the project and authenticated user to the client.
// Ensure this happens only for page requests, rather than for API requests.
var path = url.parse(request.url).pathname;
if ((path.indexOf('/tree') == 0) || (path.indexOf('/notebooks') == 0) ||
(path.indexOf('/edit') == 0) || (path.indexOf('/terminals') == 0)) {
var templateData: common.Map<string> = getBaseTemplateData(request);
var page: string = null;
if (path.indexOf('/tree') == 0) {
// stripping off the /tree/ from the path
templateData['notebookPath'] = path.substr(6);
page = 'tree';
} else if (path.indexOf('/edit') == 0) {
// stripping off the /edit/ from the path
templateData['filePath'] = path.substr(6);
templateData['fileName'] = path.substr(path.lastIndexOf('/') + 1);
page = 'edit';
} else if (path.indexOf('/terminals') == 0) {
templateData['terminalId'] = 'terminals/websocket/' + path.substr(path.lastIndexOf('/') + 1);
page = 'terminals';
} else {
// stripping off the /notebooks/ from the path
templateData['notebookPath'] = path.substr(11);
templateData['notebookName'] = path.substr(path.lastIndexOf('/') + 1);
page = 'nb';
}
sendTemplate(page, templateData, response);
// Suppress further writing to the response to prevent sending response
// from the notebook server. There is no way to communicate that, so hack around the
// limitation, by stubbing out all the relevant methods on the response with
// no-op methods.
response.setHeader = placeHolder;
response.writeHead = placeHolder;
response.write = placeHolder;
response.end = placeHolder;
}
}
function errorHandler(error: Error, request: http.ServerRequest, response: http.ServerResponse) {
logging.getLogger().error(error, 'Jupyter server returned error.')
response.writeHead(500, 'Internal Server Error');
response.end();
}
function placeHolder(): boolean { return false; } | the_stack |
import * as fs from "fs";
import {ProxyType} from "./bst-proxy";
import {LoggingHelper} from "../core/logging-helper";
import {LambdaConfig} from "./lambda-config";
import {SourceNameGenerator} from "../external/source-name-generator";
import {SpokesClient} from "../external/spokes";
import {BstMessages} from "../external/messages";
const Logger = "CONFIG";
const BSTDirectoryName = ".bst";
/**
* Handles setting up initial configuration and ongoing state of BST
*/
export class BSTConfig {
public configuration: any = null;
public process: any = null;
/**
* Loads the configuration
* Done all synchronously as this is done first thing at startup and everything waits on it
* createSource: call source api to create a soruce
*/
public static async load(createSource?: boolean): Promise<BSTConfig> {
createSource = typeof createSource === "undefined" ? true : createSource;
await BSTConfig.bootstrapIfNeeded(createSource);
let config = undefined;
if (fs.existsSync(BSTConfig.configPath())) {
let data = fs.readFileSync(BSTConfig.configPath());
config = JSON.parse(data.toString());
}
let bstConfig = new BSTConfig();
bstConfig.loadFromJSON(config);
return bstConfig;
}
public getMessages(): any {
const bstMessages = this.configuration.bstMessages;
if (!bstMessages) return undefined;
const messages = bstMessages.messages;
if (!messages) return undefined;
const result: any = {};
if (messages.customMessages && messages.customMessages.length) {
const randomMessage = Math.floor(Math.random() * messages.customMessages.length);
result.customMessage = messages.customMessages[randomMessage];
}
if (messages.tips && messages.tips.length) {
const randomTip = Math.floor(Math.random() * messages.tips.length);
result.tip = messages.tips[randomTip];
}
return result;
}
public save() {
BSTConfig.saveConfig(this.configuration);
}
public static getBstVersion() {
const packageInfo: any = require("../../package.json");
return packageInfo.version;
}
public sourceID(): string {
return this.configuration.sourceID;
}
public secretKey(): string {
return this.configuration.secretKey;
}
public applicationID(): string {
return this.configuration.applicationID;
}
public updateApplicationID(applicationID: string): void {
this.configuration.applicationID = applicationID;
this.commit();
}
public updateVirtualDeviceToken(virtualDeviceToken: string): void {
this.configuration.virtualDeviceToken = virtualDeviceToken;
this.commit();
}
public updateMessages(messages: any[]): void {
this.configuration.messages = messages;
this.commit();
}
public deleteSession(): void {
if (fs.existsSync(BSTConfig.sessionPath())) {
fs.unlinkSync(BSTConfig.sessionPath());
}
}
public saveSession(session: any): void {
const sessionBuffer = Buffer.from(JSON.stringify(session, null, 4) + "\n");
fs.writeFileSync(BSTConfig.sessionPath(), sessionBuffer);
}
public loadSession(): any {
if (!fs.existsSync(BSTConfig.sessionPath())) {
return null;
}
const data = fs.readFileSync(BSTConfig.sessionPath());
return JSON.parse(data.toString());
}
public virtualDeviceToken(): string {
return this.configuration.virtualDeviceToken;
}
public commit() {
let configBuffer = Buffer.from(JSON.stringify(this.configuration, null, 4) + "\n");
fs.writeFileSync(BSTConfig.configPath(), configBuffer);
}
private loadFromJSON(config: any): void {
this.configuration = config;
}
private static configDirectory(): string {
return getUserHome() + "/" + BSTDirectoryName;
}
private static configPath(): string {
return BSTConfig.configDirectory() + "/config";
}
private static sessionPath(): string {
return BSTConfig.configDirectory() + "/session";
}
/**
* Creates a new configuration file if one does not exist
* createSource: call source api to create a source
*/
private static async bootstrapIfNeeded(createSource?: boolean): Promise<void> {
createSource = typeof createSource === "undefined" ? true : createSource;
let directory = BSTConfig.configDirectory();
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
if (!fs.existsSync(BSTConfig.configPath())) {
LoggingHelper.info(Logger, "No configuration. Creating one: " + BSTConfig.configPath());
let configJSON: any = {};
if (createSource) {
// Create the config file if it does not yet exist
configJSON = await BSTConfig.createConfig();
}
configJSON.bstMessages = await this.fetchMessages();
BSTConfig.saveConfig(configJSON);
} else {
// If config exists but doesn't have sourceID update it
let data = fs.readFileSync(BSTConfig.configPath());
let config = JSON.parse(data.toString());
if (createSource && (!config.sourceID || !config.version)) {
await BSTConfig.updateConfig(config);
}
if (config.bstMessages && config.bstMessages.fetched) {
const difference = (new Date()).getTime() - config.bstMessages.fetched;
// If the messages where older than a day, we will fetch again
if (difference > 1000 * 3600 * 24) {
config.bstMessages = await this.fetchMessages();
}
} else {
config.bstMessages = await this.fetchMessages();
}
BSTConfig.saveConfig(config);
}
}
private static async updateConfig(config: any): Promise<void> {
const previousKey = config.nodeID || config.secretKey;
const generatedConfig = await BSTConfig.createConfig(previousKey, config.sourceID);
config.sourceID = generatedConfig.sourceID;
config.secretKey = generatedConfig.secretKey;
config.version = generatedConfig.version;
delete config.nodeID;
}
private static saveConfig(config: any) {
let configBuffer = Buffer.from(JSON.stringify(config, null, 4) + "\n");
fs.writeFileSync(BSTConfig.configPath(), configBuffer);
}
private static async createConfig(nodeID?: string, sourceID?: string): Promise<any> {
const lambdaConfig = LambdaConfig.defaultConfig().lambdaDeploy;
const pipeInfo = await BSTConfig.createExternalResources(nodeID, sourceID);
const bstMessages = await this.fetchMessages();
return {
"sourceID": pipeInfo.endPoint.name,
"secretKey": pipeInfo.uuid,
"lambdaDeploy": lambdaConfig,
"version": this.getBstVersion(),
"bstMessages": bstMessages,
};
}
private static async createSpokesPipe(id: string, secretKey: string): Promise<any> {
const spokesClient = new SpokesClient(id, secretKey);
const isUUIDUnassigned = await spokesClient.verifyUUIDisNew();
if (isUUIDUnassigned) {
return spokesClient.createPipe();
}
// Pipe exists, we return the info we have as pipe
return {
endPoint: {
name: id,
},
uuid: secretKey,
};
}
private static async createSource(secretKey?: string, sourceID?: string): Promise<any> {
const sourceNameGenerator = new SourceNameGenerator();
let id;
let key;
// Covers new users case and also
// If someone have only sourceID but not secretKey then he modified the config, so it's ok to drop
if (!secretKey) {
const generatedKey = await sourceNameGenerator.callService();
id = generatedKey.id;
key = generatedKey.secretKey;
}
// This means it has nodeID but have no pipe or key
if (secretKey && !sourceID) {
const generatedKey = await sourceNameGenerator.callService();
id = generatedKey.id;
key = secretKey;
}
if (sourceID && secretKey) {
// We have a previously created config, we try to create it directly
id = sourceID;
key = secretKey;
}
try {
await sourceNameGenerator.createDashboardSource(id, key);
} catch (e) {
// If the source already exists everything is fine
if (e.statusCode !== 403) {
throw(e);
}
}
return {
id,
key,
};
}
private static async createExternalResources(secretKey?: string, sourceID?: string): Promise<any> {
const sourceData = await this.createSource(secretKey, sourceID);
const pipe = await this.createSpokesPipe(sourceData.id, sourceData.key);
return pipe;
}
private static async fetchMessages(): Promise<any> {
try {
const bstMessages = new BstMessages();
const messages = await bstMessages.callService();
return {
messages,
fetched: new Date().getTime(),
};
} catch (error) {
if (process.env.DISPLAY_INTERNAL_ERROR) {
console.log("error", error);
}
}
return undefined;
}
}
export class BSTProcess {
public port: number;
public proxyType: ProxyType;
public pid: number;
public constructor() {}
/**
* Returns the running process, if any
*/
public static running(): BSTProcess {
let process: BSTProcess = null;
if (fs.existsSync(BSTProcess.processPath())) {
let data = fs.readFileSync(BSTProcess.processPath());
let json = JSON.parse(data.toString());
// Check if the process is actually running - otherwise discount it
if (BSTProcess.isRunning(json.pid)) {
process = new BSTProcess();
process.loadJSON(json);
}
}
return process;
}
// Excellent code from the internet
// https://github.com/nisaacson/is-running/blob/master/index.js
// http://stackoverflow.com/questions/14390930/how-to-check-if-an-arbitrary-pid-is-running-using-node-js
private static isRunning (pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return e.code === "EPERM";
}
}
public static processPath(): string {
return getUserHome() + "/" + BSTDirectoryName + "/process";
}
public static run(port: number, proxyType: ProxyType, pid: number): BSTProcess {
let process = new BSTProcess();
process.port = port;
process.proxyType = proxyType;
process.pid = pid;
let json = process.json();
let jsonBuffer = Buffer.from(JSON.stringify(json, undefined, 4) + "\n");
fs.writeFileSync(BSTProcess.processPath(), jsonBuffer);
return process;
}
public kill(): boolean {
try {
process.kill(this.pid, "SIGKILL");
return true;
} catch (e) {
console.error("Error killing process[" + this.pid + "] Message: " + e.message);
return false;
}
}
private loadJSON(json: any) {
this.port = json.port;
this.proxyType = json.proxyType;
this.pid = json.pid;
}
private json() {
return {
"port": this.port,
"type": this.proxyType,
"pid": this.pid
};
}
}
// Internet code:
// http://stackoverflow.com/questions/9080085/node-js-find-home-directory-in-platform-agnostic-way
function getUserHome(): string {
return process.env[(process.platform === "win32") ? "USERPROFILE" : "HOME"];
} | the_stack |
* #%L
* %%
* Copyright (C) 2020 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
/*eslint no-use-before-define: "off"*/
import UdsClientAddress from "../../../generated/joynr/system/RoutingTypes/UdsClientAddress";
import * as MessageSerializer from "../MessageSerializer";
import LongTimer from "../../util/LongTimer";
import LoggingManager from "../../system/LoggingManager";
const log = LoggingManager.getLogger("joynr.messaging.uds.UdsClient");
import net = require("net");
import fs = require("fs");
import MagicCookieUtil from "./MagicCookieUtil";
import util from "util";
import JoynrMessage from "../JoynrMessage";
import * as DiagnosticTags from "../../system/DiagnosticTags";
import JoynrRuntimeException from "../../exceptions/JoynrRuntimeException";
interface UdsLibJoynrProvisioning {
socketPath: string;
clientId: string;
connectSleepTimeMs: number;
onMessageCallback: Function;
onFatalRuntimeError: (error: JoynrRuntimeException) => void;
}
class UdsClient {
/**
util.promisify creates the callback which will be called by socket.write once the message was sent.
When the callback is called with an error it will reject the promise, otherwise resolve it.
The arrow function is there to assure that socket.write is called with socket as its this context.
*/
private readonly promisifyWriteToSocket: (marshalledMessage: Buffer) => Promise<void>;
private encodingConf = { binary: true };
private reconnectTimer: any;
private connected: boolean = false;
private closed: boolean = false;
private queuedMessages: any = [];
private readonly onMessageCallback: Function;
private readonly onFatalRuntimeError: (error: JoynrRuntimeException) => void;
private readonly connectSleepTimeMs: number;
private socket: any;
private readonly socketPath: string;
private readonly clientId?: string;
private internBuff: Buffer;
private readonly serializedUdsClientAddress: Buffer;
/**
* @constructor
* @param parameters
* @param parameters.socketPath: path of uds socket to communicate to the server through it
* @param parameters.clientId: client id
* @param parameters.connectSleepTimeMs: interval to try to connect to the server when it is unavailable
* @param parameters.onMessageCallback: callback to be called when a complete message arrives
* @param parameters.onFatalRuntimeError: callback to be called when a fatal error in UdsClient happens that
* prevents further communication via UDS in this runtime
*/
public constructor(parameters: UdsLibJoynrProvisioning) {
this.socketPath = parameters.socketPath;
this.clientId = parameters.clientId;
this.connectSleepTimeMs = parameters.connectSleepTimeMs;
this.onMessageCallback = parameters.onMessageCallback;
this.onFatalRuntimeError = parameters.onFatalRuntimeError;
this.internBuff = Buffer.alloc(0, 0);
this.serializedUdsClientAddress = Buffer.from(
JSON.stringify(
new UdsClientAddress({
id: this.clientId
})
)
);
if (this.serializedUdsClientAddress === undefined || this.serializedUdsClientAddress === null) {
const errorMsg: string = `Error in serializing uds client address ${this.serializedUdsClientAddress}`;
log.debug(errorMsg);
throw new Error(errorMsg);
}
log.info(`Client trying to connect to ${this.socketPath} with clientId=${this.clientId} ...`);
this.promisifyWriteToSocket = util.promisify((marshaledMessage: Buffer, cb: any) =>
this.socket!.write(
MagicCookieUtil.writeMagicCookies(marshaledMessage, MagicCookieUtil.MESSAGE_COOKIE),
this.encodingConf,
cb
)
);
this.onClose = this.onClose.bind(this);
this.onConnect = this.onConnect.bind(this);
this.onReceivedMessage = this.onReceivedMessage.bind(this);
this.onEnd = this.onEnd.bind(this);
this.onError = this.onError.bind(this);
this.establishConnection = this.establishConnection.bind(this);
this.establishConnection();
}
private readonly establishConnection = (): void => {
this.reconnectTimer = undefined;
if (this.closed) {
log.debug(`Connection to the server is closed`);
return;
}
this.socket = net.createConnection({ path: this.socketPath });
this.socket.on(`connect`, this.onConnect);
this.socket.on(`close`, this.onClose);
this.socket.on(`end`, this.onEnd);
this.socket.on(`error`, this.onError);
this.socket.on(`data`, this.onReceivedMessage);
};
private readonly onConnect = (): void => {
this.connected = true;
log.info(`Connected to ${this.socketPath} with clientId ${this.clientId}`);
const initMsgBuff: Buffer = MagicCookieUtil.writeMagicCookies(
this.serializedUdsClientAddress,
MagicCookieUtil.INIT_COOKIE
);
log.trace(
`Send Init Message: ${MagicCookieUtil.getMagicCookieBuff(
initMsgBuff
).toString()}${MagicCookieUtil.getPayloadLength(initMsgBuff).toString()}${MagicCookieUtil.getPayloadBuff(
initMsgBuff
).toString()}`
);
this.socket.write(initMsgBuff, this.encodingConf);
this.sendQueuedMessages();
};
private readonly onClose = (event: { hadError: boolean }) => {
if (this.closed) {
log.info(`UdsClient.onClose called.`);
return;
}
if (!this.connected) {
let isSocketExist = true;
try {
fs.statSync(this.socketPath);
} catch (e) {
isSocketExist = false;
}
if (isSocketExist) {
try {
fs.accessSync(this.socketPath, fs.constants.R_OK && fs.constants.W_OK);
} catch (e) {
log.fatal(e.message);
this.onFatalRuntimeError(
new JoynrRuntimeException({
detailMessage: `Fatal runtime error, stopping all communication permanently: ${e}`
})
);
this.shutdown();
return;
}
}
log.info(`Server is not yet available. Try to connect in ${this.connectSleepTimeMs} ms`);
this.reconnectTimer = LongTimer.setTimeout(this.establishConnection, this.connectSleepTimeMs);
return;
}
let msg = `Fatal runtime error, stopping all communication permanently: `;
if (event.hadError) {
msg += `The socket had a transmission error.`;
} else {
msg += `The server terminated the connection.`;
}
log.fatal(msg);
this.onFatalRuntimeError(new JoynrRuntimeException({ detailMessage: msg }));
this.shutdown();
};
private readonly onEnd = () => {
if (this.closed) {
log.info(`UdsClient.onEnd called.`);
} else {
const msg =
"Fatal runtime error, stopping all communication permanently: The server closed the connection.";
log.fatal(msg);
this.onFatalRuntimeError(new JoynrRuntimeException({ detailMessage: msg }));
this.shutdown();
}
};
private readonly onError = (event: { err: Error }) => {
if (event.err) {
const msg = `UdsClient.onError called: ${event.err}`;
log.fatal(msg);
this.onFatalRuntimeError(
new JoynrRuntimeException({
detailMessage: `Fatal runtime error, stopping all communication permanently: ${msg}`
})
);
this.shutdown();
}
};
private readonly onReceivedMessage = (data: Buffer): void => {
// append what we received to the former received data
this.internBuff = Buffer.concat([this.internBuff, data]);
while (this.processReceivedBuffer()) {}
};
private processReceivedBuffer(): boolean {
if (Buffer.byteLength(this.internBuff) < MagicCookieUtil.MAGIC_COOKIE_AND_PAYLOAD_LENGTH) {
// received little amount of bytes, not enough to process them. continue receiving
return false;
}
// we received at least amount of magic cookie and the length of serialized joynr message.
// it might be a huge buffer which contains several messages
if (!MagicCookieUtil.checkCookie(this.internBuff)) {
this.onFatalRuntimeError(
new JoynrRuntimeException({
detailMessage: `Fatal runtime error, stopping all communication permanently: Received invalid cookies ${MagicCookieUtil.getMagicCookieBuff(
this.internBuff
).toString()}. Close the connection.`
})
);
this.shutdown();
return false;
}
const serializedJoynrMessageLength: number = MagicCookieUtil.getPayloadLength(this.internBuff);
// message is incomplete. Already buffered, continue receiving
if (this.internBuff.length < MagicCookieUtil.MAGIC_COOKIE_AND_PAYLOAD_LENGTH + serializedJoynrMessageLength) {
return false;
}
// internBuff has at least one complete message
const extractMsgBuff: Buffer = Buffer.from(
this.internBuff.subarray(
MagicCookieUtil.MAGIC_COOKIE_AND_PAYLOAD_LENGTH,
MagicCookieUtil.MAGIC_COOKIE_AND_PAYLOAD_LENGTH + serializedJoynrMessageLength
)
);
// adjust internBuff after extracting the message
this.internBuff = this.internBuff.slice(
MagicCookieUtil.MAGIC_COOKIE_AND_PAYLOAD_LENGTH + serializedJoynrMessageLength
);
this.processExtractedMessage(extractMsgBuff);
return true;
}
private processExtractedMessage(extractMsgBuff: Buffer): void {
let joynrMessage;
try {
joynrMessage = MessageSerializer.parse(extractMsgBuff);
} catch (e) {
const msg = `Fatal runtime error, stopping all communication permanently: ${e}, dropping the message!`;
log.fatal(msg);
this.onFatalRuntimeError(
new JoynrRuntimeException({
detailMessage: msg
})
);
this.shutdown();
return;
}
if (this.onMessageCallback) {
try {
if (joynrMessage) {
this.onMessageCallback(joynrMessage);
}
} catch (e) {
log.fatal(`Error from onMessageCallback ${e}`);
this.onFatalRuntimeError(
new JoynrRuntimeException({
detailMessage: `Fatal runtime error, stopping all communication permanently: Error from onMessageCallback: ${e}`
})
);
this.shutdown();
return;
}
}
}
public get numberOfQueuedMessages(): number {
return this.queuedMessages.length;
}
private sendQueuedMessages(): void {
log.debug(`Sending queued messages if any: ${this.queuedMessages.length} queued.`);
try {
while (this.queuedMessages.length) {
const queuedMessageBuff = this.queuedMessages.shift();
this.writeToSocket(queuedMessageBuff);
}
} catch (e) {
const msg = `Sending queued messages failed. It fails with ${e}`;
log.fatal(msg);
this.onFatalRuntimeError(
new JoynrRuntimeException({
detailMessage: `Fatal runtime error, stopping all communication permanently: ${msg}`
})
);
this.shutdown();
}
return;
}
private serializeJoynrMessage(joynrMessage: JoynrMessage): Buffer | undefined {
let marshaledMessage;
try {
marshaledMessage = MessageSerializer.stringify(joynrMessage);
} catch (e) {
log.error(
`Could not marshal joynrMessage: ${DiagnosticTags.forJoynrMessage(joynrMessage)}. It failed with ${e}.`
);
}
return marshaledMessage;
}
/**
* @param joynrMessage the joynr message to transmit
*/
public async send(joynrMessage: JoynrMessage): Promise<void> {
log.info(`>>> OUTGOING >>> message: ${joynrMessage.msgId}`);
let marshaledMessage;
let serializingTries = 2;
while (serializingTries > 0) {
--serializingTries;
marshaledMessage = this.serializeJoynrMessage(joynrMessage);
if (marshaledMessage) {
break;
}
}
if (!marshaledMessage) {
log.error(`Discarding the message because of a failure in serializing it.`);
} else if (this.socket !== null && this.connected && this.socket!.readyState === "open") {
await this.sendInternal(marshaledMessage);
} else if (!this.closed) {
log.debug(`Not connected, push new messages to the back of the queue`);
this.queuedMessages.push(marshaledMessage);
} else {
log.error(
`Dropping message because connection is already closed. ${DiagnosticTags.forJoynrMessage(joynrMessage)}`
);
}
}
private async sendInternal(marshaledMessage: Buffer): Promise<void> {
this.writeToSocket(marshaledMessage);
}
private writeToSocket(marshaledMessage: Buffer): void {
this.socket!.write(
MagicCookieUtil.writeMagicCookies(marshaledMessage, MagicCookieUtil.MESSAGE_COOKIE),
this.encodingConf
);
}
/**
* Normally the UdsClient.send api automatically resolves the Promise
* when it's called. But this doesn't mean that the data was actually
* written out. This method is a helper for a graceful shutdown which delays
* the resolving of the UdsClient.send Promise till the data is
* written out, to make sure that unsubscribe messages are successfully sent.
*/
public enableShutdownMode(): void {
this.sendInternal = this.promisifyWriteToSocket;
}
/**
* Ends connection to the socket
*/
public shutdown(callback?: Function): void {
if (this.closed && this.socket === null) {
return;
}
log.info(`shutdown of uds client is invoked`);
this.closed = true;
if (this.reconnectTimer !== undefined) {
LongTimer.clearTimeout(this.reconnectTimer);
this.reconnectTimer = undefined;
}
if (this.socket) {
this.socket.end(callback);
delete this.socket;
this.socket = null;
}
}
}
export = UdsClient; | the_stack |
import { Linter, LinterOptions, ProgramFactory } from './linter';
import {
LintResult,
FileSummary,
Configuration,
AbstractProcessor,
DirectoryService,
ConfigurationError,
MessageHandler,
FileFilterFactory,
Severity,
} from '@fimbul/ymir';
import * as path from 'path';
import * as ts from 'typescript';
import * as glob from 'glob';
import { unixifyPath, hasSupportedExtension, addUnique, flatMap, hasParseErrors, invertChangeRange } from './utils';
import { Minimatch, IMinimatch } from 'minimatch';
import { ProcessorLoader } from './services/processor-loader';
import { injectable } from 'inversify';
import { CachedFileSystem, FileKind } from './services/cached-file-system';
import { ConfigurationManager } from './services/configuration-manager';
import { ProjectHost } from './project-host';
import debug = require('debug');
import { normalizeGlob } from 'normalize-glob';
import { ProgramStateFactory } from './services/program-state';
import { createConfigHash } from './config-hash';
const log = debug('wotan:runner');
export interface LintOptions {
config: string | undefined;
files: ReadonlyArray<string>;
exclude: ReadonlyArray<string>;
project: ReadonlyArray<string>;
references: boolean;
fix: boolean | number;
extensions: ReadonlyArray<string> | undefined;
reportUselessDirectives: Severity | boolean | undefined;
cache: boolean;
}
interface NormalizedOptions extends Pick<LintOptions, Exclude<keyof LintOptions, 'files'>> {
files: ReadonlyArray<NormalizedGlob>;
}
interface NormalizedGlob {
hasMagic: boolean;
normalized: string[];
}
@injectable()
export class Runner {
constructor(
private fs: CachedFileSystem,
private configManager: ConfigurationManager,
private linter: Linter,
private processorLoader: ProcessorLoader,
private directories: DirectoryService,
private logger: MessageHandler,
private filterFactory: FileFilterFactory,
private programStateFactory: ProgramStateFactory,
) {}
public lintCollection(options: LintOptions): LintResult {
const config = options.config !== undefined ? this.configManager.loadLocalOrResolved(options.config) : undefined;
const cwd = this.directories.getCurrentDirectory();
const files = options.files.map(
(pattern) => ({hasMagic: glob.hasMagic(pattern), normalized: Array.from(normalizeGlob(pattern, cwd))}),
);
const exclude = flatMap(options.exclude, (pattern) => normalizeGlob(pattern, cwd));
const linterOptions: LinterOptions = {
reportUselessDirectives: options.reportUselessDirectives
? options.reportUselessDirectives === true
? 'error'
: options.reportUselessDirectives
: undefined,
};
if (options.project.length === 0 && options.files.length !== 0)
return this.lintFiles({...options, files, exclude}, config, linterOptions);
return this.lintProject({...options, files, exclude}, config, linterOptions);
}
private *lintProject(options: NormalizedOptions, config: Configuration | undefined, linterOptions: LinterOptions): LintResult {
const processorHost = new ProjectHost(
this.directories.getCurrentDirectory(),
config,
this.fs,
this.configManager,
this.processorLoader,
);
for (let {files, program, configFilePath: tsconfigPath} of
this.getFilesAndProgram(options.project, options.files, options.exclude, processorHost, options.references)
) {
const programState = options.cache ? this.programStateFactory.create(program, processorHost, tsconfigPath) : undefined;
let invalidatedProgram = false;
const factory: ProgramFactory = {
getCompilerOptions() {
return program.getCompilerOptions();
},
getProgram() {
if (invalidatedProgram) {
log('updating invalidated program');
program = processorHost.updateProgram(program);
invalidatedProgram = false;
}
return program;
},
};
for (const file of files) {
if (options.config === undefined)
config = this.configManager.find(file);
const mapped = processorHost.getProcessedFileInfo(file);
const originalName = mapped === undefined ? file : mapped.originalName;
const effectiveConfig = config && this.configManager.reduce(config, originalName);
if (effectiveConfig === undefined)
continue;
let sourceFile = program.getSourceFile(file)!;
const originalContent = mapped === undefined ? sourceFile.text : mapped.originalContent;
let summary: FileSummary;
const fix = shouldFix(sourceFile, options, originalName);
const configHash = programState === undefined ? undefined : createConfigHash(effectiveConfig, linterOptions);
const resultFromCache = programState?.getUpToDateResult(sourceFile.fileName, configHash!);
if (fix) {
let updatedFile = false;
summary = this.linter.lintAndFix(
sourceFile,
originalContent,
effectiveConfig,
(content, range) => {
invalidatedProgram = true;
const oldContent = sourceFile.text;
sourceFile = ts.updateSourceFile(sourceFile, content, range);
const hasErrors = hasParseErrors(sourceFile);
if (hasErrors) {
log("Autofixing caused syntax errors in '%s', rolling back", sourceFile.fileName);
sourceFile = ts.updateSourceFile(sourceFile, oldContent, invertChangeRange(range));
} else {
updatedFile = true;
}
// either way we need to store the new SourceFile as the old one is now corrupted
processorHost.updateSourceFile(sourceFile);
return hasErrors ? undefined : sourceFile;
},
fix === true ? undefined : fix,
factory,
mapped?.processor,
linterOptions,
// pass cached results so we can apply fixes from cache
resultFromCache,
);
if (updatedFile)
programState?.update(factory.getProgram(), sourceFile.fileName);
} else {
summary = {
findings: resultFromCache ?? this.linter.getFindings(
sourceFile,
effectiveConfig,
factory,
mapped?.processor,
linterOptions,
),
fixes: 0,
content: originalContent,
};
}
if (programState !== undefined && resultFromCache !== summary.findings)
programState.setFileResult(file, configHash!, summary.findings);
yield [originalName, summary];
}
programState?.save();
}
}
private *lintFiles(options: NormalizedOptions, config: Configuration | undefined, linterOptions: LinterOptions): LintResult {
let processor: AbstractProcessor | undefined;
for (const file of getFiles(options.files, options.exclude, this.directories.getCurrentDirectory())) {
if (options.config === undefined)
config = this.configManager.find(file);
const effectiveConfig = config && this.configManager.reduce(config, file);
if (effectiveConfig === undefined)
continue;
let originalContent: string | undefined;
let name: string;
let content: string;
if (effectiveConfig.processor) {
const ctor = this.processorLoader.loadProcessor(effectiveConfig.processor);
if (hasSupportedExtension(file, options.extensions)) {
name = file;
} else {
name = file + ctor.getSuffixForFile({
fileName: file,
getSettings: () => effectiveConfig.settings,
readFile: () => originalContent = this.fs.readFile(file),
});
if (!hasSupportedExtension(name, options.extensions))
continue;
}
if (originalContent === undefined) // might be initialized by the processor requesting the file content
originalContent = this.fs.readFile(file);
processor = new ctor({
source: originalContent,
sourceFileName: file,
targetFileName: name,
settings: effectiveConfig.settings,
});
content = processor.preprocess();
} else if (hasSupportedExtension(file, options.extensions)) {
processor = undefined;
name = file;
content = originalContent = this.fs.readFile(file);
} else {
continue;
}
let sourceFile = ts.createSourceFile(name, content, ts.ScriptTarget.ESNext, true);
const fix = shouldFix(sourceFile, options, file);
let summary: FileSummary;
if (fix) {
summary = this.linter.lintAndFix(
sourceFile,
originalContent,
effectiveConfig,
(newContent, range) => {
sourceFile = ts.updateSourceFile(sourceFile, newContent, range);
if (hasParseErrors(sourceFile)) {
log("Autofixing caused syntax errors in '%s', rolling back", sourceFile.fileName);
// Note: 'sourceFile' shouldn't be used after this as it contains invalid code
return;
}
return sourceFile;
},
fix === true ? undefined : fix,
undefined,
processor,
linterOptions,
);
} else {
summary = {
findings: this.linter.getFindings(
sourceFile,
effectiveConfig,
undefined,
processor,
linterOptions,
),
fixes: 0,
content: originalContent,
};
}
yield [file, summary];
}
}
private* getFilesAndProgram(
projects: ReadonlyArray<string>,
patterns: ReadonlyArray<NormalizedGlob>,
exclude: ReadonlyArray<string>,
host: ProjectHost,
references: boolean,
): Iterable<{files: Iterable<string>, program: ts.Program, configFilePath: string}> {
const cwd = unixifyPath(this.directories.getCurrentDirectory());
if (projects.length !== 0) {
projects = projects.map((configFile) => this.checkConfigDirectory(unixifyPath(path.resolve(cwd, configFile))));
} else if (references) {
projects = [this.checkConfigDirectory(cwd)];
} else {
const project = ts.findConfigFile(cwd, (f) => this.fs.isFile(f));
if (project === undefined)
throw new ConfigurationError(`Cannot find tsconfig.json for directory '${cwd}'.`);
projects = [project];
}
const allMatchedFiles: string [] = [];
const include: IMinimatch[] = [];
const nonMagicGlobs: NonMagicGlob[] = [];
for (const pattern of patterns) {
if (!pattern.hasMagic) {
const mm = new Minimatch(pattern.normalized[0]);
nonMagicGlobs.push({raw: pattern.normalized[0], match: mm});
include.push(mm);
} else {
include.push(...pattern.normalized.map((p) => new Minimatch(p)));
}
}
const ex = exclude.map((p) => new Minimatch(p, {dot: true}));
const projectsSeen: string[] = [];
let filesOfPreviousProject: string[] | undefined;
for (const {program, configFilePath} of this.createPrograms(projects, host, projectsSeen, references, isFileIncluded)) {
const ownFiles = [];
const files: string[] = [];
const fileFilter = this.filterFactory.create({program, host});
for (const sourceFile of program.getSourceFiles()) {
if (!fileFilter.filter(sourceFile))
continue;
const {fileName} = sourceFile;
ownFiles.push(fileName);
const originalName = host.getFileSystemFile(fileName)!;
if (!isFileIncluded(originalName))
continue;
files.push(fileName);
allMatchedFiles.push(originalName);
}
// uncache all files of the previous project if they are no longer needed
if (filesOfPreviousProject !== undefined)
for (const oldFile of filesOfPreviousProject)
if (!ownFiles.includes(oldFile))
host.uncacheFile(oldFile);
filesOfPreviousProject = ownFiles;
if (files.length !== 0)
yield {files, program, configFilePath};
}
ensurePatternsMatch(nonMagicGlobs, ex, allMatchedFiles, projectsSeen);
function isFileIncluded(fileName: string) {
return (include.length === 0 || include.some((p) => p.match(fileName))) && !ex.some((p) => p.match(fileName));
}
}
private checkConfigDirectory(fileOrDirName: string): string {
switch (this.fs.getKind(fileOrDirName)) {
case FileKind.NonExistent:
throw new ConfigurationError(`The specified path does not exist: '${fileOrDirName}'`);
case FileKind.Directory: {
const file = unixifyPath(path.join(fileOrDirName, 'tsconfig.json'));
if (!this.fs.isFile(file))
throw new ConfigurationError(`Cannot find a tsconfig.json file at the specified directory: '${fileOrDirName}'`);
return file;
}
default:
return fileOrDirName;
}
}
private* createPrograms(
projects: ReadonlyArray<string> | ReadonlyArray<ts.ResolvedProjectReference | undefined>,
host: ProjectHost,
seen: string[],
references: boolean,
isFileIncluded: (fileName: string) => boolean,
): Iterable<{program: ts.Program, configFilePath: string}> {
for (const configFile of projects) {
if (configFile === undefined)
continue;
const configFilePath = typeof configFile === 'string' ? configFile : configFile.sourceFile.fileName;
if (!addUnique(seen, configFilePath))
continue;
let commandLine;
if (typeof configFile !== 'string') {
({commandLine} = configFile);
} else {
commandLine = host.getParsedCommandLine(configFile);
if (commandLine === undefined)
continue;
}
if (commandLine.errors.length !== 0)
this.logger.warn(ts.formatDiagnostics(commandLine.errors, host));
if (commandLine.fileNames.length !== 0) {
if (!commandLine.options.composite || commandLine.fileNames.some((file) => isFileIncluded(host.getFileSystemFile(file)!))) {
log("Using project '%s'", configFilePath);
let resolvedReferences;
{
// this is in a nested block to allow garbage collection while recursing
const program =
host.createProgram(commandLine.fileNames, commandLine.options, undefined, commandLine.projectReferences);
yield {program, configFilePath};
if (references)
resolvedReferences = program.getResolvedProjectReferences();
}
if (resolvedReferences !== undefined)
yield* this.createPrograms(resolvedReferences, host, seen, true, isFileIncluded);
continue;
}
log("Project '%s' contains no file to lint", configFilePath);
}
if (references) {
if (typeof configFile !== 'string') {
if (configFile.references !== undefined)
yield* this.createPrograms(configFile.references, host, seen, true, isFileIncluded);
} else if (commandLine.projectReferences !== undefined) {
yield* this.createPrograms(
commandLine.projectReferences.map((ref) => this.checkConfigDirectory(ref.path)),
host,
seen,
true,
isFileIncluded,
);
}
}
}
}
}
function getFiles(patterns: ReadonlyArray<NormalizedGlob>, exclude: ReadonlyArray<string>, cwd: string): Iterable<string> {
const result: string[] = [];
const globOptions: glob.IOptions = {
cwd,
nobrace: true, // braces are already expanded
cache: {},
ignore: exclude,
nodir: true,
realpathCache: {},
statCache: {},
symlinks: {},
};
for (const pattern of patterns) {
let matched = pattern.hasMagic;
for (const normalized of pattern.normalized) {
const match = glob.sync(normalized, globOptions);
if (match.length !== 0) {
matched = true;
result.push(...match);
}
}
if (!matched && !isExcluded(pattern.normalized[0], exclude.map((p) => new Minimatch(p, {dot: true}))))
throw new ConfigurationError(`'${pattern.normalized[0]}' does not exist.`);
}
return new Set(result.map(unixifyPath)); // deduplicate files
}
interface NonMagicGlob {
raw: string;
match: IMinimatch;
}
function ensurePatternsMatch(include: NonMagicGlob[], exclude: IMinimatch[], files: string[], projects: ReadonlyArray<string>) {
for (const pattern of include)
if (!isExcluded(pattern.raw, exclude) && !files.some((f) => pattern.match.match(f)))
throw new ConfigurationError(`'${pattern.raw}' is not included in any of the projects: '${projects.join("', '")}'.`);
}
function isExcluded(file: string, exclude: IMinimatch[]): boolean {
for (const e of exclude)
if (e.match(file))
return true;
return false;
}
function shouldFix(sourceFile: ts.SourceFile, options: Pick<LintOptions, 'fix'>, originalName: string) {
if (options.fix && hasParseErrors(sourceFile)) {
log("Not fixing '%s' because of parse errors.", originalName);
return false;
}
return options.fix;
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* The resource model definition representing SKU
*/
export interface Sku {
/**
* The name of the HealthBot SKU. Possible values include: 'F0', 'S1', 'C0'
*/
name: SkuName;
}
/**
* Read only system data
*/
export interface SystemData {
/**
* The identity that created the resource.
*/
createdBy?: string;
/**
* The type of identity that created the resource. Possible values include: 'User',
* 'Application', 'ManagedIdentity', 'Key'
*/
createdByType?: IdentityType;
/**
* The timestamp of resource creation (UTC)
*/
createdAt?: Date;
/**
* The identity that last modified the resource.
*/
lastModifiedBy?: string;
/**
* The type of identity that last modified the resource. Possible values include: 'User',
* 'Application', 'ManagedIdentity', 'Key'
*/
lastModifiedByType?: IdentityType;
/**
* The timestamp of resource last modification (UTC)
*/
lastModifiedAt?: Date;
}
/**
* The resource model definition for a ARM tracked top level resource
*/
export interface Resource extends BaseResource {
/**
* Fully qualified resource Id for the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* The name of the resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* The type of the resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* Metadata pertaining to creation and last modification of the resource
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly systemData?: SystemData;
}
/**
* The resource model definition for a ARM tracked top level resource
*/
export interface TrackedResource extends Resource {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* The geo-location where the resource lives
*/
location: string;
}
/**
* The properties of a HealthBot. The Health Bot Service is a cloud platform that empowers
* developers in Healthcare organizations to build and deploy their compliant, AI-powered virtual
* health assistants and health bots, that help them improve processes and reduce costs.
* @summary HealthBotProperties
*/
export interface HealthBotProperties {
/**
* The provisioning state of the Healthbot resource.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly provisioningState?: string;
/**
* The link.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly botManagementPortalLink?: string;
}
/**
* HealthBot resource definition
*/
export interface HealthBot extends TrackedResource {
/**
* SKU of the HealthBot.
*/
sku: Sku;
/**
* The set of properties specific to Healthbot resource.
*/
properties?: HealthBotProperties;
}
/**
* Parameters for updating a HealthBot.
*/
export interface HealthBotUpdateParameters {
/**
* Tags for a HealthBot.
*/
tags?: { [propertyName: string]: string };
/**
* SKU of the HealthBot.
*/
sku?: Sku;
}
/**
* The response returned from validation process
* @summary ValidationResult
*/
export interface ValidationResult {
/**
* The status code of the response validation.
*/
status?: string;
}
/**
* The resource management error additional info.
*/
export interface ErrorAdditionalInfo {
/**
* The additional info type.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
/**
* The additional info.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly info?: any;
}
/**
* The error object.
*/
export interface ErrorError {
/**
* The error code.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly code?: string;
/**
* The error message.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
/**
* The error target.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly target?: string;
/**
* The error details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly details?: ErrorModel[];
/**
* The error additional info.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly additionalInfo?: ErrorAdditionalInfo[];
}
/**
* The resource management error response.
*/
export interface ErrorModel {
/**
* The error object.
*/
error?: ErrorError;
}
/**
* Operation display payload
*/
export interface OperationDisplay {
/**
* Resource provider of the operation
*/
provider?: string;
/**
* Resource of the operation
*/
resource?: string;
/**
* Localized friendly name for the operation
*/
operation?: string;
/**
* Localized friendly description for the operation
*/
description?: string;
}
/**
* Operation detail payload
*/
export interface OperationDetail {
/**
* Name of the operation
*/
name?: string;
/**
* Indicates whether the operation is a data action
*/
isDataAction?: boolean;
/**
* Display of the operation
*/
display?: OperationDisplay;
/**
* Origin of the operation
*/
origin?: string;
/**
* Additional properties.
*/
properties?: any;
}
/**
* An interface representing HealthbotClientOptions.
*/
export interface HealthbotClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* The list of Healthbot operation response.
* @extends Array<HealthBot>
*/
export interface BotResponseList extends Array<HealthBot> {
/**
* The link used to get the next page of bot service resources.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly nextLink?: string;
}
/**
* @interface
* Available operations of the service
* @extends Array<OperationDetail>
*/
export interface AvailableOperations extends Array<OperationDetail> {
/**
* URL client should use to fetch the next page (per server side paging).
* It's null for now, added for future use.
*/
nextLink?: string;
}
/**
* Defines values for SkuName.
* Possible values include: 'F0', 'S1', 'C0'
* @readonly
* @enum {string}
*/
export type SkuName = 'F0' | 'S1' | 'C0';
/**
* Defines values for IdentityType.
* Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key'
* @readonly
* @enum {string}
*/
export type IdentityType = 'User' | 'Application' | 'ManagedIdentity' | 'Key';
/**
* Contains response data for the create operation.
*/
export type BotsCreateResponse = HealthBot & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: HealthBot;
};
};
/**
* Contains response data for the get operation.
*/
export type BotsGetResponse = HealthBot & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: HealthBot;
};
};
/**
* Contains response data for the update operation.
*/
export type BotsUpdateResponse = HealthBot & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: HealthBot;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type BotsListByResourceGroupResponse = BotResponseList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: BotResponseList;
};
};
/**
* Contains response data for the list operation.
*/
export type BotsListResponse = BotResponseList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: BotResponseList;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type BotsBeginCreateResponse = HealthBot & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: HealthBot;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type BotsListByResourceGroupNextResponse = BotResponseList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: BotResponseList;
};
};
/**
* Contains response data for the listNext operation.
*/
export type BotsListNextResponse = BotResponseList & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: BotResponseList;
};
};
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = AvailableOperations & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AvailableOperations;
};
};
/**
* Contains response data for the listNext operation.
*/
export type OperationsListNextResponse = AvailableOperations & {
/**
* The underlying HTTP response.
*/
_response: msRest.HttpResponse & {
/**
* The response body as text (string format)
*/
bodyAsText: string;
/**
* The response body as parsed JSON or XML
*/
parsedBody: AvailableOperations;
};
}; | the_stack |
import { krakenPrint } from './bridge';
const SEPARATOR = ' ';
const INTERPOLATE = /%[sdifoO]/g;
const DIMENSIONS = 3;
const INDENT = ' ';
const times = {};
const counts = {};
const INDEX = '(index)';
const VALUE = '(value)';
const PLACEHOLDER = ' '; // empty placeholder
let groupIndent = '';
function printer(message: string, level?: string) {
if (groupIndent.length !== 0) {
if (message.includes('\n')) {
message = message.replace(/\n/g, `\n${groupIndent}`);
}
message = groupIndent + message;
}
krakenPrint(message, level);
}
/**
* formatter({x:2, y:8}) === '{x: 2, y: 8}'
* @param {*} obj
* @param {Number} limit dimension of objects
* @param {Array} stack of parent objects
* @return {String} string representation of input
*/
function formatter(obj: any, limit: number, stack: Array<any>): string {
var type = typeof obj;
switch (type) {
case 'string':
return `'${obj}'`;
case 'function':
break;
case 'object':
if (obj === null) {
return 'null';
}
break;
default:
return '' + obj;
}
var prefix;
var kind = Object.prototype.toString.call(obj).slice(8, -1);
if (kind == 'Object') {
prefix = '';
} else {
prefix = kind + ' ';
var primitive;
switch (typeof obj) {
case 'object':
case 'function':
break;
case 'string':
primitive = `'${obj}'`;
default:
primitive = '' + obj; // Use "+" convert undefined to "undefined"
}
if (primitive) {
prefix += primitive + ' ';
}
}
if (!limit) {
return prefix + '{...}';
}
// Check circular references
var stackLength = stack.length;
for (var s = 0; s < stackLength; s++) {
if (stack[s] === obj) {
return '#';
}
}
stack[stackLength++] = obj;
var indent = INDENT.repeat(stackLength);
var keys = Object.getOwnPropertyNames(obj);
var result = prefix + '{';
if (!keys.length) {
return result + '}';
}
var items = [];
for (var n = 0; n < keys.length; n++) {
let key = keys[n];
var value = formatter(obj[key], limit - 1, [...stack]);
items.push('\n' + indent + key + ': ' + value);
}
return result + items.join(', ') + '\n' + INDENT.repeat(stackLength - 1) + '}';
}
function inspect(obj: any, within?: boolean): string {
var result = '';
if (obj && obj.nodeType == 1) {
// Is element?
result = '<' + obj.tagName.toLowerCase();
for (var i = 0, ii = obj.attributes.length; i < ii; i++) {
if (obj.attributes[i].specified) {
result += ' ' + obj.attributes[i].name + '="' + obj.attributes[i].value + '"';
}
}
if (obj.childNodes && obj.childNodes.length === 0) {
result += '/';
}
return result + '>';
}
var kind = Object.prototype.toString.call(obj).slice(8, -1);
switch (kind) {
case 'Null':
return 'null';
case 'Undefined':
return 'undefined';
case 'String':
return within ? `'${obj}'` : obj;
case 'Function':
return 'ƒ ()';
case 'Number':
case 'Boolean':
case 'Date':
case 'RegExp':
return obj.toString();
case 'Array':
var itemList = obj.map((item: any) => inspect(item, true));
return '[' + itemList.join(', ') + ']';
default:
if (typeof obj === 'object') {
var prefix;
if (kind == 'Map') {
let mapList = Array.from(obj.entries()).map((item: any) => item[0] + ' => ' + inspect(item[1], true)).join(', ');
return 'Map {' + mapList + '}';
// return JSON.stringify(Array.from(obj.entries()));
} else if (kind == 'Set') {
return 'Set { ' + Array.from(obj).map((item: any) => inspect(item, true)).join(', ') + '}'
} else if (kind == 'Object') {
prefix = '';
} else {
prefix = kind + ' ';
}
if (within) {
return prefix + '{...}';
}
if (Object.getOwnPropertyNames) {
var keys = Object.getOwnPropertyNames(obj);
} else {
keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
}
result = prefix + '{';
if (!keys.length) {
return result + "}";
}
keys = keys.sort();
var properties = [];
for (var n = 0; n < keys.length; n++) {
key = keys[n];
try {
var value = inspect(obj[key], true);
properties.push(key + ': ' + value);
} catch (e) { }
}
return result + properties.join(', ') + '}';
} else {
return '' + obj;
}
}
}
function logger(allArgs: any) {
var args = Array.prototype.slice.call(allArgs, 0);
var firstArg = args[0];
var result = [];
if (typeof firstArg === 'string' && INTERPOLATE.test(firstArg)) {
args.shift();
result.push(firstArg.replace(INTERPOLATE, function () {
return inspect(args.shift());
}));
}
for (var i = 0; i < args.length; i++) {
result.push(inspect(args[i]));
}
return result.join(SEPARATOR);
}
export const console = {
log(...args: any) {
printer(logger(arguments));
},
info(...args: any) {
printer(logger(arguments), 'info');
},
warn(...args: any) {
printer(logger(arguments), 'warn');
},
debug(...args: any) {
printer(logger(arguments), 'debug');
},
error(...args: any) {
printer(logger(arguments), 'error');
},
dirxml(...args: any) {
printer(logger(arguments));
},
dir(...args: any) {
var result = [];
for (var i = 0; i < arguments.length; i++) {
result.push(formatter(arguments[i], DIMENSIONS, []));
}
printer(result.join(SEPARATOR));
},
table(data: Array<any>, filterColumns: Array<string>) {
if (data === null || typeof data !== 'object') {
return console.log(data);
}
const rows: any[] = [];
const columns: string[] = [];
const index: any[] = [];
let hasValueColumn = false;
for (var key in data) {
if (data.hasOwnProperty(key)) {
let row = data[key];
index.push(key);
rows.push(row);
if (typeof row === 'object' && data !== null) {
Object.keys(row).forEach(columnName => {
if (columns.indexOf(columnName) === -1) {
if (Array.isArray(filterColumns) && filterColumns.length !== 0) {
if (filterColumns.indexOf(columnName) !== -1) {
columns.push(columnName);
}
} else {
columns.push(columnName);
}
}
});
} else {
hasValueColumn = true;
}
}
}
// Unshift (index) or push (value) in columns
columns.unshift(INDEX);
if (hasValueColumn) columns.push(VALUE);
var stringRows: any[] = [];
var columnWidths: number[] = [];
// Convert each cell to a string. Also
// figure out max cell width for each column
columns.forEach((columnName, columnIndex) => {
columnWidths[columnIndex] = columnName.length;
rows.forEach((row, rowIndex) => {
let cellString: string;
if (columnName === INDEX) cellString = index[rowIndex];
else if (row[columnName] !== undefined) cellString = logger([row[columnName]]);
else if (columnName === VALUE && (row === null || typeof row !== 'object')) cellString = logger([row]);
else cellString = PLACEHOLDER; // empty
stringRows[rowIndex] = stringRows[rowIndex] || [];
stringRows[rowIndex][columnIndex] = cellString;
// Update to the max length value in column
columnWidths[columnIndex] = Math.max(columnWidths[columnIndex], cellString.length);
});
});
// Join all elements in the row into a single string with | separators
// (appends extra spaces to each cell to make separators | aligned)
function joinRow(row: any[], space = ' ', sep = '│') {
var cells = row.map(function (cell, i) {
var extraSpaces = ' '.repeat(columnWidths[i] - cell.length);
return cell + extraSpaces;
});
return cells.join(space + sep + space);
}
var separators = columnWidths.map(function (columnWidth) {
return '─'.repeat(columnWidth);
});
var sep = joinRow(separators, '─', '─');
var header = joinRow(columns);
var separatorRow = joinRow(separators, '─');
var table = [sep, header, separatorRow];
for (var i = 0; i < rows.length; i++) {
table.push(joinRow(stringRows[i]));
}
table.push(sep);
console.log(table.join('\n'));
},
trace(...args: any) {
var traceStack = 'Trace:';
var argsInfo = logger(arguments);
if (argsInfo) {
traceStack += (' ' + argsInfo);
}
var stack = new Error().stack;
if (stack) {
// Compilable with V8 that has Error prefix
stack = stack.replace(/^Error\n/g, '');
// Slice the top trace is the current function,
// and compilable with JSC that without space indent
stack = stack.split('\n').slice(1).map(line => INDENT + line.trim()).join('\n');
traceStack += ('\n' + stack);
}
printer(traceStack);
},
// Defined by: https://console.spec.whatwg.org/#count
count(label = 'default') {
label = String(label);
if (counts[label] === undefined) {
counts[label] = 1;
} else {
counts[label]++;
}
console.info(label + ' ' + counts[label]);
},
// Defined by: https://console.spec.whatwg.org/#countreset
countReset(label = 'default') {
label = String(label);
if (counts[label] === undefined) {
console.warn(`Count for '${label}' does not exist`);
} else {
counts[label] = 0;
}
},
assert(expression: boolean, ...args: Array<any>) {
if (!expression) {
let msg = args.join(' ');
throw new Error('Assertion failed:' + msg);
}
},
time(label = 'default') {
label = String(label);
if (times[label] === undefined) {
times[label] = (new Date).getTime();
} else {
console.warn(`Timer '${label}' already exists`);
}
},
timeLog(label = 'default', ...args: Array<any>) {
label = String(label);
var start = times[label];
if (start) {
var end = (new Date).getTime();
console.log(label + ': ' + (end - start) + 'ms', ...args);
} else {
console.warn(`Timer '${label}' does not exist`);
}
},
timeEnd(label = 'default') {
label = String(label);
var start = times[label];
if (start) {
var end = (new Date).getTime();
console.info(label + ': ' + (end - start) + 'ms');
delete times[label];
} else {
console.warn(`Timer '${label}' does not exist`);
}
},
group(...data: Array<any>) {
if (data.length > 0) {
console.log(...data);
}
groupIndent += INDENT;
},
groupCollapsed(...data: Array<any>) {
console.group(...data);
},
groupEnd() {
groupIndent = groupIndent.slice(0, groupIndent.length - 2);
},
clear() { }
} | the_stack |
import { LOCALE_ID } from '@angular/core';
import { createHostFactory, SpectatorHost } from '@ngneat/spectator';
import { format, startOfDay, startOfMonth } from 'date-fns';
import { zonedTimeToUtc } from 'date-fns-tz';
import { MockComponent } from 'ng-mocks';
import { CalendarComponent, IconComponent } from '..';
import { TestHelper } from '../../testing/test-helper';
import { WindowRef } from '../../types/window-ref';
import { CardComponent } from '../card';
import { DropdownComponent } from '../dropdown/dropdown.component';
import { ItemComponent } from '../item';
import { RadioComponent } from '../radio';
import { CalendarYearNavigatorConfig } from './options/calendar-year-navigator-config';
// NOTE: when specifying multiple input properties, set selectedDate
// as the last one. This makes the component update without the need to
// explicitly call spectator.component.ngOnChanges()
describe('CalendarComponent', () => {
let spectator: SpectatorHost<CalendarComponent>;
const createHost = createHostFactory({
component: CalendarComponent,
declarations: [
CalendarComponent,
MockComponent(IconComponent),
DropdownComponent,
RadioComponent,
CardComponent,
ItemComponent,
],
providers: [
{
provide: LOCALE_ID,
// i.e. en-US. The week should start on Monday regardlessly
useValue: 'en-GB',
},
{
provide: WindowRef,
useValue: <WindowRef>{ nativeWindow: window },
},
],
imports: [TestHelper.ionicModuleForTest],
});
beforeEach(() => {
spectator = createHost('<kirby-calendar></kirby-calendar>');
});
it('should create', () => {
expect(spectator.component).toBeTruthy();
});
it('should initially render the current month if selectedDate is not specified', () => {
const currentDay = startOfDay(new Date());
const currentMonth = startOfMonth(new Date());
verifyMonthAndYear(format(currentMonth, 'MMMM yyyy'));
expect(spectator.query('.day.today')).toHaveText(format(currentDay, 'd'));
});
it('should initially render the month of selectedDate if specified', () => {
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
verifyMonthAndYear('August 1997');
const headerTexts = trimmedTexts('th');
expect(headerTexts).toEqual(['M', 'T', 'W', 'T', 'F', 'S', 'S']);
const dayTexts = trimmedTexts('.day.current-month');
expect(dayTexts.slice(0, 5)).toEqual(['1', '2', '3', '4', '5']);
expect(dayTexts.length).toEqual(31);
});
it('should be possible to specify which day is today by passing todayDate', () => {
spectator.setInput('todayDate', localMidnightDate('1997-08-30'));
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
expect(spectator.query('.day.today')).toHaveText('30');
});
it('should make it possible to navigate past and future months', () => {
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
spectator.click(SEL_NAV_BACK);
verifyMonthAndYear('July 1997');
spectator.click(SEL_NAV_FORWARD);
verifyMonthAndYear('August 1997');
spectator.click(SEL_NAV_FORWARD);
verifyMonthAndYear('September 1997');
spectator.click(SEL_NAV_FORWARD);
spectator.click(SEL_NAV_FORWARD);
spectator.click(SEL_NAV_FORWARD);
spectator.click(SEL_NAV_FORWARD);
verifyMonthAndYear('January 1998');
});
it('should not be possible to navigate to any month preceding minDate, if specified', () => {
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
spectator.setInput('minDate', localMidnightDate('1997-06-15'));
spectator.click(SEL_NAV_BACK);
spectator.click(SEL_NAV_BACK);
verifyMonthAndYear('June 1997');
expect(spectator.query(SEL_NAV_BACK)).toBeDisabled();
spectator.click(SEL_NAV_BACK);
verifyMonthAndYear('June 1997');
});
it('should not be possible to navigate to any month exceeding maxDate, if specified', () => {
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
spectator.setInput('maxDate', localMidnightDate('1997-10-01'));
spectator.click(SEL_NAV_FORWARD);
spectator.click(SEL_NAV_FORWARD);
verifyMonthAndYear('October 1997');
expect(spectator.query(SEL_NAV_FORWARD)).toBeDisabled();
spectator.click(SEL_NAV_FORWARD);
verifyMonthAndYear('October 1997');
});
it('should emit a dateChange event when a valid date is clicked', () => {
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
const captured = captureDateChangeEvents();
clickDayOfMonth(14);
expect(captured.event).toEqual(localMidnightDate('1997-08-14'));
});
it('should not emit a dateChange event when selectedDate is changed from the outside', () => {
const captured = captureDateChangeEvents();
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
expect(captured.event).toBeUndefined();
});
it('should not emit a dateChange event if disableWeekends is true and a weekend date is clicked', () => {
spectator.setInput('disableWeekends', true);
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
const captured = captureDateChangeEvents();
clickDayOfMonth(24); // August 24th is a Sunday
expect(captured.event).toBeUndefined();
});
it('should not emit a dateChange event if disablePastDates is true and a date in the past is clicked', () => {
spectator.setInput('disablePastDates', true);
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
spectator.setInput('todayDate', localMidnightDate('1997-08-29'));
const captured = captureDateChangeEvents();
clickDayOfMonth(1); // August 1st is in the past
expect(captured.event).toBeUndefined();
});
it('should not emit a dateChange event if disableFutureDates is true and a date in the future is clicked', () => {
spectator.setInput('disableFutureDates', true);
spectator.setInput('todayDate', localMidnightDate('1997-08-29'));
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
const captured = captureDateChangeEvents();
clickDayOfMonth(31); // August 31st is in the future
expect(captured.event).toBeUndefined();
});
it('should not emit a dateChange event if clicking a date that was passed in disabledDates', () => {
spectator.setInput('disabledDates', ['1997-08-25', '1997-08-26'].map(localMidnightDate));
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
const captured = captureDateChangeEvents();
clickDayOfMonth(26); // August 26st was explicitly disabled
expect(captured.event).toBeUndefined();
});
it('should not emit a dateChange event if clicking the already selected date', () => {
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
const captured = captureDateChangeEvents();
clickDayOfMonth(29);
expect(captured.event).toBeUndefined();
});
it('should always emit a dateChange event when clicking today if alwaysEnableToday is set to true', () => {
const today = localMidnightDate('1997-08-28');
spectator.setInput('disabledDates', [today]);
spectator.setInput('todayDate', today);
spectator.setInput('alwaysEnableToday', true);
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
const captured = captureDateChangeEvents();
clickDayOfMonth(28); // August 28th is was disabled but we override
expect(captured.event).toEqual(today);
});
it('should emit dateChange event as UTC midnights when timezone is set to UTC', () => {
spectator.setInput('timezone', 'UTC');
spectator.setInput('selectedDate', utcMidnightDate('1997-08-29'));
const captured = captureDateChangeEvents();
clickDayOfMonth(14);
expect(captured.event).toEqual(utcMidnightDate('1997-08-14'));
});
it('should emit dateSelect event when clicking a date that is not already selected', () => {
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
const captured = captureDateSelectEvents();
clickDayOfMonth(14);
expect(captured.event).toEqual(localMidnightDate('1997-08-14'));
});
it('should emit dateSelect event when clicking the already selected date', () => {
spectator.setInput('selectedDate', localMidnightDate('1997-08-29'));
const captured = captureDateSelectEvents();
clickDayOfMonth(29);
expect(captured.event).toEqual(localMidnightDate('1997-08-29'));
});
it('should emit dateSelect event as UTC midnights when timezone is set to UTC', () => {
spectator.setInput('timezone', 'UTC');
spectator.setInput('selectedDate', utcMidnightDate('1997-08-29'));
const captured = captureDateSelectEvents();
clickDayOfMonth(14);
expect(captured.event).toEqual(utcMidnightDate('1997-08-14'));
});
it('should be tolerant of date input (selectedDate, todayDate, minDate, maxDate, and disabledDates) as both UTC midnight and local time midnight', () => {
const localDate = localMidnightDate('1997-08-29');
const utcDate = utcMidnightDate('1997-08-29');
spectator.setInput('selectedDate', localDate);
expect(spectator.component.selectedDate).toEqual(localDate);
spectator.setInput('selectedDate', utcDate);
expect(spectator.component.selectedDate).toEqual(localDate);
spectator.setInput('todayDate', localDate);
expect(spectator.component.todayDate).toEqual(localDate);
spectator.setInput('todayDate', utcDate);
expect(spectator.component.todayDate).toEqual(localDate);
spectator.setInput('minDate', localDate);
expect(spectator.component.minDate).toEqual(localDate);
spectator.setInput('minDate', utcDate);
expect(spectator.component.minDate).toEqual(localDate);
spectator.setInput('maxDate', localDate);
expect(spectator.component.maxDate).toEqual(localDate);
spectator.setInput('maxDate', utcDate);
expect(spectator.component.maxDate).toEqual(localDate);
const localDates = ['1997-08-29', '1997-08-30'].map(localMidnightDate);
const utcDates = ['1997-08-29', '1997-08-30'].map(utcMidnightDate);
spectator.setInput('disabledDates', localDates);
expect(spectator.component.disabledDates).toEqual(localDates);
spectator.setInput('disabledDates', utcDates);
expect(spectator.component.disabledDates).toEqual(localDates);
});
it('should render days from Monday to Sunday', () => {
expect(
spectator
.queryAll('th')
.map((_) => _.textContent)
.join(' ')
).toEqual('M T W T F S S');
});
describe('active month', () => {
let todayDate: Date;
beforeEach(() => {
todayDate = new Date(2021, 0, 1);
spectator.setInput('todayDate', todayDate);
spectator.setInput('selectedDate', todayDate);
});
describe('when `minDate` is set', () => {
let minDate: Date;
const yearsBeforeTodayDate = 4;
beforeEach(() => {
minDate = new Date(todayDate.getFullYear() - yearsBeforeTodayDate, 0, 1);
spectator.setInput('minDate', minDate);
});
describe('when `minDate` changes to a later date than `todayDate`', () => {
let newMinDate: Date;
beforeEach(() => {
newMinDate = new Date(
todayDate.getFullYear() + 1,
todayDate.getMonth(),
todayDate.getDay()
);
spectator.setInput('minDate', newMinDate);
});
it('should set active month based on changed `minDate`', () => {
expect(spectator.component.activeMonthName).toEqual(format(newMinDate, 'MMMM'));
});
});
});
describe('when `maxDate` is set', () => {
let maxDate: Date;
const yearsAfterTodayDate = 2;
beforeEach(() => {
maxDate = new Date(todayDate.getFullYear() + yearsAfterTodayDate, 0, 1);
spectator.setInput('maxDate', maxDate);
});
describe('when `maxDate` changes to an earlier date then `todayDate`', () => {
let newMaxDate: Date;
beforeEach(() => {
newMaxDate = new Date(
todayDate.getFullYear() - 1,
todayDate.getMonth(),
todayDate.getDay()
);
spectator.setInput('maxDate', newMaxDate);
});
it('should set active month based on changed `maxDate`', () => {
expect(spectator.component.activeMonthName).toEqual(format(newMaxDate, 'MMMM'));
});
});
});
});
describe('year navigator', () => {
describe('by default', () => {
it('should not render', () => {
expect(spectator.element.querySelector('kirby-dropdown')).toBeNull();
});
});
describe('when yearNavigatorOptions are set', () => {
let todayDate: Date;
let todayDateYear: number;
let yearNavigatorOptions: CalendarYearNavigatorConfig;
beforeEach(() => {
todayDate = new Date(2021, 0, 1);
todayDateYear = todayDate.getFullYear();
yearNavigatorOptions = { from: -3, to: 2 };
spectator.setInput('todayDate', todayDate);
spectator.setInput('selectedDate', todayDate);
spectator.setInput('yearNavigatorOptions', yearNavigatorOptions);
});
it('should render', () => {
expect(spectator.element.querySelector('kirby-dropdown')).not.toBeNull();
});
it('should change year on navigation', () => {
const firstNavigatedYearIndex = spectator.component.navigatedYear;
spectator.setInput('selectedDate', new Date(todayDateYear, 11, 31));
spectator.component._changeMonth(1);
expect(spectator.component.activeYear).toEqual('2022');
expect(spectator.component.navigatedYear).toEqual(firstNavigatedYearIndex + 1);
});
it('should emit selected year on navigation', () => {
const captured = captureYearSelectEvents();
spectator.triggerEventHandler(DropdownComponent, 'change', '2040');
expect(captured.event).toEqual(2040);
});
it('should get navigable years based on `from` and `to` when `minDate` and `maxDate` are omitted', () => {
spectator.setInput('minDate', undefined);
spectator.setInput('maxDate', undefined);
expect(spectator.component.navigableYears).toEqual([
'2018',
'2019',
'2020',
'2021',
'2022',
'2023',
]);
});
it('should prioritize `minDate` and `maxDate` over `from` and `to` when getting navigable years', () => {
spectator.setInput('minDate', new Date(todayDate.getFullYear() - 2, 0, 1));
spectator.setInput('maxDate', new Date(todayDate.getFullYear() + 3, 11, 31));
expect(spectator.component.navigableYears).toEqual([
'2019',
'2020',
'2021',
'2022',
'2023',
'2024',
]);
});
});
});
// constants and utility functions
const SEL_NAV_BACK = '.header button:first-of-type';
const SEL_NAV_FORWARD = '.header button:last-of-type';
function localMidnightDate(yyyyMMdd) {
return startOfDay(new Date(yyyyMMdd));
}
function utcMidnightDate(yyyyMMdd) {
return zonedTimeToUtc(yyyyMMdd, 'UTC');
}
function clickDayOfMonth(dateOneIndexed: number) {
spectator.click(spectator.queryAll('.day.current-month')[dateOneIndexed - 1]);
}
function trimmedTexts(selector: string) {
return spectator.queryAll<HTMLElement>(selector).map((_) => _.innerText);
}
function verifyMonthAndYear(monthAndYearText: string) {
expect(
spectator
.queryAll('.month-and-year span')
.map((_) => _.textContent)
.join(' ')
).toEqual(monthAndYearText);
}
function captureDateChangeEvents() {
let captured: { event?: Date } = {};
spectator.output<Date>('dateChange').subscribe((result) => (captured.event = result));
return captured;
}
function captureDateSelectEvents() {
const captured: { event?: Date } = {};
spectator.output<Date>('dateSelect').subscribe((result) => (captured.event = result));
return captured;
}
function captureYearSelectEvents() {
const captured: { event?: number } = {};
spectator.output<number>('yearSelect').subscribe((result) => (captured.event = result));
return captured;
}
}); | the_stack |
import {
AfterViewInit,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Injector,
Input,
OnChanges,
OnDestroy,
OnInit,
Output
} from '@angular/core';
import {MomentDatePipe} from '@common/pipe/moment.date.pipe';
import {AbstractComponent} from '@common/component/abstract.component';
import * as $ from 'jquery';
import {PageResult} from '@domain/common/page';
import {CommonUtil} from '@common/util/common.util';
import {AuditService} from '../service/audit.service';
import {ClipboardService} from 'ngx-clipboard';
import * as _ from 'lodash';
@Component({
selector: 'app-log-statistics-detail',
templateUrl: './log-statistics.detail.component.html',
providers: [MomentDatePipe]
})
export class LogStatisticsDetailComponent extends AbstractComponent implements OnInit, AfterViewInit, OnDestroy, OnChanges {
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Constructor
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 생성자
constructor(private _clipboardService: ClipboardService,
protected auditService: AuditService,
protected element: ElementRef,
protected injector: Injector) {
super(element, injector);
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Private Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Protected Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Variables
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
// 닫을떄
@Output()
public closeOutput = new EventEmitter();
// 정렬
@Output()
public sortOutput = new EventEmitter();
// 더보기
@Output()
public getMoreContentsOutput = new EventEmitter();
// 테이블로 보여줄 데이터
@Input()
public statisticsData: any;
// 정렬
@Input()
public selectedContentSort: Order;
// 페이저 정보
@Input()
public pageResult: PageResult;
// Change Detect
public changeDetect: ChangeDetectorRef;
public isQueryDetailShow: boolean = false;
public currentNumber: number;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Public Method
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
public CommonUtil = CommonUtil;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Override Methods
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 컴포넌트 시작
*/
public ngOnInit() {
super.ngOnInit();
} // function - onOnInit
public ngOnChanges() {
if (this.statisticsData.value === 'resource') {
this.selectedContentSort.key === 'incrementMemorySeconds' ? this.selectedContentSort.key = 'sumMemorySeconds' : this.selectedContentSort.key = 'sumVCoreSeconds';
} else if (this.statisticsData.value === 'success' || this.statisticsData.value === 'fail') {
this.selectedContentSort.key = 'count';
}
this.changeSortKey(this.selectedContentSort.key);
this.changeDetect.detectChanges();
}
/**
* 컴포넌트 뷰 설정 이후 초기화
*/
public ngAfterViewInit() {
for (let i = 0, nMax = this.statisticsData.fields.length; i < nMax; i++) {
const col = document.createElement('col');
col.width = this.statisticsData.fields[i].width;
$('.tableColgroup').append('<col width=' + col.width + '>');
}
this.changeDetect.detectChanges();
} // function - ngAfterViewInit
/**
* 컴포넌트 종료
*/
public ngOnDestroy() {
super.ngOnDestroy();
} // function - ngOnDestroy
/**
* 더 조회할 컨텐츠가 있는지 여부
* @returns {boolean}
*/
public isMoreContents(): boolean {
return (this.pageResult.number < this.pageResult.totalPages - 1);
}
/**
* 더보기 버튼 클릭
*/
public onClickMoreContents(): void {
// 페이지 넘버 증가
this.pageResult.number += 1;
let data: {};
switch (this.statisticsData.value) {
case 'elapsedTime' :
data = {
names: {name: 'msg.statistics.ui.longest', label: 'elapsedTime', arrayList: 'countQueryTimeList'},
values: {name: 'elapsedTime', sort: this.selectedContentSort.sort}
};
break;
case 'numRows' :
data = {
names: {name: 'msg.statistics.ui.scan.data.volume', label: 'numRows', arrayList: 'countNumRowsList'},
values: {name: 'numRows', sort: this.selectedContentSort.sort}
};
break;
case 'incrementMemorySeconds' :
data = {
names: {
name: 'msg.statistics.th.total.mem.usage',
label: 'incrementMemorySeconds',
arrayList: 'totalMemoryUsageList'
},
values: {name: 'incrementMemorySeconds', sort: this.selectedContentSort.sort}
};
break;
case 'incrementVcoreSeconds' :
data = {
names: {
name: 'msg.statistics.th.total.cpu.usage',
label: 'incrementVcoreSeconds',
arrayList: 'totalCPUUsageList'
},
values: {name: 'incrementVcoreSeconds', sort: this.selectedContentSort.sort}
};
break;
case 'success' :
data = {
names: {name: 'msg.statistics.ui.query.success.frequency', label: 'success', arrayList: 'countSuccessList'},
values: {name: 'status', status: 'SUCCESS', sort: this.selectedContentSort.sort}
};
break;
case 'fail' :
data = {
names: {name: 'msg.statistics.ui.query.fail.frequency', label: 'fail', arrayList: 'countFailList'},
values: {name: 'status', status: 'FAIL', sort: this.selectedContentSort.sort}
};
break;
case 'resource' :
data = {
names: {name: 'msg.statistics.th.resource.usage', label: 'resource', arrayList: 'resourceList'},
values: {name: 'resource', sort: this.page.sort}
};
break;
default :
data = {
names: {
name: 'Job log list - ' + this.statisticsData.value,
label: 'user',
arrayList: 'userList',
value: this.statisticsData.value
},
values: {sort: this.page.sort, user: this.statisticsData.value}
};
break;
}
data['values']['size'] = 15;
data['values']['page'] = this.pageResult.number;
this.getMoreContentsOutput.emit(data)
}
/**
* Change Sorting key keyword, sumMemorySeconds,sumVCoreSeconds 를 바꿔줘야한다
* @param data
*/
public changeSortKey(data) {
switch (data) {
case 'keyword' :
this.page.sort = 'queue' + ',' + this.selectedContentSort.sort;
break;
case 'sumMemorySeconds' :
this.page.sort = 'incrementMemorySeconds' + ',' + this.selectedContentSort.sort;
break;
case 'sumVCoreSeconds' :
this.page.sort = 'incrementVcoreSeconds' + ',' + this.selectedContentSort.sort;
break;
default :
this.page.sort = data + ',' + this.selectedContentSort.sort;
break;
}
}
/**
* Sorting
* @param data
* @param index
*/
public sortList(data, index) {
this.pageResult.number = 0;
// 초기화
this.selectedContentSort.sort = this.selectedContentSort.key !== data ? 'default' : this.selectedContentSort.sort;
// asc, desc, default
switch (this.selectedContentSort.sort) {
case 'asc':
this.selectedContentSort.sort = 'desc';
break;
case 'desc':
this.selectedContentSort.sort = 'asc';
break;
case 'default':
this.selectedContentSort.sort = 'desc';
break;
}
this.changeSortKey(data);
if (this.statisticsData.fields.length === index + 1) {
switch (this.statisticsData.value) {
case 'elapsedTime' :
this.sortOutput.emit({
names: {
name: 'msg.statistics.ui.longest',
label: 'elapsedTime',
arrayList: 'countQueryTimeList'
},
values: {name: 'elapsedTime', sort: this.selectedContentSort.sort, size: 15, page: this.pageResult.number}
});
return;
case 'numRows' :
this.sortOutput.emit({
names: {
name: 'msg.statistics.ui.scan.data.volume',
label: 'numRows',
arrayList: 'countNumRowsList'
}, values: {name: 'numRows', sort: this.selectedContentSort.sort, size: 15, page: this.pageResult.number}
});
return;
case 'incrementMemorySeconds' :
this.sortOutput.emit({
names: {
name: 'msg.statistics.th.total.mem.usage',
label: 'incrementMemorySeconds',
arrayList: 'totalMemoryUsageList'
},
values: {
name: 'incrementMemorySeconds',
sort: this.selectedContentSort.sort,
size: 15,
page: this.pageResult.number
}
});
return;
case 'incrementVcoreSeconds' :
this.sortOutput.emit({
names: {
name: 'msg.statistics.th.total.cpu.usage',
label: 'incrementVcoreSeconds',
arrayList: 'totalCPUUsageList'
},
values: {
name: 'incrementVcoreSeconds',
sort: this.selectedContentSort.sort,
size: 15,
page: this.pageResult.number
}
});
return;
case 'success' :
this.sortOutput.emit({
names: {
name: 'msg.statistics.ui.query.success.frequency',
label: 'success',
arrayList: 'countSuccessList'
},
values: {
name: 'status',
status: 'SUCCESS',
sort: this.selectedContentSort.sort,
size: 15,
page: this.pageResult.number
}
});
return;
case 'fail' :
this.sortOutput.emit({
names: {
name: 'msg.statistics.ui.query.fail.frequency',
label: 'fail',
arrayList: 'countFailList'
},
values: {
name: 'status',
status: 'FAIL',
sort: this.selectedContentSort.sort,
size: 15,
page: this.pageResult.number
}
});
return;
case 'resource' :
this.sortOutput.emit({
names: {
name: 'msg.statistics.th.resource.usage',
label: 'resource',
arrayList: 'resourceList'
},
values: {
name: data === 'sumMemorySeconds' ? 'incrementMemorySeconds' : 'incrementVcoreSeconds',
sort: this.selectedContentSort.sort,
size: 15,
page: this.pageResult.number
}
});
return;
default :
this.sortOutput.emit({
names: {
name: 'Job log list - ' + this.statisticsData.value,
label: 'user',
arrayList: 'userList',
value: this.statisticsData.value
}, values: {sort: this.page.sort, user: this.statisticsData.value, size: 15, page: this.pageResult.number}
});
return;
}
} else {
console.log('not supposed to click --> ');
if (this.statisticsData.value === 'resource') {
this.sortOutput.emit({
names: {
name: 'msg.statistics.th.resource.usage',
label: 'resource',
arrayList: 'resourceList'
},
values: {
name: data === 'sumMemorySeconds' ? 'incrementMemorySeconds' : 'incrementVcoreSeconds',
sort: this.selectedContentSort.sort,
size: 15,
page: this.pageResult.number
}
});
} else if (this.statisticsData.value !== 'elapsedTime' && data === 'startTime') {
this.sortOutput.emit({
names: {
name: 'Job log list - ' + this.statisticsData.value,
label: 'user',
arrayList: 'userList',
value: this.statisticsData.value
}, values: {sort: this.page.sort, user: this.statisticsData.value, size: 15, page: this.pageResult.number}
});
}
return;
}
}
/**
* copy clipboard
*/
public copyToClipboard(data) {
this._clipboardService.copyFromContent(data);
}
/**
* Close popup
*/
public closePopup() {
event.stopImmediatePropagation();
this.isQueryDetailShow = false;
}
/**
* Query popup open/close
*/
public openQueryDetail(event, index) {
event.stopImmediatePropagation();
this.isQueryDetailShow = !this.isQueryDetailShow;
if (this.isQueryDetailShow) {
this.currentNumber = index
}
}
/**
* Check if data is long enough to open the query popup
*/
public isDataLongEnough1(key, index?: number): boolean {
if (_.isNil(key) || _.isNil(index)) {
return false;
}
return $('#' + index + key).width() >= $('#' + key).width() - 20;
}
/**
* Check if data is long enough to open the query popup
*/
public isDataLongEnough(key, id?): boolean {
if (id) {
return $('#' + id).outerWidth() >= $('#' + key).outerWidth() - 20;
} else {
return $('.ddp-data-logdet span').outerWidth() >= $('#' + key).outerWidth() - 20;
}
}
/**
* Thousand separator
* @param {number} data
* @param {string} key
* @return data or thousand separated value
*/
public thousandSeparator(data: number, key: string) {
if (key === 'sumVCoreSeconds' || key === 'sumMemorySeconds' || key === 'incrementVcoreSeconds' || key === 'incrementMemorySeconds' || key === 'numRows') {
return CommonUtil.numberWithCommas(data)
} else {
return data
}
}
/**
* Navigate to audit detail page
* @param data
*/
public auditDetailOpen(data) {
if (data.hasOwnProperty('id')) {
this.auditService.previousRouter = '/management/monitoring/statistics';
this.router.navigateByUrl('/management/monitoring/audit/' + data.id).then();
}
}
}
class Order {
key: string = '';
sort: string = '';
} | the_stack |
import { CategoryType } from '../categoriesList';
export interface Component {
name: string;
title: string;
url: string;
categories: CategoryType[];
keywords: string[];
}
// TODO review and come up with a better approach for urls
// maybe we need to have enum with all routes like we had before?
export const components: Component[] = [
{
name: 'Protein',
title: 'dashboard.protein',
url: `/#protein`,
categories: ['charts'],
keywords: ['protein', 'charts', 'statistics'],
},
{
name: 'Fat',
title: 'dashboard.fat',
url: `/#fat`,
categories: ['charts'],
keywords: ['fat', 'charts', 'statistics'],
},
{
name: 'Bones',
title: 'dashboard.bones',
url: `/#bones`,
categories: ['charts'],
keywords: ['bones', 'charts', 'statistics'],
},
{
name: 'Water',
title: 'dashboard.water',
url: `/#water`,
categories: ['charts'],
keywords: ['water', 'statistics', 'charts'],
},
{
name: 'Map',
title: 'common.map',
url: `/#map`,
categories: ['maps'],
keywords: ['maps', 'doctor', 'polyclinic'],
},
{
name: 'Blood screening',
title: 'dashboard.bloodScreening.title',
url: `/#blood-screening`,
categories: ['data tables', 'charts'],
keywords: ['blood screening', 'statistics', 'data tables', 'charts'],
},
{
name: 'Latest screenings',
title: 'dashboard.latestScreenings.title',
url: `/#latest-screenings`,
categories: ['charts'],
keywords: ['latest screenings', 'charts', 'statistics'],
},
{
name: 'Treatment plan',
title: 'dashboard.treatmentPlan.title',
url: `/#treatment-plan`,
categories: ['data tables'],
keywords: ['treatment plan', 'data tables', 'doctor'],
},
{
name: 'Activity',
title: 'dashboard.activity.title',
url: `/#activity`,
categories: ['charts'],
keywords: ['activity', 'charts', 'statistics'],
},
{
name: 'Covid',
title: 'dashboard.covid.title',
url: `/#covid`,
categories: ['charts'],
keywords: ['covid', 'charts', 'statistics'],
},
{
name: 'Patient timeline',
title: 'dashboard.patientResults.title',
url: `/#patient-timeline`,
categories: ['data tables'],
keywords: ['patient timeline', 'data tables'],
},
{
name: 'Health',
title: 'dashboard.health.title',
url: `/#health`,
categories: ['charts'],
keywords: ['health', 'charts'],
},
{
name: 'Favorite doctors',
title: 'dashboard.favoriteDoctors.title',
url: `/#favorite-doctors`,
categories: ['data tables'],
keywords: ['favorite doctors', 'data tables'],
},
{
name: 'News',
title: 'dashboard.news',
url: `/#news`,
categories: ['data tables'],
keywords: ['news', 'data tables'],
},
{
name: 'Feed',
title: 'common.feed',
url: `/apps/feed`,
categories: ['apps'],
keywords: ['feed', 'apps'],
},
{
name: 'Kanban',
title: 'common.kanban',
url: `/apps/kanban`,
categories: ['apps'],
keywords: ['kanban', 'apps', 'trello'],
},
{
name: 'Log in',
title: 'common.login',
url: `/auth/login`,
categories: ['auth'],
keywords: ['auth', 'log in', 'login'],
},
{
name: 'Sign up',
title: 'common.signup',
url: `/auth/sign-up`,
categories: ['auth'],
keywords: ['auth', 'sign up', 'signup'],
},
{
name: 'Lock',
title: 'common.lock',
url: `/auth/lock`,
categories: ['auth'],
keywords: ['auth', 'lock'],
},
{
name: 'Forgot password',
title: 'common.forgotPass',
url: `/auth/forgot-password`,
categories: ['auth'],
keywords: ['auth', 'forgot password'],
},
{
name: 'Security code',
title: 'common.securityCode',
url: `/auth/security-code`,
categories: ['auth'],
keywords: ['auth', 'security code'],
},
{
name: 'New password',
title: 'common.newPassword',
url: `/auth/new-password`,
categories: ['auth'],
keywords: ['auth', 'new password'],
},
{
name: 'Dynamic form',
title: 'forms.dynamicForm',
url: `/forms/advanced-forms/#dynamic-form`,
categories: ['forms'],
keywords: ['dynamic form', 'forms'],
},
{
name: 'Control form',
title: 'forms.controlForm',
url: `/forms/advanced-forms/#control-form`,
categories: ['forms'],
keywords: ['control form', 'forms'],
},
{
name: 'Validation form',
title: 'forms.validationForm',
url: `/forms/advanced-forms/#validation-form`,
categories: ['forms'],
keywords: ['validation form', 'forms'],
},
{
name: 'Step form',
title: 'forms.stepForm',
url: `/forms/advanced-forms/#step-form`,
categories: ['forms'],
keywords: ['step form', 'forms'],
},
{
name: 'Basic table',
title: 'tables.basicTable',
url: `/data-tables/#basic-table`,
categories: ['data tables'],
keywords: ['basic table', 'data tables'],
},
{
name: 'Tree table',
title: 'tables.treeTable',
url: `/data-tables/#tree-table`,
categories: ['data tables'],
keywords: ['tree table', 'data tables'],
},
{
name: 'Editable table',
title: 'tables.editableTable',
url: `/data-tables/#editable-table`,
categories: ['data tables'],
keywords: ['editable table', 'data tables'],
},
{
name: 'Gradient stacked area',
title: 'charts.gradientLabel',
url: `/charts/#gradient-stacked-area`,
categories: ['charts'],
keywords: ['gradient stacked area', 'charts'],
},
{
name: 'Bar animation delay',
title: 'charts.barLabel',
url: `/charts/#bar-animation-delay`,
categories: ['charts'],
keywords: ['gradient stacked area', 'charts'],
},
{
name: 'Pie',
title: 'charts.pie',
url: `/charts/#pie`,
categories: ['charts'],
keywords: ['pie', 'charts'],
},
{
name: 'Scatter',
title: 'charts.scatter',
url: `/charts/#scatter`,
categories: ['charts'],
keywords: ['scatter', 'charts'],
},
{
name: 'Line race',
title: 'charts.lineRace',
url: `/charts/#line-race`,
categories: ['charts'],
keywords: ['line race', 'charts'],
},
{
name: 'Server error',
title: 'common.serverError',
url: `/server-error`,
categories: ['data tables'],
keywords: ['server error', 'data tables', '500'],
},
{
name: 'Client error',
title: 'common.clientError',
url: `/404`,
categories: ['data tables'],
keywords: ['client error', 'data tables', '400'],
},
{
name: 'Personal info',
title: 'profile.nav.personalInfo.title',
url: `/profile/personal-info`,
categories: ['data tables'],
keywords: ['personal info', 'data tables'],
},
{
name: 'Security settings',
title: 'profile.nav.securitySettings.title',
url: `/profile/security-settings`,
categories: ['data tables'],
keywords: ['security settings', 'data tables'],
},
{
name: 'Notifications (settings)', // Have to explain bcz user can understand it like a page with a list of his notifications
title: 'profile.nav.notifications.settings',
url: `/profile/notifications`,
categories: ['data tables'],
keywords: ['notifications', 'data tables'],
},
{
name: 'Payments',
title: 'profile.nav.payments.title',
url: `/profile/payments`,
categories: ['data tables'],
keywords: ['payments', 'data tables'],
},
{
name: 'Alert',
title: 'common.alert',
url: `/ui-components/alert`,
categories: ['data tables'],
keywords: ['alert', 'data tables'],
},
{
name: 'Avatar',
title: 'common.avatar',
url: `/ui-components/avatar`,
categories: ['data tables'],
keywords: ['avatar', 'data tables'],
},
{
name: 'AutoComplete',
title: 'common.autocomplete',
url: `/ui-components/auto-complete`,
categories: ['data tables'],
keywords: ['autocomplete', 'data tables'],
},
{
name: 'Badge',
title: 'common.badge',
url: `/ui-components/badge`,
categories: ['data tables'],
keywords: ['badge', 'data tables'],
},
{
name: 'Breadcrumbs',
title: 'common.breadcrumbs',
url: `/ui-components/breadcrumbs`,
categories: ['data tables'],
keywords: ['breadcrumbs', 'data tables'],
},
{
name: 'Button',
title: 'common.button',
url: `/ui-components/button`,
categories: ['data tables'],
keywords: ['button', 'data tables'],
},
{
name: 'Checkbox',
title: 'common.checkbox',
url: `/ui-components/checkbox`,
categories: ['data tables'],
keywords: ['checkbox', 'data tables'],
},
{
name: 'Collapse',
title: 'common.collapse',
url: `/ui-components/collapse`,
categories: ['data tables'],
keywords: ['collapse', 'data tables'],
},
{
name: 'DateTime Picker',
title: 'common.dateTimePicker',
url: `/ui-components/date-time-picker`,
categories: ['data tables'],
keywords: ['date', 'time', 'picker', 'data tables'],
},
{
name: 'Dropdown',
title: 'common.dropdown',
url: `/ui-components/dropdown`,
categories: ['data tables'],
keywords: ['dropdown', 'data tables'],
},
{
name: 'Input',
title: 'common.input',
url: `/ui-components/input`,
categories: ['data tables'],
keywords: ['input', 'data tables'],
},
{
name: 'Modal',
title: 'common.modal',
url: `/ui-components/modal`,
categories: ['data tables'],
keywords: ['modal', 'data tables'],
},
{
name: 'Notification',
title: 'common.notification',
url: `/ui-components/notification`,
categories: ['data tables'],
keywords: ['notification', 'data tables'],
},
{
name: 'Pagination',
title: 'common.pagination',
url: `/ui-components/pagination`,
categories: ['data tables'],
keywords: ['pagination', 'data tables'],
},
{
name: 'Popconfirm',
title: 'common.popconfirm',
url: `/ui-components/popconfirm`,
categories: ['data tables'],
keywords: ['popconfirm', 'data tables'],
},
{
name: 'Popover',
title: 'common.popover',
url: `/ui-components/popover`,
categories: ['data tables'],
keywords: ['popover', 'data tables'],
},
{
name: 'Progress',
title: 'common.progress',
url: `/ui-components/progress`,
categories: ['data tables'],
keywords: ['progress', 'data tables'],
},
{
name: 'Radio',
title: 'common.radio',
url: `/ui-components/radio`,
categories: ['data tables'],
keywords: ['radio', 'data tables'],
},
{
name: 'Rate',
title: 'common.rate',
url: `/ui-components/rate`,
categories: ['data tables'],
keywords: ['rate', 'data tables'],
},
{
name: 'Result',
title: 'common.result',
url: `/ui-components/result`,
categories: ['data tables'],
keywords: ['result', 'data tables'],
},
{
name: 'Select',
title: 'common.select',
url: `/ui-components/select`,
categories: ['data tables'],
keywords: ['select', 'data tables'],
},
{
name: 'Skeleton',
title: 'common.skeleton',
url: `/ui-components/skeleton`,
categories: ['data tables'],
keywords: ['skeleton', 'data tables'],
},
{
name: 'Spinner',
title: 'common.spinner',
url: `/ui-components/spinner`,
categories: ['data tables'],
keywords: ['spinner', 'data tables'],
},
{
name: 'Steps',
title: 'common.steps',
url: `/ui-components/steps`,
categories: ['data tables'],
keywords: ['steps', 'data tables'],
},
{
name: 'Switch',
title: 'common.switch',
url: `/ui-components/switch`,
categories: ['data tables'],
keywords: ['switch', 'data tables'],
},
{
name: 'Tabs',
title: 'common.tabs',
url: `/ui-components/tabs`,
categories: ['data tables'],
keywords: ['tabs', 'data tables'],
},
{
name: 'Upload',
title: 'common.upload',
url: `/ui-components/upload`,
categories: ['data tables'],
keywords: ['upload', 'data tables'],
},
]; | the_stack |
import { query as q } from 'faunadb';
import { FactoryIndexesApi } from '~/types/factory/factory.indexes';
import { FactoryContext } from '~/types/factory/factory.context';
import { pathString } from '~/helpers/path';
import { index } from '.';
import { BiotaIndexName } from '~/factory/constructors';
import { ThrowError } from '~/factory/constructors/error';
import { MethodDispatch, Query } from '~/factory/constructors/method';
import { ResultData } from '~/factory/constructors/result';
import { BiotaFunctionName } from './constructors';
import { Pagination } from '../constructors/pagination';
// tslint:disable-next-line: only-arrow-functions
export const indexes: FactoryContext<FactoryIndexesApi> = function (context): FactoryIndexesApi {
return {
findIndex(resource, termsByPath) {
const inputs = { resource, termsByPath };
// ---
const query = Query(
{
indexes: q.Paginate(
q.Intersection(
q.Match(q.Index(BiotaIndexName('indexes__by__resource')), [q.Var('resource')]),
q.Union(
q.Map(q.Var('termsByPath'), q.Lambda(['field'], q.Match(q.Index(BiotaIndexName('indexes__by__terms')), [q.Var('field')]))),
),
),
),
termsCount: q.Count(q.Var('termsByPath')),
filteredIndexes: q.Filter(
q.Var('indexes'),
q.Lambda(['index'], q.Equals(q.Var('termsCount'), q.Count(q.Select('terms', q.Get(q.Var('index')), Infinity)))),
),
},
q.Select(0, q.Var('filteredIndexes'), null),
);
// ---
const offline = 'factory.indexes.findIndex';
const online = { name: BiotaFunctionName('IndexesFindIndex'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
searchQuery(resource, searchTerms) {
const inputs = { resource, searchTerms };
// ---
const query = Query(
{
searchTerms: q.ToArray(q.Var('searchTerms')),
termIndexes: q.Map(
q.Var('searchTerms'),
q.Lambda(
['field', 'value'],
q.If(
q.IsObject(q.Var('value')),
q.If(
q.Contains('$computed', q.Var('value')),
[
indexes(q.Var('ctx')).findIndex(q.Var('resource'), [q.Concat(['binding:', q.Var('field')])]),
q.Select('$computed', q.Var('value'), null),
q.Concat(['binding:', pathString(q.Var('field'))]),
],
q.If(
q.Contains('$ngram', q.Var('value')),
[
indexes(q.Var('ctx')).findIndex(q.Var('resource'), [q.Concat(['binding:', 'ngram:', q.Var('field')])]),
q.LowerCase(q.ToString(q.Select('$ngram', q.Var('value'), ''))),
q.Concat(['ngram:', pathString(q.Var('field'))]),
],
[null, null, null],
),
),
[
indexes(q.Var('ctx')).findIndex(q.Var('resource'), [q.Concat(['term:', pathString(q.Var('field'))])]),
q.Var('value'),
q.Var('field'),
],
),
),
),
validTermIndexes: q.Filter(q.Var('termIndexes'), q.Lambda(['index', 'value', 'field'], q.IsIndex(q.Var('index')))),
unvalidIndexes: q.Filter(q.Var('termIndexes'), q.Lambda(['index', 'value', 'field'], q.Not(q.IsIndex(q.Var('index'))))),
unvalidFields: q.Concat(q.Map(q.Var('unvalidIndexes'), q.Lambda(['index', 'value', 'field'], q.Var('field'))), ', '),
},
q.If(
q.LT(q.Count(q.Var('unvalidIndexes')), 1),
q.Intersection(q.Map(q.Var('validTermIndexes'), q.Lambda(['index', 'value', 'field'], q.Match(q.Var('index'), q.Var('value'))))),
ThrowError(q.Var('ctx'), "Indexes couldn't be found", {
resource: q.Var('resource'),
searchTerms: q.Var('searchTerms'),
unvalidFields: q.Var('unvalidFields'),
}),
),
);
// ---
const offline = 'factory.indexes.searchQuery';
const online = { name: BiotaFunctionName('IndexesSearchQuery'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
findByResource(resource, pagination) {
const inputs = { resource, pagination };
// ---
const query = Query(
{
docs: q.Paginate(q.Match(q.Index(BiotaIndexName('indexes__by__resource')), q.Var('resource')), Pagination(q.Var('pagination'))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.findByResource';
const online = { name: BiotaFunctionName('IndexesFindByResource'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
findByTerm(term, pagination) {
const inputs = { term, pagination };
// ---
const query = Query(
{
docs: q.Paginate(q.Match(q.Index(BiotaIndexName('indexes__by__terms')), q.Var('term')), Pagination(q.Var('pagination'))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.findByResource';
const online = { name: BiotaFunctionName('IndexesFindByResource'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
findAll(pagination) {
const inputs = { pagination };
// ---
const query = Query(
{
docs: q.Map(q.Paginate(q.Indexes(), pagination), q.Lambda('x', q.Get(q.Var('x')))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.paginate';
const online = { name: BiotaFunctionName('IndexesFindAll'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
getMany(nameList) {
const inputs = { nameList };
// ---
const query = Query(
{
docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(index(q.Var('ctx'))(q.Var('name')).get()))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.getMany';
const online = { name: BiotaFunctionName('IndexesGetMany'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
insertMany(optionsList) {
const inputs = { optionsList };
// ---
const query = Query(
{
docs: q.Map(
q.Var('optionsList'),
q.Lambda(['options'], ResultData(index(q.Var('ctx'))(q.Select('name', q.Var('options'), null)).insert(q.Var('options')))),
),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.insertMany';
const online = { name: BiotaFunctionName('IndexesInsertMany'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
updateMany(optionsList) {
const inputs = { optionsList };
// ---
const query = Query(
{
docs: q.Map(
q.Var('optionsList'),
q.Lambda(['options'], ResultData(index(q.Var('ctx'))(q.Select('name', q.Var('options'), null)).update(q.Var('options')))),
),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.updateMany';
const online = { name: BiotaFunctionName('IndexesUpdateMany'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
upsertMany(optionsList) {
const inputs = { optionsList };
// ---
const query = Query(
{
docs: q.Map(
q.Var('optionsList'),
q.Lambda(['options'], ResultData(index(q.Var('ctx'))(q.Select('name', q.Var('options'), null)).upsert(q.Var('options')))),
),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.upsertMany';
const online = { name: BiotaFunctionName('IndexesUpsertMany'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
replaceMany(optionsList) {
const inputs = { optionsList };
// ---
const query = Query(
{
docs: q.Map(
q.Var('optionsList'),
q.Lambda(['options'], ResultData(index(q.Var('ctx'))(q.Select('name', q.Var('options'), null)).replace(q.Var('options')))),
),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.replaceMany';
const online = { name: BiotaFunctionName('IndexesReplaceMany'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
repsertMany(optionsList) {
const inputs = { optionsList };
// ---
const query = Query(
{
docs: q.Map(
q.Var('optionsList'),
q.Lambda(['options'], ResultData(index(q.Var('ctx'))(q.Select('name', q.Var('options'), null)).repsert(q.Var('options')))),
),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.repsertMany';
const online = { name: BiotaFunctionName('IndexesRepsertMany'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
deleteMany(nameList) {
const inputs = { nameList };
// ---
const query = Query(
{
docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(index(q.Var('ctx'))(q.Var('name')).delete()))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.deleteMany';
const online = { name: BiotaFunctionName('IndexesDeleteMany'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
restoreMany(nameList) {
const inputs = { nameList };
// ---
const query = Query(
{
docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(index(q.Var('ctx'))(q.Var('name')).restore()))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.restoreMany';
const online = { name: BiotaFunctionName('IndexesRestoreMany'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
forgetMany(nameList) {
const inputs = { nameList };
// ---
const query = Query(
{
docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(index(q.Var('ctx'))(q.Var('name')).forget()))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.forgetMany';
const online = { name: BiotaFunctionName('IndexesForgetMany'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
dropMany(nameList) {
const inputs = { nameList };
// ---
const query = Query(
{
docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(index(q.Var('ctx'))(q.Var('name')).drop()))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.dropMany';
const online = { name: BiotaFunctionName('IndexesDropMany'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
expireManyAt(nameList, at) {
const inputs = { nameList, at };
// ---
const query = Query(
{
docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(index(q.Var('ctx'))(q.Var('name')).expireAt(q.Var('at'))))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.expireManyAt';
const online = { name: BiotaFunctionName('IndexesExpireManyAt'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
expireManyIn(nameList, delay) {
const inputs = { nameList, delay };
// ---
const query = Query(
{
docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(index(q.Var('ctx'))(q.Var('name')).expireIn(q.Var('delay'))))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.expireManyAt';
const online = { name: BiotaFunctionName('IndexesExpireManyAt'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
expireManyNow(nameList) {
const inputs = { nameList };
// ---
const query = Query(
{
docs: q.Map(q.Var('nameList'), q.Lambda(['name'], ResultData(index(q.Var('ctx'))(q.Var('name')).expireNow()))),
},
q.Var('docs'),
);
// ---
const offline = 'factory.indexes.expireManyNow';
const online = { name: BiotaFunctionName('IndexesExpireManyNow'), role: null };
return MethodDispatch({ context, inputs, query })(offline, online);
},
};
}; | the_stack |
import { createElement, remove } from '@syncfusion/ej2-base';
import { Chart } from '../../../src/chart/chart';
import { getElement } from '../../../src/common/utils/helper';
import { DataLabel } from '../../../src/chart/series/data-label';
import { Legend } from '../../../src/chart/legend/legend';
import { ColumnSeries } from '../../../src/chart/series/column-series';
import { unbindResizeEvents } from '../base/data.spec';
import { StackingColumnSeries } from '../../../src/chart/series/stacking-column-series';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { EmitType } from '@syncfusion/ej2-base';
import {profile , inMB, getMemoryProfile} from '../../common.spec';
import { ILoadedEventArgs } from '../../../src/chart/model/chart-interface';
Chart.Inject(ColumnSeries, StackingColumnSeries, DataLabel, Legend);
describe('Chart Control', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Chart Bar series', () => {
let chartObj: Chart;
let elem: HTMLElement;
let point: HTMLElement;
let svg: HTMLElement;
let targetElement: HTMLElement;
let loaded: EmitType<ILoadedEventArgs>;
let done: Function;
let dataLabel: HTMLElement;
let x: number;
let y: number;
let loaded1: EmitType<ILoadedEventArgs>;
let material: string[] = ['#00bdae', '#404041', '#357cd2', '#e56590', '#f8b883',
'#70ad47', '#dd8abd', '#7f84e8', '#7bb4eb', '#ea7a57'];
let fabric: string[] = ['#4472c4', '#ed7d31', '#ffc000', '#70ad47', '#5b9bd5',
'#c1c1c1', '#6f6fe2', '#e269ae', '#9e480e', '#997300'];
let paletteColor: string[] = ['#005378', '#006691', '#007EB5', '#0D97D4', '#00AEFF',
'#14B9FF', '#54CCFF', '#87DBFF', '#ADE5FF', '#C5EDFF'];
let bootstrap: string[] = ['#a16ee5', '#f7ce69', '#55a5c2', '#7ddf1e', '#ff6ea6',
'#7953ac', '#b99b4f', '#407c92', '#5ea716', '#b91c52'];
let highContrast = ['#79ECE4', '#E98272', '#DFE6B6', '#C6E773', '#BA98FF',
'#FA83C3', '#00C27A', '#43ACEF', '#D681EF', '#D8BC6E'];
beforeAll(() => {
elem = createElement('div', { id: 'theme' });
document.body.appendChild(elem);
chartObj = new Chart(
{
primaryXAxis: { minimum: 0.5, maximum: 1.5, interval: 1 },
primaryYAxis: { minimum: 0, maximum: 25, interval: 5 },
series: [{
dataSource: [{ x: 1, y: 16 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'USA', marker: { dataLabel: { visible: true, fill: material[0] } }
}, {
dataSource: [{ x: 1, y: 17 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'GBR', marker: { dataLabel: { visible: true, fill: material[1] } }
}, {
dataSource: [{ x: 1, y: 16 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'CHN', marker: { dataLabel: { visible: true, fill: material[2] } }
}, {
dataSource: [{ x: 1, y: 19 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'RUS', marker: { dataLabel: { visible: true, fill: material[3] } }
}, {
dataSource: [{ x: 1, y: 17 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'GER', marker: { dataLabel: { visible: true, fill: material[4] } }
}, {
dataSource: [{ x: 1, y: 12 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'JAP', marker: { dataLabel: { visible: true, fill: material[5] } }
}, {
dataSource: [{ x: 1, y: 10 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'FRN', marker: { dataLabel: { visible: true, fill: material[6] } }
}, {
dataSource: [{ x: 1, y: 18 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'IND', marker: { dataLabel: { visible: true, fill: material[7] } }
}, {
dataSource: [{ x: 1, y: 10 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'AUS', marker: { dataLabel: { visible: true, fill: material[8] } }
}, {
dataSource: [{ x: 1, y: 15 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'NZ', marker: { dataLabel: { visible: true, fill: material[9] } }
}, {
dataSource: [{ x: 1, y: 19 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'PAK', marker: { dataLabel: { visible: true, fill: material[0] } }
}, {
dataSource: [{ x: 1, y: 19 }], xName: 'x', yName: 'y', animation: { enable: false }, type: 'Column',
name: 'SPN', marker: { dataLabel: { visible: true, fill: material[1] } }
}
], width: '950',
legendSettings: { visible: true },
title: 'Series Palette'
});
});
afterAll((): void => {
chartObj.destroy();
elem.remove();
});
it('Checking with default pattern color', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_Series_';
let suffix: string = '_Point_0';
expect(getElement(prefix + 0 + suffix).getAttribute('fill')).toBe(material[0]);
expect(getElement(prefix + 1 + suffix).getAttribute('fill')).toBe(material[1]);
expect(getElement(prefix + 2 + suffix).getAttribute('fill')).toBe(material[2]);
expect(getElement(prefix + 3 + suffix).getAttribute('fill')).toBe(material[3]);
expect(getElement(prefix + 4 + suffix).getAttribute('fill')).toBe(material[4]);
expect(getElement(prefix + 5 + suffix).getAttribute('fill')).toBe(material[5]);
expect(getElement(prefix + 6 + suffix).getAttribute('fill')).toBe(material[6]);
expect(getElement(prefix + 7 + suffix).getAttribute('fill')).toBe(material[7]);
expect(getElement(prefix + 8 + suffix).getAttribute('fill')).toBe(material[8]);
expect(getElement(prefix + 9 + suffix).getAttribute('fill')).toBe(material[9]);
expect(getElement(prefix + 10 + suffix).getAttribute('fill')).toBe(material[0]);
expect(getElement(prefix + 11 + suffix).getAttribute('fill')).toBe(material[1]);
done();
};
chartObj.loaded = loaded;
chartObj.appendTo('#theme');
});
it('Checking with legend color', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_chart_legend_shape_';
expect(getElement(prefix + 0).getAttribute('fill')).toBe(material[0]);
expect(getElement(prefix + 1).getAttribute('fill')).toBe(material[1]);
expect(getElement(prefix + 2).getAttribute('fill')).toBe(material[2]);
expect(getElement(prefix + 3).getAttribute('fill')).toBe(material[3]);
expect(getElement(prefix + 4).getAttribute('fill')).toBe(material[4]);
expect(getElement(prefix + 5).getAttribute('fill')).toBe(material[5]);
expect(getElement(prefix + 6).getAttribute('fill')).toBe(material[6]);
expect(getElement(prefix + 7).getAttribute('fill')).toBe(material[7]);
expect(getElement(prefix + 8).getAttribute('fill')).toBe(material[8]);
expect(getElement(prefix + 9).getAttribute('fill')).toBe(material[9]);
expect(getElement(prefix + 10).getAttribute('fill')).toBe(material[0]);
expect(getElement(prefix + 11).getAttribute('fill')).toBe(material[1]);
done();
};
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Checking with fabric theme color', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_Series_';
let suffix: string = '_Point_0';
expect(getElement(prefix + 0 + suffix).getAttribute('fill')).toBe(fabric[0]);
expect(getElement(prefix + 1 + suffix).getAttribute('fill')).toBe(fabric[1]);
expect(getElement(prefix + 2 + suffix).getAttribute('fill')).toBe(fabric[2]);
expect(getElement(prefix + 3 + suffix).getAttribute('fill')).toBe(fabric[3]);
expect(getElement(prefix + 4 + suffix).getAttribute('fill')).toBe(fabric[4]);
expect(getElement(prefix + 5 + suffix).getAttribute('fill')).toBe(fabric[5]);
expect(getElement(prefix + 6 + suffix).getAttribute('fill')).toBe(fabric[6]);
expect(getElement(prefix + 7 + suffix).getAttribute('fill')).toBe(fabric[7]);
expect(getElement(prefix + 8 + suffix).getAttribute('fill')).toBe(fabric[8]);
expect(getElement(prefix + 9 + suffix).getAttribute('fill')).toBe(fabric[9]);
expect(getElement(prefix + 10 + suffix).getAttribute('fill')).toBe(fabric[0]);
expect(getElement(prefix + 11 + suffix).getAttribute('fill')).toBe(fabric[1]);
done();
};
chartObj.theme = 'Fabric';
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Checking with highcontrast theme color', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_Series_';
let suffix: string = '_Point_0';
expect(getElement(prefix + 0 + suffix).getAttribute('fill')).toBe(highContrast[0]);
expect(getElement(prefix + 1 + suffix).getAttribute('fill')).toBe(highContrast[1]);
expect(getElement(prefix + 2 + suffix).getAttribute('fill')).toBe(highContrast[2]);
expect(getElement(prefix + 3 + suffix).getAttribute('fill')).toBe(highContrast[3]);
expect(getElement(prefix + 4 + suffix).getAttribute('fill')).toBe(highContrast[4]);
expect(getElement(prefix + 5 + suffix).getAttribute('fill')).toBe(highContrast[5]);
expect(getElement(prefix + 6 + suffix).getAttribute('fill')).toBe(highContrast[6]);
expect(getElement(prefix + 7 + suffix).getAttribute('fill')).toBe(highContrast[7]);
expect(getElement(prefix + 8 + suffix).getAttribute('fill')).toBe(highContrast[8]);
expect(getElement(prefix + 9 + suffix).getAttribute('fill')).toBe(highContrast[9]);
expect(getElement(prefix + 10 + suffix).getAttribute('fill')).toBe(highContrast[0]);
expect(getElement(prefix + 11 + suffix).getAttribute('fill')).toBe(highContrast[1]);
done();
};
chartObj.theme = 'HighContrastLight';
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Checking with bootstrap theme color', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_Series_';
let suffix: string = '_Point_0';
expect(getElement(prefix + 0 + suffix).getAttribute('fill')).toBe(bootstrap[0]);
expect(getElement(prefix + 1 + suffix).getAttribute('fill')).toBe(bootstrap[1]);
expect(getElement(prefix + 2 + suffix).getAttribute('fill')).toBe(bootstrap[2]);
expect(getElement(prefix + 3 + suffix).getAttribute('fill')).toBe(bootstrap[3]);
expect(getElement(prefix + 4 + suffix).getAttribute('fill')).toBe(bootstrap[4]);
expect(getElement(prefix + 5 + suffix).getAttribute('fill')).toBe(bootstrap[5]);
expect(getElement(prefix + 6 + suffix).getAttribute('fill')).toBe(bootstrap[6]);
expect(getElement(prefix + 7 + suffix).getAttribute('fill')).toBe(bootstrap[7]);
expect(getElement(prefix + 8 + suffix).getAttribute('fill')).toBe(bootstrap[8]);
expect(getElement(prefix + 9 + suffix).getAttribute('fill')).toBe(bootstrap[9]);
expect(getElement(prefix + 10 + suffix).getAttribute('fill')).toBe(bootstrap[0]);
expect(getElement(prefix + 11 + suffix).getAttribute('fill')).toBe(bootstrap[1]);
done();
};
chartObj.theme = 'Bootstrap';
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Checking with bootstrap4 theme color', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_Series_';
let suffix: string = '_Point_0';
expect(getElement(prefix + 0 + suffix).getAttribute('fill')).toBe(bootstrap[0]);
expect(getElement(prefix + 1 + suffix).getAttribute('fill')).toBe(bootstrap[1]);
expect(getElement(prefix + 2 + suffix).getAttribute('fill')).toBe(bootstrap[2]);
expect(getElement(prefix + 3 + suffix).getAttribute('fill')).toBe(bootstrap[3]);
expect(getElement(prefix + 4 + suffix).getAttribute('fill')).toBe(bootstrap[4]);
expect(getElement(prefix + 5 + suffix).getAttribute('fill')).toBe(bootstrap[5]);
expect(getElement(prefix + 6 + suffix).getAttribute('fill')).toBe(bootstrap[6]);
expect(getElement(prefix + 7 + suffix).getAttribute('fill')).toBe(bootstrap[7]);
expect(getElement(prefix + 8 + suffix).getAttribute('fill')).toBe(bootstrap[8]);
expect(getElement(prefix + 9 + suffix).getAttribute('fill')).toBe(bootstrap[9]);
expect(getElement(prefix + 10 + suffix).getAttribute('fill')).toBe(bootstrap[0]);
expect(getElement(prefix + 11 + suffix).getAttribute('fill')).toBe(bootstrap[1]);
done();
};
chartObj.theme = 'Bootstrap4';
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Checking with fabric theme legend color', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_chart_legend_shape_';
expect(getElement(prefix + 0).getAttribute('fill')).toBe(fabric[0]);
expect(getElement(prefix + 1).getAttribute('fill')).toBe(fabric[1]);
expect(getElement(prefix + 2).getAttribute('fill')).toBe(fabric[2]);
expect(getElement(prefix + 3).getAttribute('fill')).toBe(fabric[3]);
expect(getElement(prefix + 4).getAttribute('fill')).toBe(fabric[4]);
expect(getElement(prefix + 5).getAttribute('fill')).toBe(fabric[5]);
expect(getElement(prefix + 6).getAttribute('fill')).toBe(fabric[6]);
expect(getElement(prefix + 7).getAttribute('fill')).toBe(fabric[7]);
expect(getElement(prefix + 8).getAttribute('fill')).toBe(fabric[8]);
expect(getElement(prefix + 9).getAttribute('fill')).toBe(fabric[9]);
expect(getElement(prefix + 10).getAttribute('fill')).toBe(fabric[0]);
expect(getElement(prefix + 11).getAttribute('fill')).toBe(fabric[1]);
done();
};
chartObj.theme = 'Fabric';
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Checking with dataLabel color', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_Series_';
let suffix: string = '_Point_0_TextShape_0';
expect(getElement(prefix + 0 + suffix).getAttribute('fill')).toBe(material[0]);
expect(getElement(prefix + 1 + suffix).getAttribute('fill')).toBe(material[1]);
expect(getElement(prefix + 2 + suffix).getAttribute('fill')).toBe(material[2]);
expect(getElement(prefix + 3 + suffix).getAttribute('fill')).toBe(material[3]);
expect(getElement(prefix + 4 + suffix).getAttribute('fill')).toBe(material[4]);
expect(getElement(prefix + 5 + suffix).getAttribute('fill')).toBe(material[5]);
expect(getElement(prefix + 6 + suffix).getAttribute('fill')).toBe(material[6]);
expect(getElement(prefix + 7 + suffix).getAttribute('fill')).toBe(material[7]);
expect(getElement(prefix + 8 + suffix).getAttribute('fill')).toBe(material[8]);
expect(getElement(prefix + 9 + suffix).getAttribute('fill')).toBe(material[9]);
expect(getElement(prefix + 10 + suffix).getAttribute('fill')).toBe(material[0]);
expect(getElement(prefix + 11 + suffix).getAttribute('fill')).toBe(material[1]);
done();
};
chartObj.theme = 'Material';
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Checking palette while changing', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_Series_';
let suffix: string = '_Point_0';
expect(getElement(prefix + 0 + suffix).getAttribute('fill')).toBe(paletteColor[0]);
expect(getElement(prefix + 1 + suffix).getAttribute('fill')).toBe(paletteColor[1]);
expect(getElement(prefix + 2 + suffix).getAttribute('fill')).toBe(paletteColor[2]);
expect(getElement(prefix + 3 + suffix).getAttribute('fill')).toBe(paletteColor[3]);
expect(getElement(prefix + 4 + suffix).getAttribute('fill')).toBe(paletteColor[4]);
expect(getElement(prefix + 5 + suffix).getAttribute('fill')).toBe(paletteColor[5]);
expect(getElement(prefix + 6 + suffix).getAttribute('fill')).toBe(paletteColor[6]);
expect(getElement(prefix + 7 + suffix).getAttribute('fill')).toBe(paletteColor[7]);
expect(getElement(prefix + 8 + suffix).getAttribute('fill')).toBe(paletteColor[8]);
expect(getElement(prefix + 9 + suffix).getAttribute('fill')).toBe(paletteColor[9]);
expect(getElement(prefix + 10 + suffix).getAttribute('fill')).toBe(paletteColor[0]);
expect(getElement(prefix + 11 + suffix).getAttribute('fill')).toBe(paletteColor[1]);
done();
};
chartObj.loaded = loaded;
chartObj.palettes = paletteColor;
chartObj.refresh();
});
it('Checking series fill', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_Series_';
let suffix: string = '_Point_0';
expect(getElement(prefix + 0 + suffix).getAttribute('fill')).toBe(paletteColor[0]);
expect(getElement(prefix + 1 + suffix).getAttribute('fill')).toBe(paletteColor[1]);
expect(getElement(prefix + 2 + suffix).getAttribute('fill')).toBe(paletteColor[2]);
expect(getElement(prefix + 3 + suffix).getAttribute('fill')).toBe('violet');
expect(getElement(prefix + 4 + suffix).getAttribute('fill')).toBe(paletteColor[4]);
expect(getElement(prefix + 5 + suffix).getAttribute('fill')).toBe(paletteColor[5]);
expect(getElement(prefix + 6 + suffix).getAttribute('fill')).toBe('grey');
expect(getElement(prefix + 7 + suffix).getAttribute('fill')).toBe(paletteColor[7]);
expect(getElement(prefix + 8 + suffix).getAttribute('fill')).toBe(paletteColor[8]);
expect(getElement(prefix + 9 + suffix).getAttribute('fill')).toBe(paletteColor[9]);
expect(getElement(prefix + 10 + suffix).getAttribute('fill')).toBe(paletteColor[0]);
expect(getElement(prefix + 11 + suffix).getAttribute('fill')).toBe(paletteColor[1]);
done();
};
chartObj.loaded = loaded;
chartObj.series[3].fill = 'violet';
chartObj.series[6].fill = 'grey';
chartObj.refresh();
});
it('Checking series fill with data bind', (done: Function) => {
loaded = (args: Object): void => {
let prefix: string = 'theme_Series_';
let suffix: string = '_Point_0';
expect(getElement(prefix + 0 + suffix).getAttribute('fill')).toBe('violet');
done();
};
chartObj.loaded = loaded;
chartObj.palettes = ['violet'];
chartObj.legendSettings.visible = false;
chartObj.dataBind();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
}); | the_stack |
import "mocha";
import {expect} from "chai";
import {parseBibFile} from "../src/bibfile/BibFile";
import {isOuterQuotedString, OuterQuotedString, QuotedString} from "../src/bibfile/datatype/string/QuotedString";
import {isNumber, mustBeArray, mustBeDefined} from "../src/util";
import {BibEntry, EntryFields} from "../src/bibfile/bib-entry/BibEntry";
import {determineAuthorNames$, mustBeAuthors} from "../src/bibfile/bib-entry/bibliographic-entity/Authors";
import {BracedString} from "../src/bibfile/datatype/string/BracedString";
import Lexer from "../src/lexer/Lexer";
import {BibStringData} from "../src/bibfile/datatype/string/BibStringData";
import {splitOnComma, splitOnPattern, toStringBibStringData} from "../src/bibfile/datatype/string/bib-string-utils";
import {FieldValue} from "../src/bibfile/datatype/KeyVal";
import {parseAuthorName} from "../src/bibfile/bib-entry/bibliographic-entity/Author";
// TODO test crossref?
describe("Author: von Last, First", () => {
it("von Last, First", function () {
const authorName = parseAuthorName(["Von De la ", "Last", ",", "firstName= ", "."]);
expect(authorName.vons$[1].indexOf("De")).to.greaterThan(-1);
expect(authorName.lastNames$[0].indexOf("Last")).to.greaterThan(-1);
expect(authorName.jrs$).to.deep.equal([]);
expect(authorName.firstNames$[0].indexOf("firstName=")).to.greaterThan(-1);
});
// NOTE: This case raises an error message from BibTEX, complaining that a name ends with a comma. It is a common error to separate names with commas instead of “and”
it("jean de la fontaine,", function () {
const authorName = parseAuthorName(["jean de la fontaine,"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("jean de la");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("de la fontaine, Jean", function () {
const authorName = parseAuthorName(["de la fontaine, Jean"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("de la");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("De La Fontaine, Jean", function () {
const authorName = parseAuthorName(["De La Fontaine, Jean"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("De La Fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("De la Fontaine, Jean", function () {
const authorName = parseAuthorName(["De la Fontaine, Jean"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("De la");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("Fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("de La Fontaine, Jean", function () {
const authorName = parseAuthorName(["de La Fontaine, Jean"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("de");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("La Fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
});
describe("Author: von Last, Jr, First", () => {
// NOTE: This case raises an error message from BibTEX, complaining that a name ends with a comma. It is a common error to separate names with commas instead of “and”
it("jean de la fontaine,", function () {
const authorName = parseAuthorName(["jean de la fontaine,,"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("jean de la");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("de la fontaine, Jr., Jean", function () {
const authorName = parseAuthorName(["de la fontaine, Jr., Jean"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("de la");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("Jr.");
});
it("De La Fontaine, Jr., Jean", function () {
const authorName = parseAuthorName(["De La Fontaine, Jr., Jean"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("De La Fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("Jr.");
});
it("De la Fontaine, Jr., Jean", function () {
const authorName = parseAuthorName(["De la Fontaine, Jr., Jean"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("De la");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("Fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("Jr.");
});
it("de La Fontaine, Jr., Jean", function () {
const authorName = parseAuthorName(["de La Fontaine, Jr., Jean"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("de");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("La Fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("Jr.");
});
it("von Last, Jr., First", function () {
const authorName = parseAuthorName(["von ", "Last", ", Jr.", ",", "firstName, ", ".,,,etc,,"]);
expect(authorName.vons$[0].indexOf("von")).to.greaterThan(-1);
expect(authorName.lastNames$[0].indexOf("Last")).to.greaterThan(-1);
expect(authorName.jrs$[0].indexOf("Jr.")).to.greaterThan(-1);
expect(authorName.firstNames$[0].indexOf("firstName,")).to.greaterThan(-1);
});
});
describe("Author: First von Last", () => {
it("First von Last", function () {
const authorName = parseAuthorName(["First von Last"]);
expect(authorName.vons$[0].indexOf("von")).to.greaterThan(-1);
expect(authorName.lastNames$[0].indexOf("Last")).to.greaterThan(-1);
expect(authorName.jrs$.length).to.equal(0);
expect(authorName.firstNames$[0].indexOf("First")).to.greaterThan(-1);
});
it("jean de la fontaine", function () {
const authorName = parseAuthorName(["jean de la fontaine"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("jean de la");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("Jean de la fontaine", function () {
const authorName = parseAuthorName(["Jean de la fontaine"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("de la");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("Jean {de} la fontaine", function () {
const authorName = parseAuthorName(["Jean ", new BracedString(0, ["de"]), " la fontaine"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean de");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("la");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("jean {de} {la} fontaine", function () {
const authorName = parseAuthorName(["jean ", new BracedString(0, ["de"]), " ",
new BracedString(0, ["la"]), " fontaine"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("jean");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("de la fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("Jean {de} {la} fontaine", function () {
const authorName = parseAuthorName(["Jean ", new BracedString(0, ["de"]), " ",
new BracedString(0, ["la"]), " fontaine"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean de la");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("Jean De La Fontaine", function () {
const authorName = parseAuthorName(["Jean De La Fontaine"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean De La");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("Fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("jean De la Fontaine", function () {
const authorName = parseAuthorName(["jean De la Fontaine"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("jean De la");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("Fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
it("Jean de La Fontaine", function () {
const authorName = parseAuthorName(["Jean de La Fontaine"]);
expect(authorName.firstNames$.map(toStringBibStringData).join(" ")).to.eq("Jean");
expect(authorName.vons$.map(toStringBibStringData).join(" ")).to.eq("de");
expect(authorName.lastNames$.map(toStringBibStringData).join(" ")).to.eq("La Fontaine");
expect(authorName.jrs$.map(toStringBibStringData).join(" ")).to.eq("");
});
});
describe("utils", () => {
it("split on pattern", function () {
expect(
splitOnPattern(
["xx", "xx", "endfirst xxx startsecond", " xxx xxx xxx3", "xxx xxx", "midxxxEOF"],
/\s*xxx\s*/g,
3
)
).to.deep.equal(
[
[
"xx",
"xx",
"endfirst"
],
[
"startsecond",
""
],
[
""
],
[
"xxx3",
"xxx xxx",
"midxxxEOF"
],
]
);
});
it("split on pattern", function () {
expect(
splitOnPattern(["xx", "xx", "xx"], /\s*xxx\s*/g, 3)
).to.deep.equal(
[["xx", "xx", "xx"]]
);
});
it("split on ,", function () {
expect(
splitOnComma(["von ", "Last", ", ", "name, ", "Jr.,,,etc,,"], 3)
).to.deep.equal(
[
[
"von ",
"Last",
""
],
[
"name"
],
[
"Jr."
],
[
",,etc,,"
]
]
);
});
});
describe("lexer", () => {
it("should lex", function () {
const lexer1 = new Lexer("\n\t\nthisisallacommentof{}commentswitheverythingexceptan\", whichweca123nescapewitha0123 ");
expect(
lexer1.readTokens()
).to.deep.equal([
{"type": "ws", "string": "\n\t\n"},
{"type": "id", "string": "thisisallacommentof"},
"{",
"}",
{"type": "id", "string": "commentswitheverythingexceptan"},
"\"",
",",
{"type": "ws", "string": " "},
{"type": "id", "string": "whichweca"},
123,
{"type": "id", "string": "nescapewitha"},
{"type": "number", "string": "0123"},
{"type": "ws", "string": " "}
]
);
});
});
describe("field values", () => {
it("should handle strings of all shapes", function () {
const bib = parseBibFile(`
@string{ abc = "def" }
@b00k{comp4nion,
quoted = "Simple quoted string",
quotedComplex = "Complex " # quoted #" string",
braced = {I am a so-called "braced string09 11"},
bracedComplex = {I {{\\am}} a {so-called} {\\"b}raced string{\\"}.},
number = 911 ,
naughtyNumber = a911a,
a911a = {a911a},
naughtyString = abc
}
@string{ quoted = " referenced" }
@string{ a911a = {b911c} }
`);
expect(bib.entries$.comp4nion.getField("quoted")).to.deep.equal(new OuterQuotedString([
new QuotedString(0, [
"Simple", " ", "quoted", " ", "string"
])
]));
// TODO
// expect(bib.entries$.comp4nion.getField("quotedCOMPLEX")).to.deep.equal(
// {
// "type": "quotedstringwrapper",
// "braceDepth": 0,
// "data": [{"type": "quotedstring", "braceDepth": 0, "data": ["Complex", " "]}, {
// "braceDepth": 0,
// "stringref": "quoted"
// }, {"type": "quotedstring", "braceDepth": 0, "data": [" ", "string"]}]
// }
// );
// expect(bib.entries$.comp4nion.getField("braced")).to.deep.equal(
// {
// "type": "bracedstringwrapper",
// "braceDepth": 0,
// "data": [
// "I", " ", "am", " ", "a", " ", "so-called", " ",
// "\"", "braced", " ", "string", "09", " ", 11, "\""
// ]
// }
// );
const bracedComplex: any = bib.entries$.comp4nion.getField("bracedCOMPLEX");
expect(bracedComplex.type).to.equal("bracedstringwrapper");
const bracedComplexData = bracedComplex.data;
const bracedComplexDatum0: any = bracedComplexData[0];
const bracedComplexDatum2: any = bracedComplexData[2];
expect(bracedComplexDatum0).to.equal("I");
const bracedComplexDatum2Data: any = bracedComplexDatum2.data;
const bracedComplexDatum2Datum0: any = bracedComplexDatum2Data[0];
expect(bracedComplexDatum2Datum0.braceDepth).to.equal(1);
const numberField = bib.entries$.comp4nion.getField("number");
expect(numberField).to.equal(911);
const naughtyNumber: any = mustBeDefined(bib.entries$.comp4nion.getField("naughtyNumber"));
const t: any = naughtyNumber["type"];
const nnData: any[] = mustBeArray(naughtyNumber["data"]);
expect(t).to.equal("quotedstringwrapper");
});
it("should tease apart author names", function () {
function qs(data: BibStringData): QuotedString {
return new QuotedString(0, data);
}
function bs(data: BibStringData): QuotedString {
return new BracedString(0, data);
}
expect(determineAuthorNames$(new OuterQuotedString([1]))).to.deep.equal([["1"]]);
const auth2 = new OuterQuotedString(
[1, qs([" a"]), "n", "d", qs([" "]), bs(["\\", "two"])]
);
const authNames2 = determineAuthorNames$(auth2);
expect(authNames2.length).to.deep.equal(2);
expect(authNames2[0]).to.deep.equal(["1"]);
expect(authNames2[1][0]["type"]).to.deep.equal("bracedstring"/*{
"braceDepth": 0,
"data": [
"\\",
"two"
],
"isSpecialCharacter": true,
"type": "bracedstring"
}*/);
});
it("should determine author names", function () {
const bib = parseBibFile(` @ STRiNG { mittelbach = "Mittelbach, Franck" }
some comment
@b00k
{ comp4nion ,
auTHor = "Goossens, jr, Mich{\\\`e}l Frederik and " # mittelbach # " and "#"{ { A}}le"#"xander de La Samarin ",\n
}`);
const book: BibEntry = mustBeDefined(bib.getEntry("COMP4NION"));
// console.log(
mustBeDefined(book.getAuthors()).authors$;
// );
});
it("should flatten quoted strings", function () {
const bib = parseBibFile(`
@string { quoted = "QUO" # "TED" }
@string { braced = {"quoted"} }
@a{b,
bracedComplex = {I {{\\am}} {\\"a} "so-"called"" braced string{\\"}.},
quotedComplex = "and I {"} am a {"} " # quoted # " or "#braced#"string ",
number = 911,
}`);
// stringref = abc
const a: BibEntry = bib.entries$.b;
const fields$: EntryFields = a.fields;
const bracedcomplex: FieldValue = fields$.bracedcomplex;
if (isNumber(bracedcomplex)) throw Error();
// console.log(flattenQuotedStrings(bracedcomplex.data, true));
const quotedComplex: FieldValue = fields$.quotedcomplex;
if (isNumber(quotedComplex)) throw Error();
// console.log(flattenQuotedStrings(quotedComplex.data, true));
const nineEleven: FieldValue = fields$.number;
expect(nineEleven).to.equal(911);
});
/* todo implement
it("should process titles correctly", function () {
const bib = parseBibFile(`
This won’t work, since turning it to lower case will produce
The \latex companion, and LATEX won't accept this...
@article{lowercased, title = "The \LaTeX Companion"}
This ensures that switching to lower case will be
correct. However, applying purify$ gives The
Companion. Thus sorting could be wrong;
@article{wrongsorting1, title = "The {\csname LaTeX\endcsname} {C}ompanion"}
In this case, { \LaTeX} is not a special character,
but a set of letters at depth 1. It won’t be modified by change.case$. However, purify$ will
leave both spaces, and produce The LaTeX Companion, which could result in wrong sorting;
@article{wrongsorting2, title = "The { \LaTeX} {C}ompanion"}
@article{works1, title = "The{ \LaTeX} {C}ompanion"}
@article{works2, title = "The {{\LaTeX}} {C}ompanion"}
For encoding an accent in a title, say É (in upper case) as in the French word École, we’ll write
{\’{E}}cole, {\’E}cole or {{\’E}}cole, depending on whether we want it to be turned to lower
case (the first two solutions) or not (the last one). purify$ will give the same result in the three
cases. However, it should be noticed that the third one is not a special character. If you ask BibTEX
to extract the first character of each string using text.prefix$, you’ll get {\’{E}} in the first case,
{\’E} in the second case and {{\}} in the third case.
@article{ecoleLowercased1, title = "{\'{E}}cole"}
@article{ecoleLowercased2, title = "{\'E}cole"}
@article{ecoleUppercased, title = "{{\'E}}cole"}
`);*/
/* todo implement
it("should process authors correctly", function () {
const bib = parseBibFile(`
The first point to notice is that two authors are separated with the keyword and. The format of the
names is the second important point: The last name first, then the first name, with a separating
comma. In fact, BibTEX understands other formats
@article{authors, author = "Goossens, Michel and Mittelbach, Franck and Samarin, Alexander"}
// TODO additional cases in http://tug.ctan.org/info/bibtex/tamethebeast/ttb_en.pdf
`);*/
// TODO crossref ; additional cases in http://tug.ctan.org/info/bibtex/tamethebeast/ttb_en.pdf
// });
});
describe("parser", () => {
it("should parse comments", function () {
const bib = parseBibFile("\n\t\nthisisallacommentof{}commentswitheverythingexceptan\", whichweca123nescapewitha0123 ");
// console.log(JSON.stringify(bib));
expect(bib.entries_raw.length).to.equal(0);
expect(bib.comments.length).to.equal(1);
expect(bib.content.length).to.equal(1);
const firstComment = bib.comments[0].data;
expect(firstComment[0]).to.equal("\n\t\n");
expect(firstComment[9]).to.equal("123");
expect(firstComment[11]).to.equal("0123");
});
it("should parse empty", function () {
expect(parseBibFile("").content.length).to.equal(0);
});
it("should throw for cyclic string entries", function () {
let thrown = false;
try {
parseBibFile(
`@string{c = "a"#b}
@string{b = "b"#a}`
);
} catch (e) {
thrown = true;
}
expect(thrown).to.equal(true);
});
it("should parse string entries", function () {
const bib = parseBibFile(`leading comment
@ STRiNG { mittelbach = "Mittelbach, Franck" }
@string{acab= a #_# c #_#"are" #_# b}
@string{c = "co"#cc}
@string{a = "a"#l#l}
@string{_ = {{{{{ }}}}}}
@string{l = {l}}
@string{cc ={mp{\\"u}ters}}
@string{b = "beautifu"#l} `
);
expect(bib.content.length).to.equal(17);
// expect(bib.entries[0]["data"].key).to.equal("mittelbach");
const acab = bib.strings_raw.acab;
if (isOuterQuotedString(acab)) {
const thirdDatum: any = acab.data[3];
expect(thirdDatum.stringref).to.equal("_");
const fourthDatum: any = acab.data[4];
expect(fourthDatum["type"]).to.equal("quotedstring");
} else
expect(isOuterQuotedString(acab)).to.throw();
const acab$ = bib.strings$.acab;
if (isOuterQuotedString(acab$)) {
expect(acab$.stringify()).to.equal("all comp\\\"uters are beautiful");
const thirdDatum: any = acab$.data[3];
expect(thirdDatum.type).to.equal("bracedstringwrapper");
const fourthDatum: any = acab$.data[4];
expect(fourthDatum["type"]).to.equal("quotedstring");
} else expect(isOuterQuotedString(acab$)).to.throw();
});
it("should parse bib entries", function () {
const bib = parseBibFile(` @ STRiNG { mittelbach = "Mittelbach, Franck" }
some comment
@b00k
{ comp4nion ,
auTHor = "Goossens, jr, Mich{\\\`e}l Frederik and " # mittelbach # " and "#"{ { A}}le"#"xander de La Samarin ",\n
titLe = "The {{\\LaTeX}} {C}{\\"o}mp{\\"a}nion",
publisher = "Addison-Wesley",
yeaR=1993 ,
Title = {{Bib}\\TeX},
title = {{Bib}\\TeX},
Title2 = "{Bib}\\TeX",
Title3 = "{Bib}" # "\\TeX"
}`);
expect(bib.content.length).to.equal(4);
// console.log(JSON.stringify(bib.content));
const entry: BibEntry = mustBeDefined(bib.getEntry("Comp4nion"));
const authors = mustBeAuthors(mustBeDefined(entry.getField("author")));
expect(authors).to.not.be.null;
expect(authors.authors$.length).to.eq(3);
// console.log(authors.authors$);
});
it("should parse preamble entries", function () {
const bib = parseBibFile(`@preamble{ "\\@ifundefined{url}{\\def\\url#1{\\texttt{#1}}}{}" }
@preamble{ "\\makeatletter" }
@preamble{ "\\makeatother" }
`);
expect(bib.preamble$, ` "\\@ifundefined{url}{\\def\\url#1{\\texttt{#1}}}{}"
"\\makeatletter"
"\\makeatother" `);
});
}); | the_stack |
let appScript = {
info: {
totalResults: ['大约有','約','About','大約有'],
totalResults1: ['条记录','件','results','條記錄'],
moreResults: ['更多结果','結果をさらに表示','More Results','更多結果'],
searchToolBarMenu: [
[
'网站','ウェイブ','Website','網頁'
],[
'新闻','ニュース','News','新聞'
],[
'图片','画像','Picture','圖片'
],[
'视频','ビデオ','Video','視頻'
]
]
},
showMain: ko.observable ( true ),
showWebPage: ko.observable ( null ),
htmlIframe: ko.observable ( false ),
showSnapshop: ko.observable ( false ),
searchItemsArray: ko.observable (),
hasFocusShowTool: ko.observable ( false ),
backGroundBlue: ko.observable ( false ),
searchItem: ko.observable ( null ),
showMainSearchForm: ko.observable ( true ),
showSearchSetupForm: ko.observable ( false ),
showSearchError: ko.observable ( false ),
showInputLoading: ko.observable ( false ),
errorMessageIndex: ko.observable ( -1 ),
searchInputText: ko.observable (''),
hasFocus: ko.observable ( false ),
passwordError: ko.observable ( false ),
searchSetupIcon: ko.observable ( bingIcon ),
password: ko.observable (''),
searchInputTextActionShow: ko.observable ( false ),
SearchInputNextHasFocus: ko.observable ( false ),
showSearchesRelated: ko.observable ( false ),
searchItemList: ko.observableArray ([]),
loadingGetResponse: ko.observable ( false ),
conetResponse: ko.observable ( false ),
searchInputTextShow: ko.observable (''),
currentlyShowItems: ko.observable ( 0 ),
newsButtonShowLoading: ko.observable ( false ),
newsItemsArray: ko.observable (),
newsButtonShowError: ko.observable ( false ),
newsButtonErrorIndex: ko.observable ( null ),
newsLoadingGetResponse: ko.observable ( false ),
newsConetResponse: ko.observable ( false ),
nextButtonShowError: ko.observable ( false ),
moreResultsButtomLoading: ko.observable ( false ),
imageButtonShowLoading: ko.observable ( false ),
imageButtonShowError: ko.observable ( false ),
imageButtonErrorIndex: ko.observable ( -1 ),
imageLoadingGetResponse: ko.observable ( false ),
imageConetResponse: ko.observable ( false ),
imageItemsArray: ko.observable (),
searchSimilarImagesList: ko.observableArray ([]),
showSearchSimilarImagesResult: ko.observable ( false ),
imageSearchItemArray: ko.observable (),
videoButtonShowLoading: ko.observable ( false ),
videoItemsArray: ko.observable (),
videoButtonShowError: ko.observable ( false ),
videoButtonErrorIndex: ko.observable ( -1 ),
videoLoadingGetResponse: ko.observable ( false ),
videoConetResponse: ko.observable ( false ),
nextButtonErrorIndex: ko.observable ( false ),
nextButtonConetResponse: ko.observable ( false ),
nextButtonLoadingGetResponse: ko.observable ( false ),
// ['originImage']
initSearchData: ( self ) => {
self.searchItem ( null )
self.searchItemList ([])
self.showInputLoading ( true )
self.showSearchesRelated ( false )
self.newsItemsArray ( null )
self.imageItemsArray ( null )
self.showSearchesRelated ( null )
self.videoItemsArray ( null )
self.imageSearchItemArray ( null )
},
showResultItems: ( self, items ) => {
self.searchItem ( items )
self.searchItemList ( items.Result )
$('.selection.dropdown').dropdown()
},
searchSetupClick: ( self, event ) => {
self.showSearchSetupForm ( true )
self.backGroundBlue ( true )
/*
$('#coSearchBackGround').one ( 'click', function() {
self.backGroundClick ()
$('#coSearchForm').off ('click')
})
$('#coSearchForm').one ( 'click', function() {
self.backGroundClick ()
$('#coSearchBackGround').off ('click')
})
*/
return false
},
searchInputCloseError: ( self, event ) => {
self.showSearchError ( false )
self.errorMessageIndex (null)
},
returnSearchResultItemsInit: ( items ) => {
let i = 0
const y = []
items.Result.forEach ( n => {
i++
n['showLoading'] = ko.observable ( false )
n['conetResponse'] = ko.observable ( false )
n['loadingGetResponse'] = ko.observable ( false )
n['snapshotReady'] = ko.observable ( false )
n['snapshotClass'] = null
n['snapshotData'] = null
n['snapshotUuid'] = null
n['id'] = uuid_generate ()
n['showError'] = ko.observable ( false )
n['errorIndex'] = ko.observable ( -1 )
if ( !n['newsBrand'] ) {
n['newsBrand'] = null
}
if ( n.imageInfo ) {
if ( !n.imageInfo['videoTime'] ) {
n.imageInfo['videoTime'] = null
}
}
n['webUrlHref'] = n.clickUrl
n['imgUrlHref'] = n.imgSrc
n['showImageLoading'] = ko.observable ( false )
n['showImageError'] = ko.observable ( false )
n['snapshotImageReady'] = ko.observable ( false )
n['loadingImageGetResponse'] = ko.observable ( false )
n['conetImageResponse'] = ko.observable ( false )
n['imageErrorIndex'] = ko.observable (-1)
})
},
search_form: ( self, event ) => {
if ( self.showInputLoading()) {
return
}
if ( !_view.CanadaBackground ()) {
_view.CanadaBackground ( true )
}
if ( !self.showMainSearchForm()) {
self.showMainSearchForm( true )
}
const search_text = self.searchInputText ()
const width = window.innerWidth
const height = window.outerHeight
self.initSearchData ( self )
const com: QTGateAPIRequestCommand = {
command: 'CoSearch',
Args: null,
error: null,
subCom: null
}
/**
* web page address
*/
if ( /^http[s]?:\/\//.test( search_text )) {
com.Args = [ search_text, width, height ]
com.subCom = 'getSnapshop'
} else {
com.Args = [ 'google', search_text ]
com.subCom = 'webSearch'
}
const errorProcess = ( err ) => {
self.showInputLoading ( false )
self.searchInputText ( '' )
self.errorMessageIndex ( _view.connectInformationMessage.getErrorIndex( err ))
return self.showSearchError ( true )
}
/**
*
* test Unit
*/
return _view.keyPairCalss.emitRequest ( com, ( err, com: QTGateAPIRequestCommand ) => {
if ( err ) {
return errorProcess ( err )
}
if ( !com ) {
return self.loadingGetResponse ( true )
}
if ( com.error === -1 ) {
self.loadingGetResponse ( false )
return self.conetResponse ( true )
}
if ( com.error ) {
return errorProcess ( com.error )
}
if ( com.subCom === 'webSearch') {
self.showInputLoading ( false )
const args = com.Args
self.searchInputTextShow ( search_text )
self.returnSearchResultItemsInit ( args.param )
self.searchItemsArray ( args.param )
self.showResultItems ( self, args.param )
_view.CanadaBackground ( false )
return self.showMainSearchForm ( false )
}
const arg: string = com.Args[0]
const uuid = arg.split(',')[0].split ('.')[0]
return _view.connectInformationMessage.sockEmit ( 'getFilesFromImap', arg, ( err, buffer: string ) => {
if ( err ) {
return errorProcess ( err )
}
return _view.keyPairCalss.decryptMessageToZipStream ( buffer, ( err, data ) => {
if ( err ) {
return errorProcess ( err )
}
self.showInputLoading ( false )
_view.CanadaBackground ( false )
self.showMainSearchForm ( false )
self.showMain ( false )
self.showSnapshop ( true )
let y = null
self.showWebPage ( y = new showWebPageClass ( search_text, buffer, uuid , () => {
self.showWebPage ( y = null )
self.showMain ( true )
self.showSnapshop ( false )
_view.CanadaBackground ( true )
self.showMainSearchForm ( true )
}))
})
})
})
},
searchSetup: ( key: string, self, event ) => {
self.showSearchSetupForm ( false )
self.backGroundBlue ( false )
switch ( key ) {
case 'b': {
return self.searchSetupIcon ( bingIcon )
}
case 'd': {
return self.searchSetupIcon ( duckduckgoIcon )
}
case 'y': {
return self.searchSetupIcon ( YahooIcon )
}
default: {
self.searchSetupIcon ( googleIcon )
}
}
},
startup: ( self ) => {
self.password.subscribe (( _text: string ) => {
self.passwordError ( false )
})
self.hasFocus.subscribe (( _result: boolean ) => {
if ( _result ) {
self.hasFocusShowTool ( true )
return self.backGroundBlue ( true )
}
/*
if ( self.showMain () ) {
if ( !self.searchInputText().length ) {
self.searchInputTextActionShow ( false )
return self.backGroundBlue ( _result )
}
self.searchInputTextActionShow ( true )
_result = false
return true
}
if ( !_result ) {
return true
}
if ( _result ) {
if ( !self.showSubViewToolBar ()) {
self.showSubViewToolBar ( true )
}
}
return true
*/
})
self.searchInputText.subscribe (( _text: string ) => {
self.searchInputTextActionShow ( _text.length > 0 )
})
self.SearchInputNextHasFocus.subscribe (( hasFocus: boolean ) => {
if ( hasFocus ) {
self.showSearchesRelated ( true )
}
})
_view.showIconBar ( false )
_view.CanadaBackground ( true )
},
nextButtonErrorClick: ( self ) => {
self.nextButtonShowError ( false )
self.nextButtonErrorIndex ( null )
},
webItemsClick: ( self, event ) => {
self.currentlyShowItems ( 0 )
self.showResultItems ( self, self.searchItemsArray ())
},
searchNext: ( self, event ) => {
const nextLink = self.searchItem().nextPage
if ( self.moreResultsButtomLoading () || !nextLink ) {
return
}
self.moreResultsButtomLoading ( true )
function showError ( err ) {
self.moreResultsButtomLoading ( false )
self.nextButtonErrorIndex ( _view.connectInformationMessage.getErrorIndex ( err ))
self.nextButtonShowError ( true )
}
let currentArray = null
const com: QTGateAPIRequestCommand = {
command: 'CoSearch',
Args: [ 'google', nextLink ],
error: null,
subCom: null
}
switch ( self.currentlyShowItems ()) {
// google search
case 0: {
com.subCom = 'searchNext'
currentArray = self.searchItemsArray()
break
}
// news
case 1: {
com.subCom = 'newsNext'
currentArray = self.newsItemsArray()
break
}
case 2: {
com.subCom = 'imageSearchNext'
currentArray = self.imageSearchItemArray()
break
}
default: {
com.subCom = 'videoNext'
currentArray = self.videoItemsArray()
break
}
}
/** */
return _view.keyPairCalss.emitRequest ( com, ( err, com: QTGateAPIRequestCommand ) => {
if ( err ) {
return showError ( err )
}
if ( !com ) {
return self.nextButtonLoadingGetResponse ( true )
}
if ( com.error === -1 ) {
self.nextButtonLoadingGetResponse ( false )
return self.nextButtonConetResponse ( true )
}
if ( com.error ) {
return showError ( com.error )
}
self.moreResultsButtomLoading ( false )
self.nextButtonLoadingGetResponse ( false )
self.nextButtonConetResponse ( false )
const args = com.Args
self.returnSearchResultItemsInit ( args.param )
currentArray.Result.push ( ...args.param.Result )
currentArray.nextPage = args.param.nextPage
return self.showResultItems ( self, currentArray )
})
},
createNewsResult: ( self, newsResult ) => {
const newsItems = JSON.parse ( JSON.stringify ( self.searchItemsArray ()))
newsItems.Result = newsResult.Result
newsItems.nextPage = newsResult.nextPage
newsItems.totalResults = newsResult.totalResults
return newsItems
},
newsButtonClick: ( self, event ) => {
if ( self.newsButtonShowLoading ()) {
return
}
if ( self.newsButtonShowError ()) {
self.newsButtonShowError( false )
return self.newsButtonErrorIndex ( null )
}
self.newsButtonShowLoading ( true )
const errorProcess = ( err ) => {
self.newsButtonShowLoading ( false )
self.newsLoadingGetResponse ( false )
self.newsConetResponse ( false )
self.newsButtonErrorIndex ( _view.connectInformationMessage.getErrorIndex( err ))
return self.newsButtonShowError ( true )
}
if ( ! self.newsItemsArray() ) {
if ( !self.searchItemsArray().action || !self.searchItemsArray().action.news ) {
return errorProcess ('invalidRequest')
}
const com: QTGateAPIRequestCommand = {
command: 'CoSearch',
Args: [ 'google', self.searchItemsArray().action.news ],
error: null,
subCom: 'newsNext'
}
return _view.keyPairCalss.emitRequest ( com,( err, com: QTGateAPIRequestCommand ) => {
if ( err ) {
return errorProcess ( err )
}
if ( !com ) {
return self.newsLoadingGetResponse ( true )
}
if ( com.error === -1 ) {
self.newsLoadingGetResponse ( false )
return self.newsConetResponse ( true )
}
if ( com.error ) {
return errorProcess ( com.error )
}
self.newsButtonShowLoading ( false )
self.newsConetResponse ( false )
self.newsLoadingGetResponse ( false )
const args = com.Args
self.newsItemsArray ( self.createNewsResult( self, args.param ))
self.returnSearchResultItemsInit ( self.newsItemsArray () )
})
}
self.currentlyShowItems(1)
self.newsButtonShowLoading ( false )
return self.showResultItems ( self, self.newsItemsArray() )
},
imageButtonClick: ( self, event ) => {
if ( self.imageButtonShowLoading ()) {
return
}
if ( self.imageButtonShowError ()) {
self.imageButtonShowError ( false )
return self.imageButtonErrorIndex ( null )
}
const errorProcess = ( err ) => {
self.imageButtonShowLoading ( false )
self.imageLoadingGetResponse ( false )
self.imageConetResponse ( false )
self.imageButtonErrorIndex ( _view.connectInformationMessage.getErrorIndex( err ))
return self.imageButtonShowError ( true )
}
if ( ! self.imageItemsArray() ) {
const imageLink = self.searchItemsArray() && self.searchItemsArray().action && self.searchItemsArray().action.image ? self.searchItemsArray().action.image : self.imageSearchItemArray().searchesRelated[1]
const com: QTGateAPIRequestCommand = {
command: 'CoSearch',
Args: [ 'google', imageLink ],
error: null,
subCom: 'imageNext'
}
self.imageButtonShowLoading ( true )
return _view.keyPairCalss.emitRequest ( com,( err, com: QTGateAPIRequestCommand ) => {
if ( err ) {
return errorProcess ( err )
}
if ( !com ) {
self.imageConetResponse ( false )
return self.imageLoadingGetResponse ( true )
}
if ( com.error === -1 ) {
self.imageLoadingGetResponse ( false )
return self.imageConetResponse ( true )
}
const args = com.Args
if ( com.error ) {
return errorProcess ( com.error )
}
if ( !args.param || !args.param.Result || !args.param.Result.length ) {
return errorProcess ( 'timeOut' )
}
self.imageButtonShowLoading ( false )
self.imageConetResponse ( false )
self.imageLoadingGetResponse ( false )
self.imageItemsArray ( args.param )
self.returnSearchResultItemsInit ( self.imageItemsArray () )
})
/** */
}
self.searchSimilarImagesList( self.imageItemsArray().Result )
self.showMain ( false )
self.showSearchSimilarImagesResult ( true )
},
getSnapshotClick: ( self, index ) => {
const currentItem = self.searchItemList()[ index ]
currentItem.showLoading ( true )
const showError = err => {
currentItem.showLoading ( false )
currentItem.loadingGetResponse ( false )
currentItem.conetResponse ( false )
currentItem.errorIndex ( _view.connectInformationMessage.getErrorIndex ( err ))
currentItem.showError ( true )
const currentElm = $(`#${ currentItem.id }`)
return currentElm.popup ({
on: 'click',
inline: true,
onHidden: function () {
currentItem.showError ( false )
currentItem.errorIndex ( null )
}
})
}
const callBack = ( err?, com?: QTGateAPIRequestCommand ) => {
if ( err ) {
return showError ( err )
}
if ( !com ) {
currentItem.loadingGetResponse ( true )
return currentItem.conetResponse ( false )
}
if ( com.error === -1 ) {
currentItem.loadingGetResponse ( false )
return currentItem.conetResponse ( true )
}
if ( com.error ) {
return showError ( com.error )
}
const arg: string = com.Args[0]
currentItem.snapshotUuid = arg.split(',')[0].split ('.')[0]
return _view.connectInformationMessage.sockEmit ( 'getFilesFromImap', arg, ( err, buffer: string ) => {
if ( err ) {
return showError ( err )
}
return _view.keyPairCalss.decryptMessageToZipStream ( buffer, ( err, data ) => {
if ( err ) {
return showError ( err )
}
currentItem.snapshotReady ( true )
currentItem.showLoading ( false )
currentItem.loadingGetResponse ( false )
currentItem.conetResponse ( false )
return currentItem.snapshotData = buffer
})
})
}
const url = currentItem.url
const width = $(window).width()
const height = $(window).height()
const com: QTGateAPIRequestCommand = {
command: 'CoSearch',
Args: [ url, width, height ],
error: null,
subCom: 'getSnapshop'
}
return _view.keyPairCalss.emitRequest ( com, callBack )
},
showSnapshotClick: ( self, index ) => {
self.showMain ( false )
self.showSnapshop ( true )
const currentItem = self.searchItemList()[ index ]
let y = null
self.showWebPage ( y = new showWebPageClass ( currentItem.url, currentItem.snapshotData, currentItem.snapshotUuid , () => {
self.showWebPage ( y = null )
self.showMain ( true )
self.showSnapshop ( false )
}))
},
searchesRelatedSelect: ( self, index ) => {
self.searchInputText ( self.searchItem().searchesRelated[index].text )
self.showSearchesRelated ( false )
},
closeSimilarImagesResult: ( self ) => {
self.searchSimilarImagesList ([])
self.showMain ( true )
self.showSearchSimilarImagesResult ( false )
},
videoButtonClick: ( self ) => {
if ( self.videoButtonShowLoading ()) {
return
}
if ( self.videoButtonShowError ()) {
self.videoButtonShowError ( false )
return self.imageButtonErrorIndex ( null )
}
const errorProcess = ( err ) => {
self.videoButtonShowLoading ( false )
self.videoLoadingGetResponse ( false )
self.videoConetResponse ( false )
self.videoButtonErrorIndex ( _view.connectInformationMessage.getErrorIndex ( err ))
return self.videoButtonShowError ( true )
}
if ( ! self.videoItemsArray() ) {
if ( !self.searchItemsArray().action || !self.searchItemsArray().action.video ) {
return errorProcess ('invalidRequest')
}
const com: QTGateAPIRequestCommand = {
command: 'CoSearch',
Args: [ 'google', self.searchItemsArray().action.video ],
error: null,
subCom: 'videoNext'
}
self.videoButtonShowLoading ( true )
return _view.keyPairCalss.emitRequest ( com,( err, com: QTGateAPIRequestCommand ) => {
if ( err ) {
return errorProcess ( err )
}
if ( !com ) {
self.videoConetResponse ( false )
return self.videoLoadingGetResponse ( true )
}
if ( com.error === -1 ) {
self.videoLoadingGetResponse ( false )
return self.videoConetResponse ( true )
}
if ( com.error ) {
return errorProcess ( com.error )
}
self.videoButtonShowLoading ( false )
self.videoLoadingGetResponse ( false )
self.videoConetResponse ( false )
const args = com.Args
self.videoItemsArray ( self.createNewsResult( self, args.param ))
self.returnSearchResultItemsInit ( self.videoItemsArray () )
})
/** */
}
self.currentlyShowItems(3)
return self.showResultItems ( self, self.videoItemsArray() )
},
getPictureBase64MaxSize_mediaData: ( mediaData: string, imageMaxWidth: number, imageMaxHeight: number, CallBack ) => {
const media = mediaData.split(',')
const type = media[0].split(';')[0].split (':')[1]
const _media = Buffer.from ( media[1], 'base64')
const ret: twitter_mediaData = {
total_bytes: media[1].length,
media_type: 'image/png',
rawData: media[1],
media_id_string: null
}
//if ( mediaData.length > maxImageLength) {
const exportImage = ( _type, img ) => {
return img.getBuffer ( _type, ( err, _buf: Buffer ) => {
if ( err ) {
return CallBack ( err )
}
ret.rawData = _buf.toString( 'base64' )
ret.total_bytes = _buf.length
return CallBack ( null, ret )
})
}
return Jimp.read ( _media, ( err, image ) => {
if ( err ) {
return CallBack ( err )
}
const uu = image.bitmap
if ( uu.height + uu.width > imageMaxHeight + imageMaxWidth ) {
if ( uu.height > uu.widt ) {
image.resize ( Jimp.AUTO, imageMaxHeight )
} else {
image.resize ( imageMaxWidth, Jimp.AUTO )
}
}
// to PNG
return image.deflateStrategy ( 2, () => {
return exportImage ( ret.media_type, image )
})
})
//}
//return CallBack ( null, ret )
},
imageSearch: ( ee ) => {
const self = _view.appsManager().appScript()
const errorProcess = ( err ) => {
self.showInputLoading ( false )
self.searchInputText ( '' )
self.errorMessageIndex ( _view.connectInformationMessage.getErrorIndex( err ))
return self.showSearchError ( true )
}
const showItems = ( iResult ) => {
self.showInputLoading ( false )
self.currentlyShowItems ( 2 )
self.returnSearchResultItemsInit ( iResult )
self.imageSearchItemArray ( iResult )
self.searchInputText ( iResult.searchesRelated[0])
self.showResultItems ( self, self.imageSearchItemArray ())
}
if ( !ee || !ee.files || !ee.files.length ) {
return
}
const file = ee.files[0]
if ( !file || !file.type.match ( /^image.(png$|jpg$|jpeg$|gif$)/ )) {
return
}
const reader = new FileReader()
reader.onload = e => {
const rawData = reader.result.toString()
self.showInputLoading ( true )
self.searchInputText (' ')
self.searchItem ( null )
self.searchItemList ([])
return self.getPictureBase64MaxSize_mediaData ( rawData, 1024, 1024, ( err, data ) => {
if ( err ) {
return errorProcess ( err )
}
const uuid = uuid_generate() + '.png'
return _view.keyPairCalss.encrypt ( data.rawData, ( err, textData ) => {
if ( err ) {
return errorProcess ( err )
}
self.initSearchData ( self )
return _view.connectInformationMessage.sockEmit ( 'sendMedia', uuid, textData, err => {
if ( err ) {
return errorProcess ( err )
}
const com: QTGateAPIRequestCommand = {
command: 'CoSearch',
Args: [ 'google', uuid ],
error: null,
subCom: 'imageSearch'
}
return _view.keyPairCalss.emitRequest ( com, ( err, com: QTGateAPIRequestCommand ) => {
if ( err ) {
return errorProcess ( err )
}
if ( !com ) {
return self.loadingGetResponse ( true )
}
if ( com.error === -1 ) {
self.loadingGetResponse ( false )
return self.conetResponse ( true )
}
if ( com.error ) {
return errorProcess ( com.error )
}
_view.CanadaBackground ( false )
self.showMainSearchForm( false )
return showItems ( com.Args.param )
})
})
})
})
}
if ( !_view.CanadaBackground ()) {
_view.CanadaBackground ( true )
}
if ( !self.showMainSearchForm()) {
self.showMainSearchForm( true )
}
return reader.readAsDataURL ( file )
},
imagesResultClick: ( self, index: number, image: string ) => {
const _img = self.searchSimilarImagesList ()[ index ]
const currentElm = $(`#${ _img.id }-1`)
/**
*
* get web side
*
*/
if ( _img.showError()) {
return _img.showError ( false )
}
if ( _img.showImageError ()) {
return _img.showImageError ( false )
}
if ( image === 'link' ) {
if ( _img.showLoading() ) {
return
}
const url = _img.webUrlHref
if ( _img['snapshotData'] ) {
self.showMain ( false )
self.showSnapshop ( true )
self.showSearchSimilarImagesResult ( false )
let y = null
return self.showWebPage ( y = new showWebPageClass ( url, _img['snapshotData'], _img['snapshotUuid'] , () => {
self.showWebPage ( y = null )
self.showMain ( true )
self.showSnapshop ( false )
self.showSearchSimilarImagesResult ( true )
}))
}
const errorProcess = ( err ) => {
_img.errorIndex ( _view.connectInformationMessage.getErrorIndex( err ))
_img.showLoading ( false )
_img.snapshotReady ( false )
_img.loadingGetResponse ( false )
_img.conetResponse ( false )
const currentElm = $(`#${ _img.id }`)
currentElm.popup ({
on: 'click',
inline: true,
onHidden: function () {
_img.showError ( false )
_img.errorIndex ( null )
}
})
return _img.showError ( true )
}
_img.showLoading ( true )
const callBack = ( err?, com?: QTGateAPIRequestCommand ) => {
if ( err ) {
return errorProcess ( err )
}
if ( !com ) {
_img.loadingGetResponse ( true )
return _img.conetResponse ( false )
}
if ( com.error === -1 ) {
_img.loadingGetResponse ( false )
return _img.conetResponse ( true )
}
if ( com.error ) {
return errorProcess ( com.error )
}
const arg: string = com.Args[0]
_img['snapshotUuid'] = arg.split(',')[0].split ('.')[0]
return _view.connectInformationMessage.sockEmit ( 'getFilesFromImap', arg, ( err, buffer: string ) => {
if ( err ) {
return errorProcess ( err )
}
return _view.keyPairCalss.decryptMessageToZipStream ( buffer, ( err, data ) => {
if ( err ) {
return errorProcess ( err )
}
_img.snapshotReady ( true )
_img.showLoading ( false )
_img.loadingGetResponse ( false )
_img.conetResponse ( false )
return _img['snapshotData'] = buffer
})
})
}
const width = $(window).width()
const height = $(window).height()
const com: QTGateAPIRequestCommand = {
command: 'CoSearch',
Args: [ url, width, height ],
error: null,
subCom: 'getSnapshop'
}
return _view.keyPairCalss.emitRequest ( com, callBack )
}
/**
* n['showImageLoading'] = ko.observable ( false )
n['snapshotImageReady'] = ko.observable ( false )
n['loadingImageGetResponse'] = ko.observable ( false )
n['conetImageResponse'] = ko.observable ( false )
n['showImageError'] = ko.observable ( false )
n['imageErrorIndex'] = ko.observable (-1)
*/
if ( image === 'img') {
if ( _img.showImageLoading() ) {
return
}
if ( _img['imgOriginalData'] ) {
const uu = 1
return
}
const errorProcess = ( err ) => {
_img.imageErrorIndex (_view.connectInformationMessage.getErrorIndex( err ))
_img.showImageLoading ( false )
_img.snapshotImageReady ( false )
_img.loadingImageGetResponse ( false )
_img.conetImageResponse ( false )
_img.showImageError ( true )
currentElm.popup ({
inline: true,
onHidden: function () {
_img.showImageError ( false )
}
})
return
}
const callBack = ( err?, com?: QTGateAPIRequestCommand ) => {
if ( err ) {
return errorProcess ( err )
}
if ( !com ) {
_img.loadingGetResponse ( true )
return _img.conetResponse ( false )
}
if ( com.error === -1 ) {
_img.loadingGetResponse ( false )
return _img.conetResponse ( true )
}
if ( com.error ) {
return errorProcess ( com.error )
}
const arg: string = com.Args[0]
_img['snapshotUuid'] = arg.split(',')[0].split ('.')[0]
return _view.connectInformationMessage.sockEmit ( 'getFilesFromImap', arg, ( err, buffer: string ) => {
if ( err ) {
return errorProcess ( err )
}
return _view.keyPairCalss.decryptMessageToZipStream ( buffer, ( err, data ) => {
if ( err ) {
return errorProcess ( err )
}
_img.snapshotReady ( true )
_img.showLoading ( false )
_img.loadingGetResponse ( false )
_img.conetResponse ( false )
return _img['snapshotData'] = buffer
})
})
}
const com: QTGateAPIRequestCommand = {
command: 'CoSearch',
Args: [ _img.imgUrlHref ],
error: null,
subCom: 'getFile'
}
return _view.keyPairCalss.emitRequest ( com, callBack )
setTimeout (() => {
_img.loadingImageGetResponse ( true )
setTimeout (() => {
_img.loadingImageGetResponse ( false )
_img.conetImageResponse ( true )
setTimeout (() => {
_img.loadingImageGetResponse ( false )
_img.conetImageResponse ( false )
_img.snapshotImageReady ( true )
_img.showImageLoading ( false )
}, 1000 )
}, 1000 )
}, 1000 )
_img.showImageLoading ( true )
}
}
}
declare const TimelineMax | the_stack |
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Database from '@ioc:Adonis/Lucid/Database'
import Customer from 'App/Models/Customer'
import CustomerTitle from 'App/Models/CustomerTitle'
import CustomerValidator from 'App/Validators/CustomerValidator'
import { ADDRESS_TYPE } from 'types/customer'
export default class CustomersController {
public async index({ response, requestedCompany, request, bouncer }: HttpContextContract) {
await bouncer.with('CustomerPolicy').authorize('list', requestedCompany!)
const {
page,
descending,
perPage,
sortBy,
id,
first_name,
last_name,
email,
phone_number,
is_corporate,
created_at,
updated_at,
company_name,
company_email,
company_phone,
} = request.qs()
const searchQuery = {
id: id ? id : null,
first_name: first_name ? first_name : null,
last_name: last_name ? last_name : null,
email: email ? email : null,
phone_number: phone_number ? phone_number : null,
is_corporate: is_corporate ? is_corporate : null,
created_at: created_at ? created_at : null,
updated_at: updated_at ? updated_at : null,
company_name: company_name ? company_name : null,
company_email: company_email ? company_email : null,
company_phone: company_phone ? company_phone : null,
}
let subquery = Customer.query()
.select(
'customers.id',
'customers.first_name',
'customers.last_name',
'customers.email',
'customers.phone_number',
'customers.created_at',
'customers.updated_at',
'customers.is_corporate',
'customers.corporate_has_rep',
'customers.company_name',
'customers.company_email',
'customers.company_phone',
'customer_titles.name as title'
)
.select(
Database.rawQuery('COALESCE(customers.company_email, customers.email) AS customer_email')
)
.select(
Database.rawQuery(
'COALESCE(customers.company_phone, customers.phone_number) AS customer_phone'
)
)
.select(
Database.rawQuery(
"COALESCE(customers.company_name, CONCAT(customers.first_name, ' ', customers.last_name)) AS customer_name"
)
)
.where({ company_id: requestedCompany?.id })
.leftJoin('customer_titles', (query) =>
query.on('customer_titles.id', '=', 'customers.customer_title_id')
)
if (sortBy) {
subquery = subquery.orderBy(sortBy, descending === 'true' ? 'desc' : 'asc')
}
if (searchQuery) {
subquery.where((query) => {
for (const param in searchQuery) {
if (Object.prototype.hasOwnProperty.call(searchQuery, param)) {
let value = searchQuery[param]
if (value) {
if (value === 'true') value = true
if (value === 'false') value = false
if (param === 'title') {
query.where('customer_titles.title', value)
} else {
query.where(`customers.${param}`, value)
if (typeof value === 'string') {
query.orWhere(`customers.${param}`, 'like', `%${value}%`)
}
}
}
}
}
})
}
const customers = await subquery.paginate(page ? page : 1, perPage ? perPage : 20)
return response.ok({ data: customers })
}
public async customersForSelect({
response,
requestedCompany,
request,
bouncer,
}: HttpContextContract) {
await bouncer.with('CustomerPolicy').authorize('list', requestedCompany!)
const { query } = request.qs()
const searchedCustomers = await Customer.query()
.select(
'customers.id',
'customers.first_name',
'customers.last_name',
'customers.company_name',
'customers.is_corporate',
'customers.corporate_has_rep'
)
.where({ company_id: requestedCompany?.id })
.where(function (whereQuery) {
/**
* We will use both fulltext search matching and pattern matching
* to return the best results. If complete names are supplied,
* fulltext search will be used. Else pattern matching will
* return a result.
*/
whereQuery
.whereRaw(`customers.first_name LIKE '%${query}%'`)
.orWhereRaw(`customers.middle_name LIKE '%${query}%'`)
.orWhereRaw(`customers.last_name LIKE '%${query}%'`)
.orWhereRaw(`customers.company_name LIKE '%${query}%'`)
})
.orderBy('customers.first_name', 'asc')
const transformedSearchedCustomers = searchedCustomers.map((customer) => {
const serialisedCustomer = customer.serialize()
const isCorporate = Boolean(serialisedCustomer.is_corporate)
const fullName = `${serialisedCustomer.first_name} ${serialisedCustomer.last_name}`
return {
label: isCorporate ? serialisedCustomer.company_name : fullName,
value: serialisedCustomer.id,
}
})
return response.ok({ data: transformedSearchedCustomers })
}
public async store({ response, requestedCompany, request, bouncer }: HttpContextContract) {
const {
title,
first_name,
last_name,
middle_name,
email,
phone_number,
is_corporate,
corporate_has_rep,
company_name,
company_phone,
company_email,
is_billing_shipping_addresses_same,
billing_address,
billing_country,
billing_lga,
billing_postal_code,
billing_state,
shipping_address,
shipping_country,
shipping_lga,
shipping_postal_code,
shipping_state,
} = await request.validate(CustomerValidator)
await bouncer.with('CustomerPolicy').authorize('create', requestedCompany!)
const newCustomer = await requestedCompany?.related('customers').create({
customerTitleId: title,
firstName: first_name,
lastName: last_name,
middleName: middle_name,
email,
phoneNumber: phone_number,
isCorporate: is_corporate,
corporateHasRep: corporate_has_rep,
companyName: company_name,
companyPhone: company_phone,
companyEmail: company_email,
})
const areAddressFieldsSet = (
streetAddress: string | undefined,
city: string | undefined,
countryId: number | undefined,
stateId: number | undefined,
postalCode: string | undefined
) => !!city || !!countryId || !!stateId || !!postalCode || !!streetAddress
if (
is_billing_shipping_addresses_same &&
areAddressFieldsSet(
shipping_address,
shipping_lga,
shipping_country,
shipping_state,
shipping_postal_code
)
) {
const addressTypes: Array<ADDRESS_TYPE> = ['shipping_address', 'billing_address']
for (let i = 0; i < addressTypes.length; i++) {
const addressType = addressTypes[i]
await newCustomer?.related('addresses').create({
addressType,
streetAddress: shipping_address,
city: shipping_lga,
countryId: shipping_country,
stateId: shipping_state,
postalCode: shipping_postal_code,
})
}
} else {
if (
areAddressFieldsSet(
shipping_address,
shipping_lga,
shipping_country,
shipping_state,
shipping_postal_code
)
) {
await newCustomer?.related('addresses').create({
addressType: 'shipping_address',
streetAddress: shipping_address,
city: shipping_lga,
countryId: shipping_country,
stateId: shipping_state,
postalCode: shipping_postal_code,
})
}
if (
areAddressFieldsSet(
billing_address,
billing_lga,
billing_country,
billing_state,
billing_postal_code
)
) {
await newCustomer?.related('addresses').create({
addressType: 'billing_address',
streetAddress: billing_address,
city: billing_lga,
countryId: billing_country,
stateId: billing_state,
postalCode: billing_postal_code,
})
}
}
return response.created({ data: newCustomer?.id })
}
public async show({
response,
requestedCompany,
requestedCustomer,
bouncer,
}: HttpContextContract) {
// Check authorisation
await bouncer
.with('CustomerPolicy')
.authorize('view', requestedCompany ?? null, requestedCustomer!)
await requestedCustomer?.load('title')
return response.ok({ data: requestedCustomer })
}
public async update({
response,
requestedCompany,
requestedCustomer,
request,
bouncer,
}: HttpContextContract) {
const {
title,
first_name,
last_name,
middle_name,
email,
phone_number,
is_corporate,
corporate_has_rep,
company_name,
company_phone,
company_email,
} = await request.validate(CustomerValidator)
await bouncer.with('CustomerPolicy').authorize('edit', requestedCompany!, requestedCustomer!)
requestedCustomer?.merge({
customerTitleId: title,
firstName: first_name,
lastName: last_name,
middleName: middle_name,
email,
phoneNumber: phone_number,
isCorporate: is_corporate,
corporateHasRep: corporate_has_rep,
companyName: company_name,
companyPhone: company_phone,
companyEmail: company_email,
})
await requestedCustomer?.save()
return response.created({ data: requestedCustomer?.id })
}
public async destroy({
request,
response,
requestedCompany,
requestedCustomer,
bouncer,
}: HttpContextContract) {
/**
* This method can be used to delete individual customers or multi-customers
* For multiple customers, we need to check if the user is authorised to delete
* all requested customers. If any check fails, the request will be aborted.
*/
// Check if the body contains an array of requested customers
const { customers } = request.body()
if (customers && Array.isArray(customers)) {
// This is a request to delete multiple customers
await bouncer.with('CustomerPolicy').authorize('massDelete', customers)
for (let i = 0; i < customers.length; i++) {
const customerId = customers[i]
let customer: Customer
try {
customer = await Customer.findOrFail(customerId)
await customer.delete()
} catch (error) {
return response.abort({ message: 'Customer not found' })
}
}
return response.ok({
message: `${
customers.length > 1 ? 'Customers were' : 'Customer was'
} deleted successfully.`,
data: customers,
})
} else {
await bouncer
.with('CustomerPolicy')
.authorize('delete', requestedCompany!, requestedCustomer!)
await requestedCustomer?.delete()
return response.ok({
message: 'Customer was deleted successfully.',
data: requestedCustomer?.id,
})
}
}
public async customerTitlesForSelect({ response }: HttpContextContract) {
const titles = await CustomerTitle.query()
.orderBy('name', 'asc')
.select(...['id', 'name'])
const transformedTitles = titles.map((role) => {
return {
label: role.name,
value: role.id,
}
})
return response.ok({
data: transformedTitles,
})
}
} | the_stack |
describe('Inputs', () => {
before(() => {
cy.visit('/inputs');
cy.injectAxe();
cy.get('.page-loader').should('not.exist', { timeout: 20000 });
});
it('Check A11y', () => {
cy.get('ngx-input').withinEach($el => {
cy.checkA11y($el, {
rules: {
'color-contrast': { enabled: false } // NOTE: to be evaluated by UIUX
}
});
});
});
describe('Text Input', () => {
const defaultText = 'A Value';
beforeEach(() => {
cy.getByName('input1').as('CUT');
});
afterEach(() => {
cy.get('@CUT').ngxSetValue(defaultText);
});
it('has a label', () => {
cy.get('@CUT').ngxFindLabel().should('contain.text', 'Name');
});
it('has no placeholder', () => {
cy.get('@CUT').ngxFindNativeInput().should('have.attr', 'placeholder', '');
});
it('enters and clears text', () => {
const text = 'hello world';
cy.get('@CUT').ngxGetValue().should('equal', defaultText);
cy.get('@CUT').ngxFill(text).ngxGetValue().should('equal', text);
cy.get('@CUT').clear().ngxGetValue().should('equal', '');
});
it('enters and clears text using native elements', () => {
const text = 'hello world';
cy.get('@CUT').ngxFindNativeInput().ngxGetValue().should('equal', defaultText);
cy.get('@CUT').ngxFindNativeInput().ngxFill(text).ngxGetValue().should('equal', text);
cy.get('@CUT').ngxFindNativeInput().clear().ngxGetValue().should('equal', '');
});
it('underlines active input', () => {
cy.get('@CUT').click();
cy.get('@CUT')
.find('.ngx-input-underline .underline-fill')
.invoke('attr', 'style')
.should('contain', 'width: 100%');
});
});
describe('Native Input', () => {
beforeEach(() => {
cy.getByLabel('Text').as('CUT');
});
afterEach(() => {
cy.get('@CUT').ngxSetValue('');
});
it('enters and clears text', () => {
const text = 'hello world';
cy.get('@CUT').ngxGetValue().should('equal', '');
cy.get('@CUT').ngxFill(text);
cy.get('@CUT').ngxGetValue().should('equal', text);
cy.get('@CUT').clear();
cy.get('@CUT').ngxGetValue().should('equal', '');
});
});
describe('Textarea Input', () => {
beforeEach(() => {
cy.getByName('input111').as('CUT');
});
afterEach(() => {
cy.get('@CUT').ngxSetValue('A Value');
});
it('has a label', () => {
cy.get('@CUT').ngxFindLabel().contains('Name');
});
it('has no placeholder', () => {
cy.get('@CUT').ngxFindNativeInput().should('have.attr', 'placeholder', '');
});
it('enters text', () => {
const text = ' hello world';
cy.get('@CUT').ngxFill(text);
cy.get('@CUT').ngxGetValue().should('equal', text);
});
it('underlines active input', () => {
cy.get('@CUT')
.find('.ngx-input-underline .underline-fill')
.should(el => {
expect(el).to.have.attr('style');
expect(Cypress.$(el).attr('style')).to.match(/.*width:\s*0%.*/);
});
// when we click on the input box
// it underlines it
cy.get('@CUT').ngxFindNativeInput().click();
cy.get('@CUT')
.find('.ngx-input-underline .underline-fill')
.should(el => {
expect(el).to.have.attr('style');
expect(Cypress.$(el).attr('style')).to.match(/.*width:\s*100%.*/);
});
});
});
describe('Text Input with placeholder', () => {
beforeEach(() => {
cy.getByPlaceholder('Enter your first and last name').as('CUT');
});
afterEach(() => {
cy.get('@CUT').ngxSetValue('');
});
it('adds a placeholder', () => {
cy.get('@CUT').ngxFindNativeInput().should('have.attr', 'placeholder', 'Enter your first and last name');
});
it('underlines active input', () => {
// reset active input box
cy.focused().blur();
cy.get('@CUT')
.find('.ngx-input-underline .underline-fill')
.should(el => {
expect(el).to.have.attr('style');
expect(Cypress.$(el).attr('style')).to.match(/.*width:\s*0%.*/);
});
// when we click on the input box
// it underlines it
cy.get('@CUT').ngxFindNativeInput().click();
cy.get('@CUT')
.find('.ngx-input-underline .underline-fill')
.should(el => {
expect(el).to.have.attr('style');
expect(Cypress.$(el).attr('style')).to.match(/.*width:\s*100%.*/);
});
});
});
describe('Text Input with prefix and suffix', () => {
beforeEach(() => {
cy.getByLabel('Prefix Suffix Input').as('CUT');
});
afterEach(() => {
cy.get('@CUT').ngxSetValue('');
});
it('has a label', () => {
cy.get('@CUT').ngxFindLabel().should('contain.text', 'Prefix Suffix Input');
});
it('have no placeholder', () => {
cy.get('@CUT').ngxFindNativeInput().should('have.attr', 'placeholder', '');
});
it('adds a prefix', () => {
cy.get('@CUT').find('ngx-input-prefix i').should('have.class', 'icon-add-new');
});
it('adds a suffix', () => {
cy.get('@CUT').should('contain.text', 'Clear');
});
});
describe('Disabled Example', () => {
beforeEach(() => {
cy.getByName('input3').as('CUT');
});
it('has a label', () => {
cy.get('@CUT').ngxFindLabel().should('contain.text', 'Disabled Example');
});
it('has no placeholder', () => {
cy.get('@CUT').ngxFindNativeInput().should('have.attr', 'placeholder', '');
});
it('has a value', () => {
cy.get('@CUT').ngxGetValue().should('equal', 'Disabled value');
});
it('should be disabled', () => {
cy.get('@CUT').ngxFindNativeInput().should('be.disabled');
});
});
describe('Required Example', () => {
beforeEach(() => {
cy.get('ngx-input[name="input4"]').as('CUT');
});
it('has a label with asterisk', () => {
cy.get('@CUT').ngxFindLabel().should('contain.text', 'Required Input Example Of The Day');
// todo: check if the asterisk is in the right place
});
it('has no placeholder', () => {
cy.get('@CUT').ngxFindNativeInput().should('have.attr', 'placeholder', '');
});
it('should be required', () => {
cy.get('@CUT').ngxFindNativeInput().should('have.attr', 'required');
});
});
describe('Default value', () => {
beforeEach(() => {
cy.get('ngx-input[name="input44"]').as('CUT');
});
it('has a label', () => {
cy.get('@CUT').ngxFindLabel().should('contain.text', 'Default value');
});
it('has no placeholder', () => {
cy.get('@CUT').ngxFindNativeInput().should('have.attr', 'placeholder', '');
});
it('should be required', () => {
cy.get('@CUT').ngxGetValue().should('equal', 'Defaulted!');
});
});
describe('Password', () => {
beforeEach(() => {
cy.getByLabel('Password').as('CUT');
});
it('has a label', () => {
cy.get('@CUT').ngxFindLabel().should('contain.text', 'Password');
});
it('has no placeholder', () => {
cy.get('@CUT').ngxFindNativeInput().should('have.attr', 'placeholder', '');
});
it('should have a password ', () => {
cy.get('@CUT').ngxFindNativeInput().first().should('have.attr', 'type', 'password');
});
it('should allow input', () => {
const text = '>vQ9~4W$%ag!ACe$';
cy.get('@CUT').ngxFill(text);
cy.get('@CUT').ngxGetValue().should('equal', text);
});
it('should toggle password', () => {
cy.get('@CUT').ngxFindNativeInput().first().should('have.attr', 'type', 'password');
cy.get('@CUT').find('.ngx-input__password-toggle').click();
cy.get('@CUT').ngxFindNativeInput().first().should('have.attr', 'type', 'text');
});
});
describe('Number', () => {
beforeEach(() => {
cy.getByLabel('Number').as('CUT');
});
it('has a label', () => {
cy.get('@CUT').ngxFindLabel().should('contain', 'Number');
});
it('should allow input', () => {
const text = '42';
cy.get('@CUT').ngxFill(text);
cy.get('@CUT').ngxGetValue().should('equal', text);
});
it('should allow exponential notation input', () => {
const text = '4.1e-2';
cy.get('@CUT').ngxFill(text);
cy.get('@CUT').ngxGetValue().should('equal', text);
});
it('can increment and decrement values using keyboard', () => {
cy.get('@CUT').ngxFill('42');
cy.get('@CUT').ngxGetValue().should('equal', '42');
cy.get('@CUT').type('{downarrow}');
cy.get('@CUT').ngxGetValue().should('equal', '41');
cy.get('@CUT').type('{uparrow}{uparrow}{uparrow}');
cy.get('@CUT').ngxGetValue().should('equal', '44');
});
it('can increment and decrement values using spinner', () => {
cy.get('@CUT').ngxFill('42');
cy.get('@CUT').ngxGetValue().should('equal', '42');
cy.get('@CUT').find('.numeric-spinner__down').click();
cy.get('@CUT').ngxGetValue().should('equal', '41');
cy.get('@CUT').find('.numeric-spinner__up').click().click();
cy.get('@CUT').ngxGetValue().should('equal', '43');
});
it('shows invalid when out of max/min', () => {
cy.getByLabel('Age').as('CUT');
cy.get('@CUT').ngxFill('42');
cy.get('@CUT').should('not.have.class', 'ng-invalid');
cy.get('@CUT').ngxFill('1000');
cy.get('@CUT').should('have.class', 'ng-invalid');
cy.get('@CUT').ngxFill('42');
cy.get('@CUT').should('not.have.class', 'ng-invalid');
cy.get('@CUT').ngxFill('-1');
cy.get('@CUT').should('have.class', 'ng-invalid');
});
});
describe('Unlockable password', () => {
beforeEach(() => {
cy.getByName('input6b').as('CUT');
});
it('has a label', () => {
cy.get('@CUT').ngxFindLabel().contains('Secret');
});
it('should show lock icon when locked', () => {
cy.get('@CUT').find('.ngx-lock').should('exist');
cy.get('@CUT').find('.ngx-eye').should('not.exist');
});
it('should clear the password on unlock', () => {
cy.get('@CUT').find('.ngx-lock').click();
cy.get('@CUT').ngxFindNativeInput().ngxGetValue().should('equal', '');
cy.get('@CUT').ngxFindNativeInput().should('not.be.disabled');
});
it('should show visibility icon when unlocked', () => {
cy.get('@CUT').find('.ngx-lock').should('not.exist');
cy.get('@CUT').find('.ngx-eye').should('exist');
});
});
}); | the_stack |
// Copyright (c) 2015 Vadim Macagon
// MIT License, see LICENSE file for full terms.
export enum TargetStopReason {
/** A breakpoint was hit. */
BreakpointHit,
/** A step instruction finished. */
EndSteppingRange,
/** A step-out instruction finished. */
FunctionFinished,
/** The target finished executing and terminated normally. */
ExitedNormally,
/** The target was signalled. */
SignalReceived,
/** The target encountered an exception (this is LLDB specific). */
ExceptionReceived,
/** Catch-all for any of the other numerous reasons. */
Unrecognized,
/** An inferior terminated because it received a signal. */
ExitedSignalled,
/** An inferior terminated (for some reason, check exitCode for clues). */
Exited
}
export interface IFrameInfoBase {
/** Name of the function corresponding to the frame. */
func?: string;
/** Code address of the frame. */
address: string;
/** Name of the source file corresponding to the frame's code address. */
filename?: string;
/** Full path of the source file corresponding to the frame's code address. */
fullname?: string;
/** Source line corresponding to the frame's code address. */
line?: number;
}
/** Frame-specific information returned by breakpoint and stepping MI commands. */
export interface IFrameInfo extends IFrameInfoBase {
/** Arguments of the function corresponding to the frame. */
args?: any;
}
/** Frame-specific information returned by stack related MI commands. */
export interface IStackFrameInfo extends IFrameInfoBase {
/** Level of the stack frame, zero for the innermost frame. */
level: number;
/** Name of the binary file that corresponds to the frame's code address. */
from?: string;
}
/** Frame-specific information returned by -thread-info MI command. */
export interface IThreadFrameInfo extends IFrameInfoBase {
/** Level of the stack frame, zero for the innermost frame. */
level: number;
/** Arguments of the function corresponding to the frame. */
args?: any;
}
export interface IBreakpointLocationInfo {
/**
* Breakpoint location identifier.
* This will be in the format `%d` if the breakpoint has a single location,
* or `%d.%d` if the breakpoint has multiple locations.
*/
id: string;
isEnabled?: boolean;
/** Address of the breakpoint location as a hexadecimal literal. */
address?: string;
/**
* The name of the function within which the breakpoint location is set.
* If function name is not known then this field will be undefined.
*/
func?: string;
/**
* The name of the source file of the breakpoint location.
* This filename is usually relative to the inferior executable.
* If the source file name is not known this field will be undefined.
*/
filename?: string;
/**
* Absolute path of the source file in which this breakpoint location is set.
* If the source file name is not known this field will be undefined.
*/
fullname?: string;
/**
* The source line number of the breakpoint location.
* If the source line number is not known this field will be undefined.
*/
line?: number;
/**
* If the source file name is not known this field may hold the address of the breakpoint
* location, possibly followed by a symbol name.
*/
at?: string;
}
/** Breakpoint-specific information returned by various MI commands. */
export interface IBreakpointInfo {
/** Breakpoint identifier. */
id: number;
/**
* The type of the breakpoint.
* For regular breakpoints this will be `breakpoint`, other possible values are `catchpoint`,
* `watchpoint`, and possibly other as yet unspecified values.
*/
breakpointType: string;
/** If [[breakpointType]] is `catchpoint` this field will contain the exact type of the catchpoint. */
catchpointType?: string;
/** If `true` the breakpoint will be deleted at the next stop. */
isTemp?: boolean;
isEnabled?: boolean;
/** Locations of the breakpoint, empty if the breakpoint is still pending. */
locations: IBreakpointLocationInfo[];
/** If the breakpoint is pending this field contains the text used by the user to set the breakpoint. */
pending?: string;
/**
* Indicates where the breakpoint's [[condition]] is evaluated.
* The value of this field can be either `"host"`, `"target"`, or `undefined`.
*/
evaluatedBy?: string;
/** For a thread-specific breakpoint this will be the identifier of the thread for which it is set. */
threadId?: number;
/**
* For a conditional breakpoint this is the expression that must evaluate to `true` in order
* for the debugger to stop the inferior when the breakpoint is hit. Note that the condition
* is only checked when [[ignoreCount]] is not greater than zero.
*/
condition?: string;
/**
* Number of times the debugger should let the inferior run when the breakpoint is hit.
*
* Each time the breakpoint is hit the debugger will check if the ignore count is zero, if that's
* the case it will stop the inferior (after checking the condition if one is set), otherwise it
* will simply decrement the ignore count by one and the inferior will continue running.
*/
ignoreCount?: number;
/**
* Number of times the debugger should stop the inferior when the breakpoint is hit.
*
* Each time the breakpoint is hit the debugger will decrement the enable count, after the count
* reaches zero the breakpoint is automatically disabled.
*
* Note that [[ignoreCount]] must be zero before the debugger will start decrementing [[enableCount]].
*/
enableCount?: number;
/** Watchpoint-specific. */
mask?: string;
/** Tracepoint-specific. */
passCount?: number;
/** The breakpoint location originaly specified by the user. */
originalLocation?: string;
/** Number of times the breakpoint has been hit. */
hitCount?: number;
/** Tracepoint-specific, indicates whether the tracepoint is installed or not. */
isInstalled?: boolean;
/** Extra type-dependent data. */
what?: string;
}
export interface IVariableInfo {
/** The variable's name. */
name: string;
/** The variable's value. This can be a multi-line text, e.g. for a function the body of a function. */
value: string;
/** The type of the variable's value. Typically shown in the UI when hovering over the value. */
type?: string;
/** Properties of a variable that can be used to determine how to render the variable in the UI. Format of the string value: TBD. */
kind?: string;
/** Optional evaluatable name of this variable which can be passed to the 'EvaluateRequest' to fetch the variable's value. */
evaluateName?: string;
/** If variablesReference is > 0, the variable is structured and its children can be retrieved by passing variablesReference to the VariablesRequest. */
variablesReference: number;
/** The number of named child variables.
The client can use this optional information to present the children in a paged UI and fetch them in chunks.
*/
namedVariables?: number;
/** The number of indexed child variables.
The client can use this optional information to present the children in a paged UI and fetch them in chunks.
*/
indexedVariables?: number;
}
/** Contains information about the arguments of a stack frame. */
export interface IStackFrameArgsInfo {
/** Index of the frame on the stack, zero for the innermost frame. */
level: number;
/** List of arguments for the frame. */
args: IVariableInfo[];
}
/** Contains information about the arguments and locals of a stack frame. */
export interface IStackFrameVariablesInfo {
args: IVariableInfo[];
locals: IVariableInfo[];
}
/** Indicates how much information should be retrieved when calling
* [[DebugSession.getLocalVariables]].
*/
export enum VariableDetailLevel {
/** Only variable names will be retrieved, not their types or values. */
None = 0, // specifying the value is redundant, but is used here to emphasise its importance
/** Only variable names and values will be retrieved, not their types. */
All = 1,
/**
* The name and type will be retrieved for all variables, however values will only be retrieved
* for simple variable types (not arrays, structures or unions).
*/
Simple = 2
}
/** Contains information about a newly created watch. */
export interface IWatchInfo {
id: string;
childCount: number;
value: string;
expressionType: string;
threadId: number;
isDynamic: boolean;
displayHint: string;
hasMoreChildren: boolean;
}
export interface IWatchChildInfo extends IWatchInfo {
/** The expression the front-end should display to identify this child. */
expression: string;
/** `true` if the watch state is not implicitely updated. */
isFrozen: boolean;
}
/** Contains information about the changes in the state of a watch. */
export interface IWatchUpdateInfo {
/** Unique identifier of the watch whose state changed. */
id: string;
/**
* If the number of children changed this is the updated count,
* otherwise this field is undefined.
*/
childCount?: number;
/** The value of the watch expression after the update. */
value?: string;
/**
* If the type of the watch expression changed this will be the new type,
* otherwise this field is undefined.
*/
expressionType?: string;
/**
* If `true` the watch expression is in-scope and has a valid value after the update.
* If `false' the watch expression is not in-scope and has no valid value, but if [[isObsolete]]
* is likewise `false` then the value may become valid at some point in the future if the watch
* expression comes back into scope.
*/
isInScope: boolean;
/**
* `true` if the value of the watch expression is permanently unavailable, possibly because
* the target has changed or has been recompiled. Obsolete watches should be removed by the
* front-end.
*/
isObsolete: boolean;
/** `true` iff the value if the type of the watch expression has changed. */
hasTypeChanged?: boolean;
/** `true` iff the watch relies on a Python-based visualizer. */
isDynamic?: boolean;
/**
* If `isDynamic` is `true` this field may contain a hint for the front-end on how the value of
* the watch expression should be displayed. Otherwise this field is undefined.
*/
displayHint?: string;
/** `true` iff there are more children outside the update range. */
hasMoreChildren: boolean;
/**
* If `isDynamic` is `true` and new children were added within the update range this will
* be a list of those new children. Otherwise this field is undefined.
*/
newChildren?: string;
}
/** Output format specifiers for watch values. */
export enum WatchFormatSpec {
Binary,
Decimal,
Hexadecimal,
Octal,
/**
* This specifier is used to indicate that one of the other ones should be automatically chosen
* based on the expression type, for example `Decimal` for integers, `Hexadecimal` for pointers.
*/
Default
}
/** A watch may have one or more of these attributes associated with it. */
export enum WatchAttribute {
/** Indicates the watch value can be modified. */
Editable,
/**
* Indicates the watch value can't be modified. This will be the case for any watch with
* children (at least when implemented correctly by the debugger, *cough* not LLDB-MI *cough*).
*/
NonEditable
}
/** Contains the contents of a block of memory from the target process. */
export interface IMemoryBlock {
/** Start address of the memory block (hex literal). */
begin: string;
/** End address of the memory block (hex literal). */
end: string;
/**
* Offset of the memory block (in bytes, as a hex literal) from the start address passed into
* [[DebugSession.readMemory]].
*/
offset: string;
/** Contents of the memory block in hexadecimal. */
contents: string;
}
/** Contains information about an ASM instruction. */
export interface IAsmInstruction {
/** Address at which this instruction was disassembled. */
address: string;
/** Name of the function this instruction came from. */
func: string;
/** Offset of this instruction from the start of `func` (as a decimal). */
offset: number;
/** Text disassembly of this instruction. */
inst: string;
/**
* Raw opcode bytes for this instruction.
* NOTE: This field is currently not filled in by LLDB-MI.
*/
opcodes?: string;
/**
* Size of the raw opcode in bytes.
* NOTE: This field is an LLDB-MI specific extension.
*/
size?: number;
}
/** Contains ASM instructions for a single source line. */
export interface ISourceLineAsm {
/** Source filename from the compilation unit, may be absolute or relative. */
file: string;
/**
* Absolute filename of `file` (with all symbolic links resolved).
* If the source file can't be found this field will populated from the debug information.
* NOTE: This field is currently not filled in by LLDB-MI.
*/
fullname: string;
/** Source line number in `file`. */
line: number;
/** ASM instructions corresponding to `line` in `file`. */
instructions: IAsmInstruction[];
}
/** Output format specifiers for register values. */
export enum RegisterValueFormatSpec {
Binary,
Decimal,
Hexadecimal,
Octal,
Raw,
/**
* This specifier is used to indicate that one of the other ones should be automatically chosen.
*/
Default
}
/** Contains information about a thread. */
export interface IThreadInfo {
/** Identifier used by the debugger to identify the thread. */
id: number;
/** Identifier used by the target to identify the thread. */
targetId: string;
/**
* Thread name.
* The name may originate from the target, the debugger, or may be unknown (in which case this
* field will be `undefined`).
*/
name: string;
/** Stack frame currently being executed in the thread. */
frame: IThreadFrameInfo;
/** `true` if the thread is currently stopped, `false` if it is currently running. */
isStopped: boolean;
/**
* Processor core on which the thread is running.
* The debugger may not always provide a value for this field, in which case it will be `undefined`.
*/
processorCore: string;
/** Extra free-form information about the thread, may be `undefined`. */
details: string;
}
/** Contains information about all the threads in the target. */
export interface IMultiThreadInfo {
/** List of all the threads in the target. */
all: IThreadInfo[];
/** Thread currently selected in the debugger. */
current: IThreadInfo;
} | the_stack |
import 'fake-indexeddb/auto';
import { decodeTime } from 'ulid';
import uuidValidate from 'uuid-validate';
import Observable from 'zen-observable-ts';
import {
DataStore as DataStoreType,
initSchema as initSchemaType,
} from '../src/datastore/datastore';
import { Predicates } from '../src/predicates';
import { ExclusiveStorage as StorageType } from '../src/storage/storage';
import {
NonModelTypeConstructor,
PersistentModel,
PersistentModelConstructor,
} from '../src/types';
import {
Comment,
Model,
Post,
Profile,
Metadata,
User,
testSchema,
pause,
} from './helpers';
let initSchema: typeof initSchemaType;
let DataStore: typeof DataStoreType;
const nameOf = <T>(name: keyof T) => name;
/**
* Does nothing intentionally, we care only about type checking
*/
const expectType: <T>(param: T) => void = () => {};
describe('DataStore observe, unmocked, with fake-indexeddb', () => {
let Comment: PersistentModelConstructor<Comment>;
let Model: PersistentModelConstructor<Model>;
let Post: PersistentModelConstructor<Post>;
beforeEach(async () => {
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
({ Comment, Model, Post } = classes as {
Comment: PersistentModelConstructor<Comment>;
Model: PersistentModelConstructor<Model>;
Post: PersistentModelConstructor<Post>;
});
await DataStore.clear();
});
test('clear without starting', async () => {
await DataStore.save(
new Model({
field1: 'Smurfs',
optionalField1: 'More Smurfs',
dateCreated: new Date().toISOString(),
})
);
expect(await DataStore.query(Model)).toHaveLength(1);
await DataStore.stop();
await DataStore.clear();
expect(await DataStore.query(Model)).toHaveLength(0);
});
test('subscribe to all models', async done => {
try {
const sub = DataStore.observe().subscribe(
({ element, opType, model }) => {
expectType<PersistentModelConstructor<PersistentModel>>(model);
expectType<PersistentModel>(element);
expect(opType).toEqual('INSERT');
expect(element.field1).toEqual('Smurfs');
expect(element.optionalField1).toEqual('More Smurfs');
sub.unsubscribe();
done();
}
);
DataStore.save(
new Model({
field1: 'Smurfs',
optionalField1: 'More Smurfs',
dateCreated: new Date().toISOString(),
})
);
} catch (error) {
done(error);
}
});
test('subscribe to model instance', async done => {
try {
const original = await DataStore.save(
new Model({
field1: 'somevalue',
optionalField1: 'This one should be returned',
dateCreated: new Date().toISOString(),
})
);
const sub = DataStore.observe(original).subscribe(
({ element, opType, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
expect(opType).toEqual('UPDATE');
expect(element.id).toEqual(original.id);
expect(element.field1).toEqual('new field 1 value');
// We expect all fields, including ones that haven't been updated, to be returned:
expect(element.optionalField1).toEqual('This one should be returned');
sub.unsubscribe();
done();
}
);
// decoy
await DataStore.save(
new Model({
field1: "this one shouldn't get through",
dateCreated: new Date().toISOString(),
})
);
await DataStore.save(
Model.copyOf(original, m => (m.field1 = 'new field 1 value'))
);
} catch (error) {
done(error);
}
});
test('subscribe to Model', async done => {
try {
const original = await DataStore.save(
new Model({
field1: 'somevalue',
optionalField1: 'additional value',
dateCreated: new Date().toISOString(),
})
);
const sub = DataStore.observe(Model).subscribe(
({ element, opType, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
expect(opType).toEqual('UPDATE');
expect(element.id).toEqual(original.id);
expect(element.field1).toEqual('new field 1 value');
expect(element.optionalField1).toEqual('additional value');
sub.unsubscribe();
done();
}
);
// decoy
await DataStore.save(
new Post({
title: "This one's a decoy!",
})
);
await DataStore.save(
Model.copyOf(original, m => (m.field1 = 'new field 1 value'))
);
} catch (error) {
done(error);
}
});
test('subscribe with criteria', async done => {
try {
const original = await DataStore.save(
new Model({
field1: 'somevalue',
optionalField1: 'additional value',
dateCreated: new Date().toISOString(),
})
);
const sub = DataStore.observe(Model, m =>
m.field1('contains', 'new field 1')
).subscribe(({ element, opType, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
expect(opType).toEqual('UPDATE');
expect(element.id).toEqual(original.id);
expect(element.field1).toEqual('new field 1 value');
expect(element.optionalField1).toEqual('additional value');
sub.unsubscribe();
done();
});
// decoy
await DataStore.save(
new Model({
field1: "This one's a decoy!",
dateCreated: new Date().toISOString(),
})
);
await DataStore.save(
Model.copyOf(original, m => (m.field1 = 'new field 1 value'))
);
} catch (error) {
done(error);
}
});
test('subscribe with criteria on deletes', async done => {
try {
const original = await DataStore.save(
new Model({
field1: 'somevalue',
optionalField1: 'additional value',
dateCreated: new Date().toISOString(),
})
);
const sub = DataStore.observe(Model, m =>
m.field1('eq', 'somevalue')
).subscribe(({ element, opType, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
expect(opType).toEqual('DELETE');
expect(element.id).toEqual(original.id);
expect(element.field1).toEqual('somevalue');
expect(element.optionalField1).toEqual('additional value');
sub.unsubscribe();
done();
});
// decoy
await DataStore.save(
new Model({
field1: "This one's a decoy!",
dateCreated: new Date().toISOString(),
})
);
await DataStore.delete(original);
} catch (error) {
done(error);
}
});
});
describe('DataStore observeQuery, with fake-indexeddb and fake sync', () => {
//
// ~~~~ OH HEY! ~~~~~
//
// Remember that `observeQuery()` always issues a first snapshot from the data
// already in storage. This is naturally performed async. Because of this,
// if you insert items immediately after `observeQuery()`, some of those items
// MAY show up in the initial snapshot. (Or maybe they won't!)
//
// Many of these tests should therefore include timeouts when adding records.
// These timeouts let `observeQuery()` sneak in and grab its first snapshot
// before those records hit storage, making for predictable tests.
//
// The tests should also account for that initial, empty snapshot.
//
// Remember: Snapshots are cumulative.
//
// And Also: Be careful when saving decoy records! Calling `done()` in a
// subscription body while any `DataStore.save()`'s are outstanding WILL
// result in cryptic errors that surface in subsequent tests!
//
// ("Error: An operation was called on an object on which it is not allowed ...")
//
// ~~~~ OK. Thanks! ~~~~
//
// (That's it)
//
let Comment: PersistentModelConstructor<Comment>;
let Post: PersistentModelConstructor<Post>;
let User: PersistentModelConstructor<User>;
let Profile: PersistentModelConstructor<Profile>;
beforeEach(async () => {
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
({ Comment, Post, User, Profile } = classes as {
Comment: PersistentModelConstructor<Comment>;
Post: PersistentModelConstructor<Post>;
User: PersistentModelConstructor<User>;
Profile: PersistentModelConstructor<Profile>;
});
// This prevents pollution between tests. DataStore may have processes in
// flight that need to settle. If we stampede ahead before we do this,
// we can end up in very goofy states when we try to re-init the schema.
await DataStore.stop();
await DataStore.start();
await DataStore.clear();
// Fully faking or mocking the sync engine would be pretty significant.
// Instead, we're going to be mocking a few sync engine methods we happen know
// `observeQuery()` depends on.
(DataStore as any).sync = {
// default to report that models are NOT synced.
// set to `true` to signal the model is synced.
// `observeQuery()` should finish up after this returns `true`.
getModelSyncedStatus: (model: any) => false,
// not important for this testing. but unsubscribe calls this.
// so, it needs to exist.
unsubscribeConnectivity: () => {},
};
// how many items to accumulate before `observeQuery()` sends the items
// to its subscriber.
(DataStore as any).syncPageSize = 1000;
});
test('publishes preexisting local data immediately', async done => {
try {
for (let i = 0; i < 5; i++) {
await DataStore.save(
new Post({
title: `the post ${i}`,
})
);
}
const sub = DataStore.observeQuery(Post).subscribe(({ items }) => {
expect(items.length).toBe(5);
for (let i = 0; i < 5; i++) {
expect(items[i].title).toEqual(`the post ${i}`);
}
sub.unsubscribe();
done();
});
} catch (error) {
done(error);
}
});
test('publishes data saved after sync', async done => {
try {
const expecteds = [0, 10];
const sub = DataStore.observeQuery(Post).subscribe(({ items }) => {
const expected = expecteds.shift() || 0;
expect(items.length).toBe(expected);
for (let i = 0; i < expected; i++) {
expect(items[i].title).toEqual(`the post ${i}`);
}
if (expecteds.length === 0) {
sub.unsubscribe();
done();
}
});
setTimeout(async () => {
for (let i = 0; i < 10; i++) {
await DataStore.save(
new Post({
title: `the post ${i}`,
})
);
}
}, 100);
} catch (error) {
done(error);
}
});
test('can filter items', async done => {
try {
const expecteds = [0, 5];
const sub = DataStore.observeQuery(Post, p =>
p.title('contains', 'include')
).subscribe(({ items }) => {
const expected = expecteds.shift() || 0;
expect(items.length).toBe(expected);
for (const item of items) {
expect(item.title).toMatch('include');
}
if (expecteds.length === 0) {
sub.unsubscribe();
done();
}
});
setTimeout(async () => {
for (let i = 0; i < 10; i++) {
await DataStore.save(
new Post({
title: `the post ${i} - ${Boolean(i % 2) ? 'include' : 'omit'}`,
})
);
}
}, 1);
} catch (error) {
done(error);
}
});
// Fix for: https://github.com/aws-amplify/amplify-js/issues/9325
test('can remove newly-unmatched items out of the snapshot on subsequent saves', async done => {
try {
// watch for post snapshots.
// the first "real" snapshot should include all five posts with "include"
// in the title. after the update to change ONE of those posts to "omit" instead,
// we should see a snapshot of 4 posts with the updated post removed.
const expecteds = [0, 4, 3];
const sub = DataStore.observeQuery(Post, p =>
p.title('contains', 'include')
).subscribe(async ({ items }) => {
const expected = expecteds.shift() || 0;
expect(items.length).toBe(expected);
for (const item of items) {
expect(item.title).toMatch('include');
}
if (expecteds.length === 1) {
// After the second snapshot arrives, changes a single post from
// "the post # - include"
// to
// "edited post - omit"
// This is intended to trigger a new, after-sync'd snapshot.
// This sanity-checks helps confirms we're testing what we think
// we're testing:
expect(
((DataStore as any).sync as any).getModelSyncedStatus({})
).toBe(true);
await pause(1);
const itemToEdit = (
await DataStore.query(Post, p => p.title('contains', 'include'))
).pop();
await DataStore.save(
Post.copyOf(itemToEdit, draft => {
draft.title = 'second edited post - omit';
})
);
} else if (expecteds.length === 0) {
sub.unsubscribe();
done();
}
});
setTimeout(async () => {
// Creates posts like:
//
// "the post 0 - include"
// "the post 1 - omit"
// "the post 2 - include"
// "the post 3 - omit"
//
// etc.
//
for (let i = 0; i < 10; i++) {
await DataStore.save(
new Post({
title: `the post ${i} - ${Boolean(i % 2) ? 'include' : 'omit'}`,
})
);
}
// Changes a single post from
// "the post # - include"
// to
// "edited post - omit"
await pause(1);
((DataStore as any).sync as any).getModelSyncedStatus = (model: any) =>
true;
// the first edit simulates a quick-turnaround update that gets
// applied while the first snapshot is still being generated
const itemToEdit = (
await DataStore.query(Post, p => p.title('contains', 'include'))
).pop();
await DataStore.save(
Post.copyOf(itemToEdit, draft => {
draft.title = 'first edited post - omit';
})
);
}, 1);
} catch (error) {
done(error);
}
});
test('publishes preexisting local data AND follows up with subsequent saves', done => {
(async () => {
try {
const expecteds = [5, 15];
for (let i = 0; i < 5; i++) {
await DataStore.save(
new Post({
title: `the post ${i}`,
})
);
}
const sub = DataStore.observeQuery(Post).subscribe(
({ items, isSynced }) => {
const expected = expecteds.shift() || 0;
expect(items.length).toBe(expected);
for (let i = 0; i < expected; i++) {
expect(items[i].title).toEqual(`the post ${i}`);
}
if (expecteds.length === 0) {
sub.unsubscribe();
done();
}
}
);
setTimeout(async () => {
for (let i = 5; i < 15; i++) {
await DataStore.save(
new Post({
title: `the post ${i}`,
})
);
}
}, 100);
} catch (error) {
done(error);
}
})();
});
test('removes deleted items from the snapshot', done => {
(async () => {
try {
const expecteds = [5, 4];
for (let i = 0; i < 5; i++) {
await DataStore.save(
new Post({
title: `the post ${i}`,
})
);
}
const sub = DataStore.observeQuery(Post).subscribe(
({ items, isSynced }) => {
const expected = expecteds.shift() || 0;
expect(items.length).toBe(expected);
for (let i = 0; i < expected; i++) {
expect(items[i].title).toContain(`the post`);
}
if (expecteds.length === 0) {
sub.unsubscribe();
done();
}
}
);
setTimeout(async () => {
const itemToDelete = (await DataStore.query(Post)).pop();
await DataStore.delete(itemToDelete);
}, 1);
} catch (error) {
done(error);
}
})();
});
test('removes deleted items from the snapshot with a predicate', done => {
(async () => {
try {
const expecteds = [5, 4];
for (let i = 0; i < 5; i++) {
await DataStore.save(
new Post({
title: `the post ${i}`,
})
);
}
const sub = DataStore.observeQuery(Post, p =>
p.title('beginsWith', 'the post')
).subscribe(({ items, isSynced }) => {
const expected = expecteds.shift() || 0;
expect(items.length).toBe(expected);
for (let i = 0; i < expected; i++) {
expect(items[i].title).toContain(`the post`);
}
if (expecteds.length === 0) {
sub.unsubscribe();
done();
}
});
setTimeout(async () => {
const itemToDelete = (await DataStore.query(Post)).pop();
await DataStore.delete(itemToDelete);
}, 1);
} catch (error) {
done(error);
}
})();
});
test('attaches related belongsTo properties consistently with query() on INSERT', async done => {
try {
const expecteds = [5, 15];
for (let i = 0; i < 5; i++) {
await DataStore.save(
new Comment({
content: `comment content ${i}`,
post: await DataStore.save(
new Post({
title: `new post ${i}`,
})
),
})
);
}
const sub = DataStore.observeQuery(Comment).subscribe(
({ items, isSynced }) => {
const expected = expecteds.shift() || 0;
expect(items.length).toBe(expected);
for (let i = 0; i < expected; i++) {
expect(items[i].content).toEqual(`comment content ${i}`);
expect(items[i].post.title).toEqual(`new post ${i}`);
}
if (expecteds.length === 0) {
sub.unsubscribe();
done();
}
}
);
setTimeout(async () => {
for (let i = 5; i < 15; i++) {
await DataStore.save(
new Comment({
content: `comment content ${i}`,
post: await DataStore.save(
new Post({
title: `new post ${i}`,
})
),
})
);
}
}, 1);
} catch (error) {
done(error);
}
});
test('attaches related hasOne properties consistently with query() on INSERT', async done => {
try {
const expecteds = [5, 15];
for (let i = 0; i < 5; i++) {
await DataStore.save(
new User({
name: `user ${i}`,
profile: await DataStore.save(
new Profile({
firstName: `firstName ${i}`,
lastName: `lastName ${i}`,
})
),
})
);
}
const sub = DataStore.observeQuery(User).subscribe(
({ items, isSynced }) => {
const expected = expecteds.shift() || 0;
expect(items.length).toBe(expected);
for (let i = 0; i < expected; i++) {
expect(items[i].name).toEqual(`user ${i}`);
expect(items[i].profile.firstName).toEqual(`firstName ${i}`);
expect(items[i].profile.lastName).toEqual(`lastName ${i}`);
}
if (expecteds.length === 0) {
sub.unsubscribe();
done();
}
}
);
setTimeout(async () => {
for (let i = 5; i < 15; i++) {
await DataStore.save(
new User({
name: `user ${i}`,
profile: await DataStore.save(
new Profile({
firstName: `firstName ${i}`,
lastName: `lastName ${i}`,
})
),
})
);
}
}, 1);
} catch (error) {
done(error);
}
});
test('attaches related belongsTo properties consistently with query() on UPDATE', async done => {
try {
const expecteds = [
['old post 0', 'old post 1', 'old post 2', 'old post 3', 'old post 4'],
['new post 0', 'new post 1', 'new post 2', 'new post 3', 'new post 4'],
];
for (let i = 0; i < 5; i++) {
await DataStore.save(
new Comment({
content: `comment content ${i}`,
post: await DataStore.save(
new Post({
title: `old post ${i}`,
})
),
})
);
}
const sub = DataStore.observeQuery(Comment).subscribe(
({ items, isSynced }) => {
const expected = expecteds.shift() || [];
expect(items.length).toBe(expected.length);
for (let i = 0; i < expected.length; i++) {
expect(items[i].content).toContain(`comment content ${i}`);
expect(items[i].post.title).toEqual(expected[i]);
}
if (expecteds.length === 0) {
sub.unsubscribe();
done();
}
}
);
setTimeout(async () => {
let postIndex = 0;
const comments = await DataStore.query(Comment);
for (const comment of comments) {
const newPost = await DataStore.save(
new Post({
title: `new post ${postIndex++}`,
})
);
await DataStore.save(
Comment.copyOf(comment, draft => {
draft.content = `updated: ${comment.content}`;
draft.post = newPost;
})
);
}
}, 1);
} catch (error) {
done(error);
}
});
test('attaches related hasOne properties consistently with query() on UPDATE', async done => {
try {
const expecteds = [
[
'first name 0',
'first name 1',
'first name 2',
'first name 3',
'first name 4',
],
[
'new first name 0',
'new first name 1',
'new first name 2',
'new first name 3',
'new first name 4',
],
];
for (let i = 0; i < 5; i++) {
await DataStore.save(
new User({
name: `user ${i}`,
profile: await DataStore.save(
new Profile({
firstName: `first name ${i}`,
lastName: `last name ${i}`,
})
),
})
);
}
const sub = DataStore.observeQuery(User).subscribe(
({ items, isSynced }) => {
const expected = expecteds.shift() || [];
expect(items.length).toBe(expected.length);
for (let i = 0; i < expected.length; i++) {
expect(items[i].name).toContain(`user ${i}`);
expect(items[i].profile.firstName).toEqual(expected[i]);
}
if (expecteds.length === 0) {
sub.unsubscribe();
done();
}
}
);
setTimeout(async () => {
let userIndex = 0;
const users = await DataStore.query(User);
for (const user of users) {
const newProfile = await DataStore.save(
new Profile({
firstName: `new first name ${userIndex++}`,
lastName: `new last name ${userIndex}`,
})
);
await DataStore.save(
User.copyOf(user, draft => {
draft.name = `updated: ${user.name}`;
draft.profile = newProfile;
})
);
}
}, 1);
} catch (error) {
done(error);
}
});
});
describe('DataStore tests', () => {
beforeEach(() => {
jest.resetModules();
jest.doMock('../src/storage/storage', () => {
const mock = jest.fn().mockImplementation(() => ({
init: jest.fn(),
runExclusive: jest.fn(),
query: jest.fn(() => []),
save: jest.fn(() => []),
observe: jest.fn(() => Observable.of()),
}));
(<any>mock).getNamespace = () => ({ models: {} });
return { ExclusiveStorage: mock };
});
({ initSchema, DataStore } = require('../src/datastore/datastore'));
});
test('error on schema not initialized on start', async () => {
const errorLog = jest.spyOn(console, 'error');
const errorRegex = /Schema is not initialized/;
await expect(DataStore.start()).rejects.toThrow(errorRegex);
expect(errorLog).toHaveBeenCalledWith(expect.stringMatching(errorRegex));
});
test('error on schema not initialized on clear', async () => {
const errorLog = jest.spyOn(console, 'error');
const errorRegex = /Schema is not initialized/;
await expect(DataStore.clear()).rejects.toThrow(errorRegex);
expect(errorLog).toHaveBeenCalledWith(expect.stringMatching(errorRegex));
});
describe('initSchema tests', () => {
test('Model class is created', () => {
const classes = initSchema(testSchema());
expect(classes).toHaveProperty('Model');
const { Model } = classes as { Model: PersistentModelConstructor<Model> };
expect(Model).toHaveProperty(
nameOf<PersistentModelConstructor<any>>('copyOf')
);
expect(typeof Model.copyOf).toBe('function');
});
test('Model class can be instantiated', () => {
const { Model } = initSchema(testSchema()) as {
Model: PersistentModelConstructor<Model>;
};
const model = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
});
expect(model).toBeInstanceOf(Model);
expect(model.id).toBeDefined();
// syncable models use uuid v4
expect(uuidValidate(model.id, 4)).toBe(true);
});
test('Non-syncable models get a ulid', () => {
const { LocalModel } = initSchema(testSchema()) as {
LocalModel: PersistentModelConstructor<Model>;
};
const now = Date.now();
const model = new LocalModel({
field1: 'something',
dateCreated: new Date().toISOString(),
});
expect(model).toBeInstanceOf(LocalModel);
expect(model.id).toBeDefined();
const decodedTime = decodeTime(model.id);
const diff = Math.abs(decodedTime - now);
expect(diff).toBeLessThan(1000);
});
test('initSchema is executed only once', () => {
initSchema(testSchema());
const spy = jest.spyOn(console, 'warn');
expect(() => {
initSchema(testSchema());
}).not.toThrow();
expect(spy).toBeCalledWith('The schema has already been initialized');
});
test('Non @model class is created', () => {
const classes = initSchema(testSchema());
expect(classes).toHaveProperty('Metadata');
const { Metadata } = classes;
expect(Metadata).not.toHaveProperty(
nameOf<PersistentModelConstructor<any>>('copyOf')
);
});
test('Non @model class can be instantiated', () => {
const { Metadata } = initSchema(testSchema()) as {
Metadata: NonModelTypeConstructor<Metadata>;
};
const metadata = new Metadata({
author: 'some author',
tags: [],
rewards: [],
penNames: [],
nominations: [],
});
expect(metadata).toBeInstanceOf(Metadata);
expect(metadata).not.toHaveProperty('id');
});
});
describe('Immutability', () => {
test('Field cannot be changed', () => {
const { Model } = initSchema(testSchema()) as {
Model: PersistentModelConstructor<Model>;
};
const model = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
});
expect(() => {
(<any>model).field1 = 'edit';
}).toThrowError("Cannot assign to read only property 'field1' of object");
});
test('Model can be copied+edited by creating an edited copy', () => {
const { Model } = initSchema(testSchema()) as {
Model: PersistentModelConstructor<Model>;
};
const model1 = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
});
const model2 = Model.copyOf(model1, draft => {
draft.field1 = 'edited';
});
expect(model1).not.toBe(model2);
// ID should be kept the same
expect(model1.id).toBe(model2.id);
expect(model1.field1).toBe('something');
expect(model2.field1).toBe('edited');
});
test('Id cannot be changed inside copyOf', () => {
const { Model } = initSchema(testSchema()) as {
Model: PersistentModelConstructor<Model>;
};
const model1 = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
});
const model2 = Model.copyOf(model1, draft => {
(<any>draft).id = 'a-new-id';
});
// ID should be kept the same
expect(model1.id).toBe(model2.id);
});
test('Optional field can be initialized with undefined', () => {
const { Model } = initSchema(testSchema()) as {
Model: PersistentModelConstructor<Model>;
};
const model1 = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
optionalField1: undefined,
});
expect(model1.optionalField1).toBeUndefined();
});
test('Optional field can be initialized with null', () => {
const { Model } = initSchema(testSchema()) as {
Model: PersistentModelConstructor<Model>;
};
const model1 = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
optionalField1: null,
});
expect(model1.optionalField1).toBeNull();
});
test('Optional field can be changed to undefined inside copyOf', () => {
const { Model } = initSchema(testSchema()) as {
Model: PersistentModelConstructor<Model>;
};
const model1 = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
optionalField1: 'something-else',
});
const model2 = Model.copyOf(model1, draft => {
(<any>draft).optionalField1 = undefined;
});
// ID should be kept the same
expect(model1.id).toBe(model2.id);
expect(model1.optionalField1).toBe('something-else');
expect(model2.optionalField1).toBeUndefined();
});
test('Optional field can be set to null inside copyOf', () => {
const { Model } = initSchema(testSchema()) as {
Model: PersistentModelConstructor<Model>;
};
const model1 = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
});
const model2 = Model.copyOf(model1, draft => {
(<any>draft).optionalField1 = null;
});
// ID should be kept the same
expect(model1.id).toBe(model2.id);
expect(model1.optionalField1).toBeUndefined();
expect(model2.optionalField1).toBeNull();
});
test('multiple copyOf operations carry all changes on save', async () => {
let model: Model;
const save = jest.fn(() => [model]);
const query = jest.fn(() => [model]);
jest.resetModules();
jest.doMock('../src/storage/storage', () => {
const mock = jest.fn().mockImplementation(() => {
const _mock = {
init: jest.fn(),
save,
query,
runExclusive: jest.fn(fn => fn.bind(this, _mock)()),
};
return _mock;
});
(<any>mock).getNamespace = () => ({ models: {} });
return { ExclusiveStorage: mock };
});
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
const { Model } = classes as { Model: PersistentModelConstructor<Model> };
const model1 = new Model({
dateCreated: new Date().toISOString(),
field1: 'original',
optionalField1: 'original',
});
model = model1;
await DataStore.save(model1);
const model2 = Model.copyOf(model1, draft => {
(<any>draft).field1 = 'field1Change1';
(<any>draft).optionalField1 = 'optionalField1Change1';
});
const model3 = Model.copyOf(model2, draft => {
(<any>draft).field1 = 'field1Change2';
});
model = model3;
await DataStore.save(model3);
const [settingsSave, saveOriginalModel, saveModel3] = <any>(
save.mock.calls
);
const [_model, _condition, _mutator, [patches]] = saveModel3;
const expectedPatches = [
{
op: 'replace',
path: ['field1'],
value: 'field1Change2',
},
{
op: 'replace',
path: ['optionalField1'],
value: 'optionalField1Change1',
},
];
expect(patches).toMatchObject(expectedPatches);
});
test('Non @model - Field cannot be changed', () => {
const { Metadata } = initSchema(testSchema()) as {
Metadata: NonModelTypeConstructor<Metadata>;
};
const nonModel = new Metadata({
author: 'something',
rewards: [],
penNames: [],
nominations: [],
});
expect(() => {
(<any>nonModel).author = 'edit';
}).toThrowError("Cannot assign to read only property 'author' of object");
});
});
describe('Initialization', () => {
test('start is called only once', async () => {
const storage: StorageType =
require('../src/storage/storage').ExclusiveStorage;
const classes = initSchema(testSchema());
const { Model } = classes as { Model: PersistentModelConstructor<Model> };
const promises = [
DataStore.query(Model),
DataStore.query(Model),
DataStore.query(Model),
DataStore.query(Model),
];
await Promise.all(promises);
expect(storage).toHaveBeenCalledTimes(1);
});
test('It is initialized when observing (no query)', async () => {
const storage: StorageType =
require('../src/storage/storage').ExclusiveStorage;
const classes = initSchema(testSchema());
const { Model } = classes as { Model: PersistentModelConstructor<Model> };
DataStore.observe(Model).subscribe(jest.fn());
expect(storage).toHaveBeenCalledTimes(1);
});
});
describe('Basic operations', () => {
let Model: PersistentModelConstructor<Model>;
let Metadata: NonModelTypeConstructor<Metadata>;
beforeEach(() => {
jest.resetModules();
jest.doMock('../src/storage/storage', () => {
const mock = jest.fn().mockImplementation(() => ({
init: jest.fn(),
runExclusive: jest.fn(() => []),
query: jest.fn(() => []),
observe: jest.fn(() => Observable.from([])),
}));
(<any>mock).getNamespace = () => ({ models: {} });
return { ExclusiveStorage: mock };
});
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
({ Model, Metadata } = classes as {
Model: PersistentModelConstructor<Model>;
Metadata: NonModelTypeConstructor<Metadata>;
});
});
test('Save returns the saved model', async () => {
let model: Model;
const save = jest.fn(() => [model]);
const query = jest.fn(() => [model]);
jest.resetModules();
jest.doMock('../src/storage/storage', () => {
const mock = jest.fn().mockImplementation(() => {
const _mock = {
init: jest.fn(),
save,
query,
runExclusive: jest.fn(fn => fn.bind(this, _mock)()),
};
return _mock;
});
(<any>mock).getNamespace = () => ({ models: {} });
return { ExclusiveStorage: mock };
});
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
const { Model } = classes as { Model: PersistentModelConstructor<Model> };
model = new Model({
field1: 'Some value',
dateCreated: new Date().toISOString(),
});
const result = await DataStore.save(model);
const [settingsSave, modelCall] = <any>save.mock.calls;
const [_model, _condition, _mutator, patches] = modelCall;
expect(result).toMatchObject(model);
expect(patches).toBeUndefined();
});
test('Save returns the updated model and patches', async () => {
let model: Model;
const save = jest.fn(() => [model]);
const query = jest.fn(() => [model]);
jest.resetModules();
jest.doMock('../src/storage/storage', () => {
const mock = jest.fn().mockImplementation(() => {
const _mock = {
init: jest.fn(),
save,
query,
runExclusive: jest.fn(fn => fn.bind(this, _mock)()),
};
return _mock;
});
(<any>mock).getNamespace = () => ({ models: {} });
return { ExclusiveStorage: mock };
});
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
const { Model } = classes as { Model: PersistentModelConstructor<Model> };
model = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
});
await DataStore.save(model);
model = Model.copyOf(model, draft => {
draft.field1 = 'edited';
});
const result = await DataStore.save(model);
const [settingsSave, modelSave, modelUpdate] = <any>save.mock.calls;
const [_model, _condition, _mutator, [patches]] = modelUpdate;
const expectedPatches = [
{ op: 'replace', path: ['field1'], value: 'edited' },
];
expect(result).toMatchObject(model);
expect(patches).toMatchObject(expectedPatches);
});
test('Save returns the updated model and patches - list field', async () => {
let model: Model;
const save = jest.fn(() => [model]);
const query = jest.fn(() => [model]);
jest.resetModules();
jest.doMock('../src/storage/storage', () => {
const mock = jest.fn().mockImplementation(() => {
const _mock = {
init: jest.fn(),
save,
query,
runExclusive: jest.fn(fn => fn.bind(this, _mock)()),
};
return _mock;
});
(<any>mock).getNamespace = () => ({ models: {} });
return { ExclusiveStorage: mock };
});
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
const { Model } = classes as { Model: PersistentModelConstructor<Model> };
model = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
emails: ['john@doe.com', 'jane@doe.com'],
});
await DataStore.save(model);
model = Model.copyOf(model, draft => {
draft.emails = [...draft.emails, 'joe@doe.com'];
});
let result = await DataStore.save(model);
expect(result).toMatchObject(model);
model = Model.copyOf(model, draft => {
draft.emails.push('joe@doe.com');
});
result = await DataStore.save(model);
expect(result).toMatchObject(model);
const [settingsSave, modelSave, modelUpdate, modelUpdate2] = <any>(
save.mock.calls
);
const [_model, _condition, _mutator, [patches]] = modelUpdate;
const [_model2, _condition2, _mutator2, [patches2]] = modelUpdate2;
const expectedPatches = [
{
op: 'replace',
path: ['emails'],
value: ['john@doe.com', 'jane@doe.com', 'joe@doe.com'],
},
];
const expectedPatches2 = [
{
op: 'replace',
path: ['emails'],
value: ['john@doe.com', 'jane@doe.com', 'joe@doe.com', 'joe@doe.com'],
},
];
expect(patches).toMatchObject(expectedPatches);
expect(patches2).toMatchObject(expectedPatches2);
});
test('Read-only fields cannot be overwritten', async () => {
let model: Model;
const save = jest.fn(() => [model]);
const query = jest.fn(() => [model]);
jest.resetModules();
jest.doMock('../src/storage/storage', () => {
const mock = jest.fn().mockImplementation(() => {
const _mock = {
init: jest.fn(),
save,
query,
runExclusive: jest.fn(fn => fn.bind(this, _mock)()),
};
return _mock;
});
(<any>mock).getNamespace = () => ({ models: {} });
return { ExclusiveStorage: mock };
});
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
const { Model } = classes as { Model: PersistentModelConstructor<Model> };
expect(() => {
new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
createdAt: '2021-06-03T20:56:23.201Z',
} as any);
}).toThrow('createdAt is read-only.');
model = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
});
expect(() => {
Model.copyOf(model, draft => {
(draft as any).createdAt = '2021-06-03T20:56:23.201Z';
});
}).toThrow('createdAt is read-only.');
expect(() => {
Model.copyOf(model, draft => {
(draft as any).updatedAt = '2021-06-03T20:56:23.201Z';
});
}).toThrow('updatedAt is read-only.');
});
test('Instantiation validations', async () => {
expect(() => {
new Model({
field1: undefined,
dateCreated: new Date().toISOString(),
});
}).toThrowError('Field field1 is required');
expect(() => {
new Model({
field1: null,
dateCreated: new Date().toISOString(),
});
}).toThrowError('Field field1 is required');
expect(() => {
new Model({
field1: <any>1234,
dateCreated: new Date().toISOString(),
});
}).toThrowError(
'Field field1 should be of type string, number received. 1234'
);
expect(() => {
new Model({
field1: 'someField',
dateCreated: 'not-a-date',
});
}).toThrowError(
'Field dateCreated should be of type AWSDateTime, validation failed. not-a-date'
);
expect(
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
tags: undefined,
rewards: [],
penNames: [],
nominations: [],
}),
}).metadata.tags
).toBeUndefined();
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
tags: undefined,
rewards: [null],
penNames: [],
nominations: [],
}),
});
}).toThrowError(
'All elements in the rewards array should be of type string, [null] received. '
);
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
emails: null,
ips: null,
});
}).not.toThrow();
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
emails: [null],
});
}).toThrowError(
'All elements in the emails array should be of type string, [null] received. '
);
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
ips: [null],
});
}).not.toThrow();
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
ips: ['1.1.1.1'],
});
}).not.toThrow();
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
ips: ['not.an.ip'],
});
}).toThrowError(
`All elements in the ips array should be of type AWSIPAddress, validation failed for one or more elements. not.an.ip`
);
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
ips: ['1.1.1.1', 'not.an.ip'],
});
}).toThrowError(
`All elements in the ips array should be of type AWSIPAddress, validation failed for one or more elements. 1.1.1.1,not.an.ip`
);
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
emails: ['test@example.com'],
});
}).not.toThrow();
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
emails: [],
ips: [],
});
}).not.toThrow();
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
emails: ['not-an-email'],
});
}).toThrowError(
'All elements in the emails array should be of type AWSEmail, validation failed for one or more elements. not-an-email'
);
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
ips: ['not-an-ip'],
});
}).toThrowError(
'All elements in the ips array should be of type AWSIPAddress, validation failed for one or more elements. not-an-ip'
);
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
tags: undefined,
rewards: [],
penNames: [],
nominations: null,
}),
});
}).toThrowError('Field nominations is required');
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
tags: undefined,
rewards: [],
penNames: [undefined],
nominations: [],
}),
});
}).toThrowError(
'All elements in the penNames array should be of type string, [undefined] received. '
);
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
tags: [<any>1234],
rewards: [],
penNames: [],
nominations: [],
}),
});
}).toThrowError(
'All elements in the tags array should be of type string | null | undefined, [number] received. 1234'
);
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
rewards: [],
penNames: [],
nominations: [],
misc: [null],
}),
});
}).not.toThrow();
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
rewards: [],
penNames: [],
nominations: [],
misc: [undefined],
}),
});
}).not.toThrow();
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
rewards: [],
penNames: [],
nominations: [],
misc: [undefined, null],
}),
});
}).not.toThrow();
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
rewards: [],
penNames: [],
nominations: [],
misc: [null, 'ok'],
}),
});
}).not.toThrow();
expect(() => {
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
rewards: [],
penNames: [],
nominations: [],
misc: [null, <any>123],
}),
});
}).toThrowError(
'All elements in the misc array should be of type string | null | undefined, [null,number] received. ,123'
);
expect(
new Model(<any>{ extraAttribute: 'some value', field1: 'some value' })
).toHaveProperty('extraAttribute');
expect(() => {
Model.copyOf(<any>undefined, d => d);
}).toThrow('The source object is not a valid model');
expect(() => {
const source = new Model({
field1: 'something',
dateCreated: new Date().toISOString(),
});
Model.copyOf(source, d => (d.field1 = <any>1234));
}).toThrow(
'Field field1 should be of type string, number received. 1234'
);
});
test('Delete params', async () => {
await expect(DataStore.delete(<any>undefined)).rejects.toThrow(
'Model or Model Constructor required'
);
await expect(DataStore.delete(<any>Model)).rejects.toThrow(
'Id to delete or criteria required. Do you want to delete all? Pass Predicates.ALL'
);
await expect(DataStore.delete(Model, <any>(() => {}))).rejects.toThrow(
'Criteria required. Do you want to delete all? Pass Predicates.ALL'
);
await expect(DataStore.delete(Model, <any>(() => {}))).rejects.toThrow(
'Criteria required. Do you want to delete all? Pass Predicates.ALL'
);
await expect(DataStore.delete(<any>{})).rejects.toThrow(
'Object is not an instance of a valid model'
);
await expect(
DataStore.delete(
new Model({
field1: 'somevalue',
dateCreated: new Date().toISOString(),
}),
<any>{}
)
).rejects.toThrow('Invalid criteria');
});
test('Delete many returns many', async () => {
const models: Model[] = [];
const save = jest.fn(model => {
model instanceof Model && models.push(model);
});
const query = jest.fn(() => models);
const _delete = jest.fn(() => [models, models]);
jest.resetModules();
jest.doMock('../src/storage/storage', () => {
const mock = jest.fn().mockImplementation(() => {
const _mock = {
init: jest.fn(),
save,
query,
delete: _delete,
runExclusive: jest.fn(fn => fn.bind(this, _mock)()),
};
return _mock;
});
(<any>mock).getNamespace = () => ({ models: {} });
return { ExclusiveStorage: mock };
});
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
const { Model } = classes as {
Model: PersistentModelConstructor<Model>;
};
for (let i = 0; i < 10; i++) {
await DataStore.save(
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author ' + i,
rewards: [],
penNames: [],
nominations: [],
misc: [null, 'ok'],
}),
})
);
}
const deleted = await DataStore.delete(Model, m =>
m.field1('eq', 'someField')
);
expect(deleted.length).toEqual(10);
deleted.forEach(deletedItem => {
expect(deletedItem.field1).toEqual('someField');
});
});
test('Delete one returns one', async () => {
let model: Model;
const save = jest.fn(saved => (model = saved));
const query = jest.fn(() => [model]);
const _delete = jest.fn(() => [[model], [model]]);
jest.resetModules();
jest.doMock('../src/storage/storage', () => {
const mock = jest.fn().mockImplementation(() => {
const _mock = {
init: jest.fn(),
save,
query,
delete: _delete,
runExclusive: jest.fn(fn => fn.bind(this, _mock)()),
};
return _mock;
});
(<any>mock).getNamespace = () => ({ models: {} });
return { ExclusiveStorage: mock };
});
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
const { Model } = classes as {
Model: PersistentModelConstructor<Model>;
};
const saved = await DataStore.save(
new Model({
field1: 'someField',
dateCreated: new Date().toISOString(),
metadata: new Metadata({
author: 'Some author',
rewards: [],
penNames: [],
nominations: [],
misc: [null, 'ok'],
}),
})
);
const deleted: Model[] = await DataStore.delete(Model, saved.id);
expect(deleted.length).toEqual(1);
expect(deleted[0]).toEqual(model);
});
test('Query params', async () => {
await expect(DataStore.query(<any>undefined)).rejects.toThrow(
'Constructor is not for a valid model'
);
await expect(DataStore.query(<any>undefined)).rejects.toThrow(
'Constructor is not for a valid model'
);
await expect(
DataStore.query(Model, <any>'someid', { page: 0 })
).rejects.toThrow('Limit is required when requesting a page');
await expect(
DataStore.query(Model, <any>'someid', { page: <any>'a', limit: 10 })
).rejects.toThrow('Page should be a number');
await expect(
DataStore.query(Model, <any>'someid', { page: -1, limit: 10 })
).rejects.toThrow("Page can't be negative");
await expect(
DataStore.query(Model, <any>'someid', { page: 0, limit: <any>'avalue' })
).rejects.toThrow('Limit should be a number');
await expect(
DataStore.query(Model, <any>'someid', { page: 0, limit: -1 })
).rejects.toThrow("Limit can't be negative");
});
});
test("non-@models can't be saved", async () => {
const { Metadata } = initSchema(testSchema()) as {
Metadata: NonModelTypeConstructor<Metadata>;
};
const metadata = new Metadata({
author: 'some author',
tags: [],
rewards: [],
penNames: [],
nominations: [],
});
await expect(DataStore.save(<any>metadata)).rejects.toThrow(
'Object is not an instance of a valid model'
);
});
describe('Type definitions', () => {
let Model: PersistentModelConstructor<Model>;
beforeEach(() => {
let model: Model;
jest.resetModules();
jest.doMock('../src/storage/storage', () => {
const mock = jest.fn().mockImplementation(() => ({
init: jest.fn(),
runExclusive: jest.fn(() => [model]),
query: jest.fn(() => [model]),
observe: jest.fn(() => Observable.from([])),
}));
(<any>mock).getNamespace = () => ({ models: {} });
return { ExclusiveStorage: mock };
});
({ initSchema, DataStore } = require('../src/datastore/datastore'));
const classes = initSchema(testSchema());
({ Model } = classes as { Model: PersistentModelConstructor<Model> });
model = new Model({
field1: 'Some value',
dateCreated: new Date().toISOString(),
});
});
describe('Query', () => {
test('all', async () => {
const allModels = await DataStore.query(Model);
expectType<Model[]>(allModels);
const [one] = allModels;
expect(one.field1).toBeDefined();
expect(one).toBeInstanceOf(Model);
});
test('one by id', async () => {
const oneModelById = await DataStore.query(Model, 'someid');
expectType<Model>(oneModelById);
expect(oneModelById.field1).toBeDefined();
expect(oneModelById).toBeInstanceOf(Model);
});
test('with criteria', async () => {
const multiModelWithCriteria = await DataStore.query(Model, c =>
c.field1('contains', 'something')
);
expectType<Model[]>(multiModelWithCriteria);
const [one] = multiModelWithCriteria;
expect(one.field1).toBeDefined();
expect(one).toBeInstanceOf(Model);
});
test('with pagination', async () => {
const allModelsPaginated = await DataStore.query(
Model,
Predicates.ALL,
{ page: 0, limit: 20 }
);
expectType<Model[]>(allModelsPaginated);
const [one] = allModelsPaginated;
expect(one.field1).toBeDefined();
expect(one).toBeInstanceOf(Model);
});
});
describe('Query with generic type', () => {
test('all', async () => {
const allModels = await DataStore.query<Model>(Model);
expectType<Model[]>(allModels);
const [one] = allModels;
expect(one.field1).toBeDefined();
expect(one).toBeInstanceOf(Model);
});
test('one by id', async () => {
const oneModelById = await DataStore.query<Model>(Model, 'someid');
expectType<Model>(oneModelById);
expect(oneModelById.field1).toBeDefined();
expect(oneModelById).toBeInstanceOf(Model);
});
test('with criteria', async () => {
const multiModelWithCriteria = await DataStore.query<Model>(Model, c =>
c.field1('contains', 'something')
);
expectType<Model[]>(multiModelWithCriteria);
const [one] = multiModelWithCriteria;
expect(one.field1).toBeDefined();
expect(one).toBeInstanceOf(Model);
});
test('with pagination', async () => {
const allModelsPaginated = await DataStore.query<Model>(
Model,
Predicates.ALL,
{ page: 0, limit: 20 }
);
expectType<Model[]>(allModelsPaginated);
const [one] = allModelsPaginated;
expect(one.field1).toBeDefined();
expect(one).toBeInstanceOf(Model);
});
});
describe('Observe', () => {
test('subscribe to all models', async () => {
DataStore.observe().subscribe(({ element, model }) => {
expectType<PersistentModelConstructor<PersistentModel>>(model);
expectType<PersistentModel>(element);
});
});
test('subscribe to model instance', async () => {
const model = new Model({
field1: 'somevalue',
dateCreated: new Date().toISOString(),
});
DataStore.observe(model).subscribe(({ element, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
});
});
test('subscribe to model', async () => {
DataStore.observe(Model).subscribe(({ element, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
});
});
test('subscribe to model instance by id', async () => {
DataStore.observe(Model, 'some id').subscribe(({ element, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
});
});
test('subscribe to model with criteria', async () => {
DataStore.observe(Model, c => c.field1('ne', 'somevalue')).subscribe(
({ element, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
}
);
});
});
describe('Observe with generic type', () => {
test('subscribe to model instance', async () => {
const model = new Model({
field1: 'somevalue',
dateCreated: new Date().toISOString(),
});
DataStore.observe<Model>(model).subscribe(({ element, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
});
});
test('subscribe to model', async () => {
DataStore.observe<Model>(Model).subscribe(({ element, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
});
});
test('subscribe to model instance by id', async () => {
DataStore.observe<Model>(Model, 'some id').subscribe(
({ element, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
}
);
});
test('subscribe to model with criteria', async () => {
DataStore.observe<Model>(Model, c =>
c.field1('ne', 'somevalue')
).subscribe(({ element, model }) => {
expectType<PersistentModelConstructor<Model>>(model);
expectType<Model>(element);
});
});
});
});
}); | the_stack |
export type rolesValueItemType = {
hidden: number,
icon?: string,
id: number,
level: number,
name: string,
parentId: number,
sort?: number,
title?: string,
}
export type rolesType = {
[s: string]: rolesValueItemType[]
}
const roles: rolesType = {
admin: [
{
hidden: 1,
icon: "vitezujian",
id: 1,
level: 0,
name: "modules",
parentId: 0,
sort: 997,
title: "组件列表",
},
{
hidden: 1,
icon: "viteyonghuliebiao",
id: 18,
level: 1,
name: "form",
parentId: 1,
sort: 997,
title: "表单",
},
{
hidden: 1,
icon: "viteZJ-biaoge",
id: 11,
level: 1,
name: "table",
parentId: 1,
sort: 997,
title: "表格",
},
{
hidden: 1,
icon: "vitequanping",
id: 19,
level: 1,
name: "export",
parentId: 1,
sort: 997,
title: "导出表格",
},
{
hidden: 1,
icon: "viteZJ-fuwenben",
id: 12,
level: 1,
name: "richText",
parentId: 1,
sort: 997,
title: "富文本",
},
{
hidden: 1,
icon: "viteZJ-shangchuan",
id: 13,
level: 1,
name: "upload",
parentId: 1,
sort: 997,
title: "上传文件",
},
{
hidden: 1,
icon: "viteviteZJ-ditu",
id: 14,
level: 1,
name: "map",
parentId: 1,
sort: 997,
title: "地图",
},
{
hidden: 1,
icon: "viteantv",
id: 15,
level: 1,
name: "antv-x6",
parentId: 1,
sort: 997,
title: "antv-x6",
},
{
hidden: 1,
icon: "vitei",
id: 16,
level: 1,
name: "icon",
parentId: 1,
sort: 997,
title: "图标",
},
{
hidden: 1,
icon: "vitesign",
id: 17,
level: 1,
name: "sign",
parentId: 1,
sort: 997,
title: "签名",
},
{
hidden: 1,
icon: "vitetubiao",
id: 2,
level: 0,
name: "eCharts",
parentId: 0,
sort: 997,
title: "图表",
},
{
hidden: 1,
icon: "vitezhexiantu",
id: 21,
level: 1,
name: "eChartLine",
parentId: 2,
sort: 997,
title: "折线图",
},
{
hidden: 1,
icon: "vitezhuzhuangtu",
id: 22,
level: 1,
name: "eChartPillar",
parentId: 2,
sort: 997,
title: "饼状图",
},
{
hidden: 1,
icon: "vitebingzhuangtu",
id: 23,
level: 1,
name: "eChartCake",
parentId: 2,
sort: 997,
title: "柱状图",
},
{
hidden: 1,
icon: "vitebullseye",
id: 3,
level: 0,
name: "log",
parentId: 0,
sort: 997,
title: "日志",
},
{
hidden: 1,
icon: "vitebug",
id: 31,
level: 1,
name: "error-log",
parentId: 3,
sort: 997,
title: "错误日志",
},
{
hidden: 1,
icon: "viteAPI",
id: 32,
level: 1,
name: "ajax-log",
parentId: 3,
sort: 997,
title: "ajax 错误",
},
{
hidden: 1,
icon: "viteyumaobi",
id: 32,
level: 1,
name: "add-log",
parentId: 3,
sort: 997,
title: "添加日志",
},
{
hidden: 1,
icon: "viteiframe",
id: 4,
level: 0,
name: "iframe",
parentId: 0,
sort: 997,
title: "内嵌页面",
},
{
hidden: 1,
icon: "viteiframe",
id: 41,
level: 1,
name: "iframe-",
parentId: 4,
sort: 997,
title: "内嵌",
},
{
hidden: 1,
icon: "vitelianjie",
id: 5,
level: 0,
name: "interlink",
parentId: 0,
sort: 997,
title: "外链",
},
{
hidden: 1,
icon: "vitelianjie",
id: 51,
level: 1,
name: "link",
parentId: 5,
sort: 997,
title: "外链",
},
{
hidden: 1,
icon: "vitemarkdown",
id: 6,
level: 0,
name: "markDown",
parentId: 0,
sort: 997,
title: "markdown",
},
{
hidden: 1,
icon: "vitemarkdown",
id: 61,
level: 1,
name: "markDownEditor",
parentId: 6,
sort: 997,
title: "markdown",
},
{
hidden: 1,
icon: "viteyanjing",
id: 62,
level: 1,
name: "markDownPreview",
parentId: 6,
sort: 997,
title: "markdown预览",
},
{
hidden: 1,
icon: "vitedirective",
id: 7,
level: 0,
name: "directives",
parentId: 0,
sort: 997,
title: "指令",
},
{
hidden: 1,
icon: "vitenumber",
id: 71,
level: 1,
name: "number-directive",
parentId: 7,
sort: 997,
title: "数字指令",
},
{
hidden: 1,
icon: "vitepress-key",
id: 72,
level: 1,
name: "press-key-directive",
parentId: 7,
sort: 997,
title: "按键指令",
},
{
hidden: 1,
icon: "vitethrottle",
id: 73,
level: 1,
name: "debounce-throttle",
parentId: 7,
sort: 997,
title: "防抖节流指令",
},
{
hidden: 1,
icon: "vitejiaose",
id: 74,
level: 1,
name: "demo-directive",
parentId: 7,
sort: 9,
title: "权限演示",
},
{
hidden: 1,
icon: "vitecopy",
id: 75,
level: 1,
name: "copy-directive",
parentId: 7,
sort: 9,
title: "复制文本指令",
},
// 多级路由
{
hidden: 1,
icon: "viteroute",
id: 8,
level: 0,
name: "much-router",
parentId: 0,
sort: 997,
title: "嵌套路由",
},
{
hidden: 1,
icon: "viteantv",
id: 81,
level: 1,
name: "much-menu-one",
parentId: 8,
sort: 997,
title: "二级菜单(一)",
},
{
hidden: 1,
icon: "vitecaidanliebiao",
id: 82,
level: 1,
name: "much-menu-two",
parentId: 8,
sort: 997,
title: "二级菜单(二)",
},
{
hidden: 1,
icon: "viteZJ-fuwenben",
id: 821,
level: 2,
name: "much-menu-two-one",
parentId: 82,
sort: 997,
title: "三级级菜单(一)",
},
{
hidden: 1,
icon: "vitecaidanliebiao",
id: 822,
level: 2,
name: "much-menu-two-two",
parentId: 82,
sort: 997,
title: "三级级菜单(二)",
},
{
hidden: 1,
icon: "viteviteZJ-ditu",
id: 8221,
level: 3,
name: "much-menu-three-one",
parentId: 822,
sort: 997,
title: "四级级菜单(一)",
},
{
hidden: 1,
icon: "vitei",
id: 8222,
level: 3,
name: "much-menu-three-two",
parentId: 822,
sort: 997,
title: "四级级菜单(二)",
},
// 权限管理
{
hidden: 1,
icon: "vitequanxianguanli-02",
id: 9,
level: 0,
name: "authority",
parentId: 0,
sort: 997,
title: "权限管理",
},
{
hidden: 1,
icon: "viteyonghuliebiao",
id: 91,
level: 1,
name: "admin",
parentId: 9,
sort: 9,
title: "用户列表",
},
{
hidden: 1,
icon: "vitejiaose",
id: 92,
level: 1,
name: "demo",
parentId: 9,
sort: 9,
title: "权限演示",
},
{
hidden: 1,
icon: "vitecaidanliebiao",
id: 93,
level: 1,
name: "menu",
parentId: 9,
sort: 2,
title: "菜单列表",
},
// {
// hidden: 1,
// icon: "viteliebiao",
// id: 9,
// level: 1,
// name: "resource",
// parentId: 5,
// sort: 999,
// title: "资源列表",
// },
],
ordinary: [
{
hidden: 1,
icon: "vitezujian",
id: 1,
level: 0,
name: "modules",
parentId: 0,
sort: 997,
title: "组件列表",
},
{
hidden: 1,
icon: "viteZJ-biaoge",
id: 11,
level: 1,
name: "table",
parentId: 1,
sort: 997,
title: "表格",
},
{
hidden: 1,
icon: "viteZJ-fuwenben",
id: 12,
level: 1,
name: "richText",
parentId: 1,
sort: 997,
title: "富文本",
},
{
hidden: 1,
icon: "viteZJ-shangchuan",
id: 13,
level: 1,
name: "upload",
parentId: 1,
sort: 997,
title: "上传文件",
},
{
hidden: 1,
icon: "viteviteZJ-ditu",
id: 14,
level: 1,
name: "map",
parentId: 1,
sort: 997,
title: "地图",
},
{
hidden: 1,
icon: "viteantv",
id: 15,
level: 1,
name: "antv-x6",
parentId: 1,
sort: 997,
title: "antv-x6",
},
{
hidden: 1,
icon: "vitei",
id: 16,
level: 1,
name: "icon",
parentId: 1,
sort: 997,
title: "图标",
},
{
hidden: 1,
icon: "vitesign",
id: 17,
level: 1,
name: "sign",
parentId: 1,
sort: 997,
title: "签名",
},
// 权限管理
{
hidden: 1,
icon: "vitequanxianguanli-02",
id: 9,
level: 0,
name: "authority",
parentId: 0,
sort: 997,
title: "权限管理",
},
{
hidden: 1,
icon: "viteyonghuliebiao",
id: 91,
level: 1,
name: "admin",
parentId: 9,
sort: 9,
title: "用户列表",
},
{
hidden: 1,
icon: "vitejiaose",
id: 92,
level: 1,
name: "demo",
parentId: 9,
sort: 9,
title: "权限演示",
}
],
test: [
// 权限管理
{
hidden: 1,
icon: "vitequanxianguanli-02",
id: 9,
level: 0,
name: "authority",
parentId: 0,
sort: 997,
title: "权限管理",
},
{
hidden: 1,
icon: "viteyonghuliebiao",
id: 91,
level: 1,
name: "admin",
parentId: 9,
sort: 9,
title: "用户列表",
},
{
hidden: 1,
icon: "vitejiaose",
id: 92,
level: 1,
name: "demo",
parentId: 9,
sort: 9,
title: "权限演示",
}
],
};
export default roles; | the_stack |
import { ChangeDetectorRef } from '@angular/core';
import {
createComponentFactory,
createHostFactory,
Spectator,
SpectatorHost,
} from '@ngneat/spectator';
import { TestHelper } from '../../testing/test-helper';
import { ProgressCircleRingComponent } from './progress-circle-ring.component';
import { ProgressCircleComponent } from './progress-circle.component';
describe('ProgressCircleComponent', () => {
describe('with stubbed IntersectionObserver', () => {
let spectator: Spectator<ProgressCircleComponent>;
let changeDetectorRef: ChangeDetectorRef;
let intersectionObserverConstructorSpy: jasmine.Spy;
const createHost = createComponentFactory({
component: ProgressCircleComponent,
declarations: [ProgressCircleRingComponent],
});
beforeEach(() => {
// IntersectionObserver not exposed in the DOM lib for TS. See: https://github.com/microsoft/TypeScript/pull/18110
intersectionObserverConstructorSpy = spyOn(
window as any,
'IntersectionObserver'
).and.returnValue({
observe: jasmine.createSpy('observe()'),
unobserve: jasmine.createSpy('unobserve()'),
disconnect: jasmine.createSpy('disconnect'),
});
spectator = createHost({
props: { value: 30 },
});
changeDetectorRef = (spectator as any).instance.changeDetectorRef;
});
it('should create', () => {
expect(spectator.component).toBeTruthy();
});
describe('diameter', () => {
it('should default to md', () => {
expect(spectator.component._diameter).toBe(56);
});
it('should map sm to correct value', () => {
spectator.setInput({ size: 'sm' });
expect(spectator.component._diameter).toBe(40);
});
it('should map md to correct value', () => {
spectator.setInput({ size: 'md' });
expect(spectator.component._diameter).toBe(56);
});
it('should map lg to correct value', () => {
spectator.setInput({ size: 'lg' });
expect(spectator.component._diameter).toBe(96);
});
});
describe('strokeWidth', () => {
it('should default to md', () => {
expect(spectator.component._strokeWidth).toBe(4);
});
it('should map sm to correct value', () => {
spectator.setInput({ size: 'sm' });
expect(spectator.component._strokeWidth).toBe(3);
});
it('should map md to correct value', () => {
spectator.setInput({ size: 'md' });
expect(spectator.component._strokeWidth).toBe(4);
});
it('should map lg to correct value', () => {
spectator.setInput({ size: 'lg' });
expect(spectator.component._strokeWidth).toBe(6);
});
});
describe('shownValue', () => {
it('should return 0 until element has been visible', () => {
spectator.setInput({ value: 50 });
spectator.component['hasElementBeenVisible'] = false;
expect(spectator.component._shownValue).toBe(0);
});
it('should return value after element has been visible', () => {
spectator.setInput({ value: 50 });
spectator.component['hasElementBeenVisible'] = true;
expect(spectator.component._shownValue).toBe(50);
});
});
describe('radius', () => {
it('should calculate radius as diameter / 2', () => {
spectator.setInput({ size: 'sm' });
expect(spectator.component._radius).toBe(
spectator.component.SIZE_CONFIG['sm'].diameter / 2
);
});
});
describe('ngAfterViewInit', () => {
it('should instantiate IntersectionObserver with onIntersectionChange as callback', async () => {
expect(intersectionObserverConstructorSpy).toHaveBeenCalledWith(
spectator.component['onIntersectionChange'],
jasmine.any(Object)
);
});
it('should set up an intersection observer on element', () => {
expect(spectator.component['observer'].observe).toHaveBeenCalledWith(
spectator.debugElement.nativeElement
);
});
});
describe('onIntersectionChange', () => {
it('should not have been visible before onIntersectionChange has been called', () => {
expect(spectator.component['hasElementBeenVisible']).toBeFalsy();
});
it('should mark element as visible if element is intersecting when observer is called', () => {
// Arrange
const entries: Partial<IntersectionObserverEntry>[] = [{ isIntersecting: true }];
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(spectator.component['hasElementBeenVisible']).toBe(true);
});
it('should mark element as visible if several entries are returned when observer is called and all are intersecting', () => {
// Arrange
const entries: Partial<IntersectionObserverEntry>[] = [
{ isIntersecting: true },
{ isIntersecting: true },
];
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(spectator.component['hasElementBeenVisible']).toBe(true);
});
it('should mark element as visible if several entries are returned when observer is called and any is intersecting', () => {
// Arrange
const entries: Partial<IntersectionObserverEntry>[] = [
{ isIntersecting: false },
{ isIntersecting: true },
];
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(spectator.component['hasElementBeenVisible']).toBe(true);
});
it('should not mark element as visible if several entries are returned when observer is called but none are intersecting', () => {
// Arrange
const entries: Partial<IntersectionObserverEntry>[] = [
{ isIntersecting: false },
{ isIntersecting: false },
];
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(spectator.component['hasElementBeenVisible']).toBe(false);
});
it('should not mark element as visible if elements are not intersecting when observer is called (on init)', () => {
// Arrange
const entries: Partial<IntersectionObserverEntry>[] = [{ isIntersecting: false }];
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(spectator.component['hasElementBeenVisible']).toBeFalsy();
});
it('should not mark element as visible if elements array is undefined', () => {
// Arrange
const entries: Partial<IntersectionObserverEntry>[] = undefined;
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(spectator.component['hasElementBeenVisible']).toBeFalsy();
});
it('should not mark element as visible if elements array is empty', () => {
// Arrange
const entries: Partial<IntersectionObserverEntry>[] = [];
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(spectator.component['hasElementBeenVisible']).toBe(false);
});
it('should not mark component for change detection when not intersecting', () => {
// Arrange
spyOn(changeDetectorRef, 'markForCheck').and.callThrough();
const entries: Partial<IntersectionObserverEntry>[] = [{ isIntersecting: false }];
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(changeDetectorRef.markForCheck).not.toHaveBeenCalled();
});
it('should mark component for change detection when visible to start animation', () => {
// Arrange
spyOn(changeDetectorRef, 'markForCheck').and.callThrough();
const entries: Partial<IntersectionObserverEntry>[] = [{ isIntersecting: true }];
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(changeDetectorRef.markForCheck).toHaveBeenCalled();
});
it('should unsubscribe observer when elements are intersecting', () => {
// Arrange
spectator.component['unobserve'] = jasmine.createSpy('disconnectObserver');
const entries: Partial<IntersectionObserverEntry>[] = [{ isIntersecting: true }];
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(spectator.component['unobserve']).toHaveBeenCalled();
});
it('should not unsubscribe observer if elements are not intersecting', () => {
// Arrange
spectator.component['unobserve'] = jasmine.createSpy('disconnectObserver');
const entries: Partial<IntersectionObserverEntry>[] = [{ isIntersecting: false }];
// Act
spectator.component['onIntersectionChange'](entries as IntersectionObserverEntry[]);
// Assert
expect(spectator.component['unobserve']).not.toHaveBeenCalled();
});
});
describe('unobserve', () => {
it('should handle observer being undefined (in case view init has not happened yet)', () => {
spectator.component['observer'] = undefined;
expect(() => {
spectator.component['unobserve']();
}).not.toThrowError();
});
it('should call unobserve when disconnecting', () => {
spectator.component['unobserve']();
expect(spectator.component['observer'].unobserve).toHaveBeenCalledWith(
spectator.debugElement.nativeElement
);
});
it('should call disconnect when disconnecting', () => {
spectator.component['unobserve']();
expect(spectator.component['observer'].disconnect).toHaveBeenCalled();
});
it('should be able disconnect function to be missing (some browsers do not suppport it)', () => {
spectator.component['observer'].disconnect = undefined;
expect(() => {
spectator.component['unobserve']();
}).not.toThrowError();
});
});
describe('ngOnDestroy', () => {
it('should call unobserve', () => {
spectator.component['unobserve'] = jasmine.createSpy('unobserve');
spectator.component.ngOnDestroy();
expect(spectator.component['unobserve']).toHaveBeenCalled();
});
});
});
describe('with real IntersectionObserver', () => {
let spectator: SpectatorHost<ProgressCircleComponent>;
const createHost = createHostFactory({
component: ProgressCircleComponent,
declarations: [ProgressCircleRingComponent],
});
beforeEach(() => {
spectator = createHost('<kirby-progress-circle></kirby-progress-circle>', {
props: { value: 50 },
});
});
it('should set hasElementBeenVisible after scrolled into view', async () => {
expect(spectator.component['hasElementBeenVisible']).toBeUndefined();
const paddingTop = window.innerHeight; // Ensure the element is below the fold
(spectator.hostElement as HTMLElement).style.paddingTop = `${paddingTop}px`;
await TestHelper.whenTrue(() => spectator.component['hasElementBeenVisible'] === false); // Await IntersectionObserver to fire
expect(spectator.component['hasElementBeenVisible']).toBeFalse();
// Act
spectator.element.scrollIntoView();
await TestHelper.whenTrue(() => spectator.component['hasElementBeenVisible'] === true); // Await IntersectionObserver to fire
expect(spectator.component['hasElementBeenVisible']).toBeTrue();
});
});
}); | the_stack |
import BinomialNode from './binomial-node'
import * as utils from '../../utils'
/*******************************************************************************
* A binomial heap is a forest of binomial trees.
*
* A binomial tree of degree 0 is a single node.
* A binomial tree of degree k has a root node with k children. The degrees of those
* children are k-1, k-2,..., 2, 1, 0.
*
* A binomial tree of degree k has 2^k nodes.
*
* A binomial heap is a forest of binomial trees that satisfy the heap invariant.
* There can be only 0 or 1 binomial tree of degree k in the forest.
*
* The two key features of binomial heaps are:
*
* 1. The roots of the forest are <= log(n)
* 2. Merging two heaps is binary addition
*
* This brings merge() from O(n + m) to O(logn + logm)!!!
*
* But because we now have a forest instead of one single tree, findMin() now
* takes O(logn) to traverse the entire forest :( Check out the lazy binomial heap
* to see how we can bring this back down to O(1)
*
* enqueue() - O(logn)
* extractMin() - O(logn)
* findMin() - O(1)
* merge() - O(logn + logm) ~~~improved from O(n+m)!
*
* More info can be found here: https://en.wikipedia.org/wiki/Binomial_heap
* The Implementation belowbased off Binomial Heap pseudocode from CLRS ed 2 (Chapter 19)
******************************************************************************/
class MinBinomialHeap<T> {
head: BinomialNode<T> | null
size: number
minRoot: BinomialNode<T> | null
// smallestValue for deleteNode(node)
// deleteNode will decrease the node to the smallest value so it swims up to
// the root, and then calls dequeue()
private smallestValue: T
// comparison function if the generic type T is non-primitive
private compare: utils.CompareFunction<T>
constructor(smallestValue: T, compareFunction?: utils.CompareFunction<T>) {
this.head = null
this.minRoot = null
this.size = 0
this.smallestValue = smallestValue
this.compare = compareFunction || utils.defaultCompare
}
/*****************************************************************************
INSPECTION
*****************************************************************************/
/**
* Returns true if the heap is empty, false otherwise - O(1)
* @returns {boolean}
*/
isEmpty(): boolean {
return this.size === 0
}
/*****************************************************************************
INSERTION/DELETION
*****************************************************************************/
/**
* Enqueues element onto the heap.
* @param {T} element
* @returns {void}
*/
enqueue(element: T): BinomialNode<T> {
// create a heap containing the single new element, hPrime
const heapWithElement = new MinBinomialHeap<T>(this.smallestValue)
const insertedElement = new BinomialNode(element)
heapWithElement.head = insertedElement
// union that heap with our current heap
const newHeap = this.union(heapWithElement) // O(logn)! not O(n)
this.size += 1
// set the current heap's head pointer to the newHeap's head pointer
this.head = newHeap.head
this.recalculateMin()
return insertedElement
}
/**
* Dequeues the smallest element from the heap // O(logn)
* @param {T} element
* @returns {void}
*/
dequeue(): BinomialNode<T> | null {
// remove smallest root of smallest tree B_k from heap
const smallestRoot = this.removeSmallestRoot() // O(logn)
this.size -= 1
if (!smallestRoot) return smallestRoot
if (smallestRoot.child) {
// make a new heap out of the reversed linked list of B_k's children
const reversedChildren = new MinBinomialHeap<T>(this.smallestValue)
reversedChildren.head = this.reverseListOfRoots(smallestRoot.child) // O(???)
// union the reversedChildren heap with the current heap to form the new heap
const newHeap = this.union(reversedChildren) // O(logn)
this.head = newHeap.head
}
this.recalculateMin()
// return the removed root
return smallestRoot
}
/**
* Deletes the given node - O(logn)
* @param {BinomialNode<T>} node
* @returns {void}
*/
deleteNode(node: BinomialNode<T>): BinomialNode<T> | null {
// make it the smallest node in the heap so it swims up
this.decreaseKey(node, this.smallestValue) // O(logn)
// dequeue the smallest node from the heap
return this.dequeue() // O(logn)
}
private removeSmallestRoot(): BinomialNode<T> | null {
if (!this.head) return null
let cur: BinomialNode<T> | null = this.head
let prev = cur
let min = cur
let prevMin = null
cur = cur.sibling
// O(logn) since we traverse entire forest
while (cur) {
const currentIsLessThanMin = this.compare(cur.value, min.value) < 0
if (currentIsLessThanMin) {
min = cur
prevMin = prev
}
prev = cur
cur = cur.sibling
}
// if smallest root is head, then move heap.head pointer one root forwards
if (prev === null || prevMin === null) {
this.head = this.head.sibling
} else {
// otherwise link prev root with min's right root
prevMin.sibling = min.sibling
}
return min
}
// reverses linked list of trees in O(t) time where t is the number of trees/roots
private reverseListOfRoots(head: BinomialNode<T>): BinomialNode<T> {
let cur: BinomialNode<T> | null = head
let prev: BinomialNode<T> | null = null
let next: BinomialNode<T> | null = null
while (cur) {
next = cur.sibling
cur.sibling = prev
prev = cur
cur = next
}
// eslint-disable-next-line
return prev!
}
private recalculateMin(): void {
if (!this.head) return
let cur = this.head.sibling
let min = this.head
while (cur) {
if (cur.value < min.value) min = cur
cur = cur.sibling
}
this.minRoot = min
}
/*****************************************************************************
READING
*****************************************************************************/
/**
* Returns the smallest node in the heap, null if the heap is empty O(1)
* @returns {BinomialNode<T> | null}
*/
peek(): BinomialNode<T> | null {
if (!this.head) return null
return this.minRoot
}
/*****************************************************************************
UPDATING
*****************************************************************************/
/**
* Unions supplied heap with current heap - O(logn + logm)
* @param {MinBinomialHeap<T>} otherHeap
* @returns {MinBinomialHeap<T>}
*/
union(otherHeap: MinBinomialHeap<T>): MinBinomialHeap<T> {
// FIRST PHASE
// =========================================================================
// this.mergeForests() merges the root lists of otherHeap (H1) and thisHeap (H2)
// into a single root list H that is sorted by monotonically increasing
// degree
// this.mergeForests() runs in O(m) times where m = n1 + n2
// by applying the merge step in merge sort to the two linked lists of roots
const newHeap = this.mergeForests(this, otherHeap) // O(n + m)
if (newHeap.head === null) return newHeap // return null if both H1 and H2 were null
// SECOND PHASE
// =========================================================================
// From the merge, there might now be two roots (but no more) of some degree k.
// Second phase links roots of equal degree until at most one root remains of each degree.
let prevRoot: BinomialNode<T> | null = null
let root = newHeap.head
let nextRoot = root.sibling
while (nextRoot !== null) {
const currentTwoRootsAreNotEqual = root.degree !== nextRoot.degree
const nextTwoRootsAreEqual =
nextRoot.sibling !== null && nextRoot.sibling.degree === nextRoot.degree
const movePointers = currentTwoRootsAreNotEqual || nextTwoRootsAreEqual
// nextTwoRootsAreEqual only gets evaluated if currentTwoRootsAreNotEqual is false
// this ==> that the next three roots are equal
// this occurs after linking two B_(k-1) trees to B_k, but the next two
// roots are B_k as well
// degree[root] = degree[root.sibling] = degree[root.sibling.sibling]
if (movePointers) {
prevRoot = root
root = nextRoot
// we don't update nextRoot in this branch
// we do it outside the if/else bc it's common to all cases
} else {
// the smaller root becomes the new root when linking to maintain the
// heap invariant
if (root.value <= nextRoot.value) {
root.sibling = nextRoot.sibling // removes nextRoot from list
this.linkTrees(root, nextRoot)
} else {
// then nextRoot.value < root.value
if (prevRoot === null) {
// if root is the head, point newHeap.head to nextRoot
newHeap.head = nextRoot
} else {
// otherwise, just remove current root by linking prevRoot.sibling to nextRoot
prevRoot.sibling = nextRoot
}
this.linkTrees(nextRoot, root)
root = nextRoot
}
}
// root now points to a binomial tree that is now the first of one, two,
// or three B_(k+1) trees on newHeap linked list of roots
nextRoot = root.sibling
}
return newHeap
}
// Links two trees with degree k-1, B_(k-1), and makes one tree with degree
// k, B_k, where nodeA becomes the root of the new tree.
// It does this by making treeB the new head of treeA's children in O(1)
private linkTrees(treeA: BinomialNode<T>, treeB: BinomialNode<T>): void {
treeB.parent = treeA
treeB.sibling = treeA.child
treeA.child = treeB
treeA.degree += 1
}
// Merges two forests and returns one forest sorted by degree in O(t)
// time where t is the total number of trees in both forests.
private mergeForests(heapA: MinBinomialHeap<T>, heapB: MinBinomialHeap<T>): MinBinomialHeap<T> {
if (!heapA.head) return heapB
if (!heapB.head) return heapA
let head = null
let a: BinomialNode<T> | null = heapA.head
let b: BinomialNode<T> | null = heapB.head
if (a.degree < b.degree) {
head = a
a = a.sibling
} else {
head = b
b = b.sibling
}
let cur: BinomialNode<T> | null = head
while (a !== null && b !== null) {
if (a.degree < b.degree) {
cur.sibling = a
a = a.sibling
} else {
cur.sibling = b
b = b.sibling
}
cur = cur.sibling
}
if (a !== null) {
cur.sibling = a
}
if (b !== null) {
cur.sibling = b
}
const mergedHeap = new MinBinomialHeap<T>(this.smallestValue)
mergedHeap.head = head
mergedHeap.size = heapA.size + heapB.size
return mergedHeap
}
/**
* Decreases the value of the given node to the new value. Returns true if
* successful, and false otherwise - O(logn)
* @param {BinomialNode<T>} node
* @param {T} newValue
* @returns {boolean}
*/
decreaseKey(node: BinomialNode<T>, newValue: T): boolean {
// if newKey >= key, don't update
if (this.compare(node.value, newValue) < 0) return false
node.value = newValue
let cur = node
let parent = cur.parent
// swim in O(logn)
while (parent && cur.value < parent.value) {
const temp = parent.value
parent.value = cur.value
cur.value = temp
cur = parent
parent = cur.parent
}
return true
}
}
export default MinBinomialHeap | the_stack |
interface IOutIsValid {
IsValid: boolean;
}
interface IType {
}
class DependencyProperty {
static UnsetValue = {};
private static _IDs: DependencyProperty[] = [];
private static _LastID: number = 0;
_ID: number;
Name: string;
GetTargetType: () => IType;
OwnerType: any;
DefaultValue: any;
IsReadOnly: boolean = false;
IsCustom: boolean = true;
IsAttached: boolean = false;
IsInheritable: boolean = false;
IsImmutable: boolean = false;
ChangedCallback: (dobj: Fayde.DependencyObject, args: DependencyPropertyChangedEventArgs) => void;
AlwaysChange: boolean = false;
Store: Fayde.Providers.PropertyStore;
private _Coercer: (dobj: Fayde.DependencyObject, propd: DependencyProperty, value: any) => any = null;
private _Validator: (dobj: Fayde.DependencyObject, propd: DependencyProperty, value: any, original: any) => boolean = null;
static Register (name: string, getTargetType: () => IType, ownerType: any, defaultValue?: any, changedCallback?: (dobj: Fayde.DependencyObject, args: DependencyPropertyChangedEventArgs) => void) {
var propd = new DependencyProperty();
propd.Name = name;
propd.GetTargetType = getTargetType;
propd.OwnerType = ownerType;
propd.DefaultValue = defaultValue;
propd.ChangedCallback = changedCallback;
propd.Store = Fayde.Providers.PropertyStore.Instance;
propd.FinishRegister();
return propd;
}
static RegisterReadOnly (name: string, getTargetType: () => IType, ownerType: any, defaultValue?: any, changedCallback?: (dobj: Fayde.DependencyObject, args: DependencyPropertyChangedEventArgs) => void) {
var propd = new DependencyProperty();
propd.Name = name;
propd.GetTargetType = getTargetType;
propd.OwnerType = ownerType;
propd.DefaultValue = defaultValue;
propd.ChangedCallback = changedCallback;
propd.IsReadOnly = true;
propd.Store = Fayde.Providers.PropertyStore.Instance;
propd.FinishRegister();
return propd;
}
static RegisterAttached (name: string, getTargetType: () => IType, ownerType: any, defaultValue?: any, changedCallback?: (dobj: Fayde.DependencyObject, args: DependencyPropertyChangedEventArgs) => void) {
var propd = new DependencyProperty();
propd.Name = name;
propd.GetTargetType = getTargetType;
propd.OwnerType = ownerType;
propd.DefaultValue = defaultValue;
propd.ChangedCallback = changedCallback;
propd.IsAttached = true;
propd.Store = Fayde.Providers.PropertyStore.Instance;
propd.FinishRegister();
return propd;
}
static RegisterCore (name: string, getTargetType: () => IType, ownerType: any, defaultValue?: any, changedCallback?: (dobj: Fayde.DependencyObject, args: DependencyPropertyChangedEventArgs) => void) {
var propd = new DependencyProperty();
propd.Name = name;
propd.GetTargetType = getTargetType;
propd.OwnerType = ownerType;
propd.DefaultValue = defaultValue;
propd.ChangedCallback = changedCallback;
propd.IsCustom = false;
propd.Store = Fayde.Providers.PropertyStore.Instance;
propd.FinishRegister();
return propd;
}
static RegisterReadOnlyCore (name: string, getTargetType: () => IType, ownerType: any, defaultValue?: any, changedCallback?: (dobj: Fayde.DependencyObject, args: DependencyPropertyChangedEventArgs) => void) {
var propd = new DependencyProperty();
propd.Name = name;
propd.GetTargetType = getTargetType;
propd.OwnerType = ownerType;
propd.DefaultValue = defaultValue;
propd.ChangedCallback = changedCallback;
propd.IsCustom = false;
propd.IsReadOnly = true;
propd.Store = Fayde.Providers.PropertyStore.Instance;
propd.FinishRegister();
return propd;
}
static RegisterAttachedCore (name: string, getTargetType: () => IType, ownerType: any, defaultValue?: any, changedCallback?: (dobj: Fayde.DependencyObject, args: DependencyPropertyChangedEventArgs) => void) {
var propd = new DependencyProperty();
propd.Name = name;
propd.GetTargetType = getTargetType;
propd.OwnerType = ownerType;
propd.DefaultValue = defaultValue;
propd.ChangedCallback = changedCallback;
propd.IsCustom = false;
propd.IsAttached = true;
propd.Store = Fayde.Providers.PropertyStore.Instance;
propd.FinishRegister();
return propd;
}
static RegisterImmutable<T>(name: string, getTargetType: () => IType, ownerType: any): ImmutableDependencyProperty<T> {
var propd = new ImmutableDependencyProperty<T>();
propd.Name = name;
propd.GetTargetType = getTargetType;
propd.OwnerType = ownerType;
propd.DefaultValue = undefined;
propd.IsImmutable = true;
propd.Store = Fayde.Providers.ImmutableStore.Instance;
propd.FinishRegister();
return propd;
}
static RegisterInheritable (name: string, getTargetType: () => IType, ownerType: any, defaultValue?: any, changedCallback?: (dobj: Fayde.DependencyObject, args: DependencyPropertyChangedEventArgs) => void) {
var propd = new DependencyProperty();
propd.Name = name;
propd.GetTargetType = getTargetType;
propd.OwnerType = ownerType;
propd.DefaultValue = defaultValue;
propd.ChangedCallback = changedCallback;
propd.IsCustom = true;
propd.IsInheritable = true;
propd.Store = Fayde.Providers.InheritedStore.Instance;
propd.FinishRegister();
return propd;
}
static RegisterFull (name: string, getTargetType: () => IType, ownerType: any, defaultValue?: any, changedCallback?: (dobj: Fayde.DependencyObject, args: DependencyPropertyChangedEventArgs) => void, coercer?: (dobj: Fayde.DependencyObject, propd: DependencyProperty, value: any) => any, alwaysChange?: boolean, validator?: (dobj: Fayde.DependencyObject, propd: DependencyProperty, value: any) => boolean, isCustom?: boolean, isReadOnly?: boolean, isAttached?: boolean): DependencyProperty {
var propd = new DependencyProperty();
propd.Name = name;
propd.GetTargetType = getTargetType;
propd.OwnerType = ownerType;
propd.DefaultValue = defaultValue;
propd.ChangedCallback = changedCallback;
propd._Coercer = coercer;
propd.AlwaysChange = alwaysChange;
propd._Validator = validator;
propd.IsCustom = isCustom !== false;
propd.IsReadOnly = isReadOnly === true;
propd.IsAttached = isAttached === true;
propd.Store = Fayde.Providers.PropertyStore.Instance;
propd.FinishRegister();
return propd;
}
private FinishRegister () {
var name = this.Name;
var ownerType = this.OwnerType;
if (!ownerType || typeof ownerType !== "function")
throw new InvalidOperationException("DependencyProperty does not have a valid OwnerType.");
var registeredDPs = (<any>ownerType)._RegisteredDPs;
if (!registeredDPs) {
var registeredDPs: any = {};
Object.defineProperty(ownerType, "_RegisteredDPs", {
value: registeredDPs,
enumerable: false,
writable: false
});
}
if (registeredDPs[name] !== undefined)
throw new InvalidOperationException("Dependency Property is already registered. [" + name + "]");
registeredDPs[name] = this;
this._ID = DependencyProperty._LastID = DependencyProperty._LastID + 1;
DependencyProperty._IDs[this._ID] = this;
if (this.IsImmutable)
return;
var propd = this;
var getter = function () {
return (<Fayde.DependencyObject>this).GetValue(propd);
};
var setter = function (value) {
(<Fayde.DependencyObject>this).SetValue(propd, value);
};
if (this.IsReadOnly)
setter = function (value) {
throw new Exception("Property [" + propd.Name + "] is readonly.");
};
Object.defineProperty(ownerType.prototype, this.Name, {
get: getter,
set: setter,
configurable: true
});
}
ExtendTo (type: any): DependencyProperty {
var registeredDPs = type._RegisteredDPs;
if (!registeredDPs) {
var registeredDPs: any = {};
Object.defineProperty(type, "_RegisteredDPs", {
value: registeredDPs,
enumerable: false,
writable: false
});
}
registeredDPs[this.Name] = this;
var propd = this;
var getter = function () {
return (<Fayde.DependencyObject>this).GetValue(propd);
};
var setter = function (value) {
(<Fayde.DependencyObject>this).SetValue(propd, value);
};
Object.defineProperty(type.prototype, this.Name, {
get: getter,
set: setter,
configurable: true
});
return this;
}
ValidateSetValue (dobj: Fayde.DependencyObject, value: any, isValidOut: IOutIsValid) {
var coerced = value;
if (this._Coercer)
coerced = this._Coercer(dobj, this, coerced);
/* TODO: Handle Type Problems
if (!this._IsValueValid(dobj, coerced))
return coerced;
*/
isValidOut.IsValid = true;
if (this._Validator)
isValidOut.IsValid = !!this._Validator(dobj, this, coerced, value);
return coerced;
}
static GetDependencyProperty (ownerType: any, name: string, noError?: boolean): DependencyProperty {
if (!ownerType)
return undefined;
var reg: DependencyProperty[] = (<any>ownerType)._RegisteredDPs;
var propd: DependencyProperty;
if (reg)
propd = reg[name];
if (!propd)
propd = DependencyProperty.GetDependencyProperty(nullstone.getTypeParent(ownerType), name, true);
if (!propd && !noError)
throw new Exception("Cannot locate dependency property [" + (<any>ownerType).name + "].[" + name + "]");
return propd;
}
}
Fayde.CoreLibrary.add(DependencyProperty);
class ImmutableDependencyProperty<T> extends DependencyProperty {
IsImmutable: boolean = true;
Initialize (dobj: Fayde.DependencyObject): T {
var storage = Fayde.Providers.GetStorage(dobj, this);
storage.Precedence = Fayde.Providers.PropertyPrecedence.LocalValue;
var type = <any>this.GetTargetType();
var obj: T = new type();
Object.defineProperty(dobj, this.Name, {
value: obj,
writable: false
});
return storage.Local = obj;
}
} | the_stack |
import { Component, OnInit, Output, EventEmitter, OnDestroy } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Subscription} from 'rxjs/Subscription';
import {WorkflowService} from '../../../../core/services/workflow.service';
import {LoggerService} from '../../../../shared/services/logger.service';
import {FilterManagementService} from '../../../../shared/services/filter-management.service';
import {ErrorHandlingService} from '../../../../shared/services/error-handling.service';
import {AssetGroupObservableService} from '../../../../core/services/asset-group-observable.service';
import {DomainTypeObservableService} from '../../../../core/services/domain-type-observable.service';
import {UtilsService} from '../../../../shared/services/utils.service';
import {RouterUtilityService} from '../../../../shared/services/router-utility.service';
import {environment} from './../../../../../environments/environment';
import {VulnerabilityDetailsService} from '../../../services/vulnerability-details.service';
@Component({
selector: 'app-vulnerability-details',
templateUrl: './vulnerability-details.component.html',
styleUrls: ['./vulnerability-details.component.css'],
providers: [VulnerabilityDetailsService]
})
export class VulnerabilityDetailsComponent implements OnInit, OnDestroy {
assetGroupSubscription: Subscription;
domainSubscription: Subscription;
pageTitle = 'Vulnerability Details';
breadcrumbDetails = {
breadcrumbArray: ['Compliance', 'All Vulnerabilities'],
breadcrumbLinks: ['compliance-dashboard', 'vulnerabilities'],
breadcrumbPresent: 'Vulnerability Details'
};
backButtonRequired: boolean;
pageLevel = 0;
errorMessage: string;
agAndDomain = {};
errorValue = 0;
@Output() errorOccurred = new EventEmitter();
tabsName= ['general info', 'software', 'threat',
'impact', 'solution', 'exploitability', 'malware'];
tabsData: any;
selectedTab: any;
selectedTabData: any;
qid: any;
vulnerabilityTitle: string;
search: any;
error_messages = {
'general info': {
'description': 'No Information found for this vulnerability'
},
'software': {
'description': 'No Software found for this vulnerability'
},
'threat': {
'description': 'No Threat found for this vulnerability'
},
'impact': {
'description': 'No Impact found for this vulnerability'
},
'solution': {
'description': 'No Solution found for this vulnerability'
},
'exploitability': {
'description': 'No Exploitability found for this vulnerability'
},
'malware': {
'description': 'No Malware is associated for this vulnerability'
}
};
isFilterRquiredOnPage = false;
appliedFilters = {
queryParamsWithoutFilter: {}, /* Stores the query parameter ibject without filter */
pageLevelAppliedFilters: {} /* Stores the query parameter ibject without filter */
};
filterArray = []; /* Stores the page applied filter array */
private dataSubscription: Subscription;
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private workflowService: WorkflowService,
private logger: LoggerService,
private filterManagementService: FilterManagementService,
private errorHandling: ErrorHandlingService,
private assetGroupObservableService: AssetGroupObservableService,
private domainObservableService: DomainTypeObservableService,
private utils: UtilsService,
private routerUtilityService: RouterUtilityService,
private vulnerabilityDetailsService: VulnerabilityDetailsService) {
this.subscribeToAssetGroup();
this.subscribeToDomain();
}
ngOnInit() {
}
subscribeToAssetGroup() {
this.assetGroupSubscription = this.assetGroupObservableService.getAssetGroup().subscribe(assetGroup => {
if (assetGroup) {
this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently(this.pageLevel);
this.agAndDomain['ag'] = assetGroup;
}
this.reset();
this.init();
this.updateComponent();
});
}
subscribeToDomain() {
this.domainSubscription = this.domainObservableService.getDomainType().subscribe(domain => {
if (domain) {
this.agAndDomain['domain'] = domain;
}
});
}
reset() {
/* Reset the page */
this.filterArray = [];
}
init() {
/* Initialize */
this.routerParam();
}
updateComponent() {
/* Updates the whole component */
this.getData();
}
routerParam() {
try {
const urlSegment = this.routerUtilityService.getPageUrlSegmentFromSnapshot(this.router.routerState.snapshot.root);
if (urlSegment) {
this.qid = urlSegment[urlSegment.length - 1].path;
}
const currentQueryParams = this.routerUtilityService.getQueryParametersFromSnapshot(this.router.routerState.snapshot.root);
if (currentQueryParams) {
this.appliedFilters.queryParamsWithoutFilter = JSON.parse(JSON.stringify(currentQueryParams));
delete this.appliedFilters.queryParamsWithoutFilter['filter'];
this.appliedFilters.pageLevelAppliedFilters = this.utils.processFilterObj(currentQueryParams);
this.filterArray = this.filterManagementService.getFilterArray(this.appliedFilters.pageLevelAppliedFilters);
}
} catch (error) {
this.errorMessage = this.errorHandling.handleJavascriptError(error);
this.logger.log('error', error);
}
}
updateUrlWithNewFilters(filterArr) {
this.appliedFilters.pageLevelAppliedFilters = this.utils.arrayToObject(
this.filterArray,
'filterkey',
'value'
); // <-- TO update the queryparam which is passed in the filter of the api
this.appliedFilters.pageLevelAppliedFilters = this.utils.makeFilterObj(this.appliedFilters.pageLevelAppliedFilters);
/**
* To change the url
* with the deleted filter value along with the other existing paramter(ex-->tv:true)
*/
const updatedFilters = Object.assign(
this.appliedFilters.pageLevelAppliedFilters,
this.appliedFilters.queryParamsWithoutFilter
);
/*
Update url with new filters
*/
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: updatedFilters
}).then(success => {
this.routerParam();
});
}
navigateBack() {
try {
this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root);
} catch (error) {
this.logger.log('error', error);
}
}
ngOnDestroy() {
try {
if (this.assetGroupSubscription) {
this.assetGroupSubscription.unsubscribe();
}
if (this.domainSubscription) {
this.domainSubscription.unsubscribe();
}
if (this.dataSubscription) {
this.dataSubscription.unsubscribe();
}
} catch (error) {
this.logger.log('error', 'JS Error - ' + error);
}
}
/* specific functionalities for this page */
getData() {
try {
if (this.dataSubscription) {
this.dataSubscription.unsubscribe();
}
const payload = {};
const queryParam = {
'qid': this.qid
};
this.errorValue = 0;
const url = environment.vulnerabilityQidDetails.url;
const method = environment.vulnerabilityQidDetails.method;
this.dataSubscription = this.vulnerabilityDetailsService.getData(url, method, payload, queryParam).subscribe(
response => {
try {
if (this.utils.checkIfAPIReturnedDataIsEmpty(response)) {
this.errorOccurred.emit();
this.errorValue = -1;
this.errorMessage = 'noDataAvailable';
} else {
this.errorValue = 1;
this.processGraphData(response);
}
} catch (e) {
this.errorOccurred.emit();
this.errorValue = -1;
this.errorMessage = 'jsError';
this.logger.log('error', e);
}
},
error => {
this.errorOccurred.emit();
this.errorValue = -1;
this.errorMessage = 'apiResponseError';
this.logger.log('error', error);
});
} catch (error) {
this.logger.log('error', error);
}
}
processGraphData(data) {
try {
this.tabsData = data;
this.vulnerabilityTitle = this.extractVulnerabilityTitle(this.tabsData);
let i = 0;
while (i < this.tabsName[i].length) {
if (this.tabsName[i].toLowerCase() === this.tabsData[0].name.toLowerCase()) {
this.selectedTab = JSON.parse(JSON.stringify(this.tabsData[0]));
this.selectedTabData = Object.keys(this.selectedTab.attributes);
if (this.selectedTabData && this.selectedTabData.length === 0) {
this.errorValue = 2;
this.selectedTab.attributes = '';
this.selectedTabData = '';
}
return;
}
i++;
}
} catch (error) {
this.logger.log('error', error);
}
}
extractVulnerabilityTitle(data) {
try {
const generalInfo = data.filter(obj => obj.name.toLowerCase() === 'general info');
if (generalInfo && generalInfo[0].attributes) {
return generalInfo[0].attributes.Title;
}
} catch (error) {
this.logger.log('error', 'js error - ' + error);
}
}
getselectedTabData() {
this.errorValue = 1;
try {
for (let i = 0; i < this.tabsData.length; i++) {
if ((this.selectedTab.name.toLowerCase() === 'exploitability' ||
this.selectedTab.name.toLowerCase() === 'malware') &&
this.selectedTab.name.toLowerCase() === this.tabsData[i].name.toLowerCase()) {
this.selectedTab = JSON.parse(JSON.stringify(this.tabsData[i]));
this.selectedTabData = Object.values(this.selectedTab.attributes);
if (this.selectedTabData && this.selectedTabData.length === 0) {
this.errorValue = 2;
this.selectedTab.attributes = '';
this.selectedTabData = '';
}
return;
} else if (this.selectedTab.name.toLowerCase() === this.tabsData[i].name.toLowerCase()) {
this.selectedTab = JSON.parse(JSON.stringify(this.tabsData[i]));
this.selectedTabData = Object.keys(this.selectedTab.attributes);
if (this.selectedTabData && this.selectedTabData.length === 0) {
this.errorValue = 2;
this.selectedTab.attributes = '';
this.selectedTabData = '';
}
return;
}
}
this.selectedTab.attributes = '';
this.selectedTabData = '';
this.errorOccurred.emit();
this.errorValue = 2;
this.errorMessage = 'dataTableMessage';
} catch (error) {
this.logger.log('error', error);
}
}
} | the_stack |
import {TokenRange} from './Parsec';
import {SubstIn} from './Kit';
import * as K from './Kit';
import * as UT from 'utility-types';
export interface NodeBase {
type: string;
range: TokenRange;
}
export interface CharNode extends NodeBase {
type: 'Char';
value: string;
}
export interface DotNode extends NodeBase {
type: 'Dot';
}
export interface BackrefNode extends NodeBase {
// Backreference
type: 'Backref';
// \3 or \k<name>
index: number | string;
}
export type UnicodeCharClass = {name: string; invert: boolean; value?: string};
export const baseCharClassTuple = ['Digit', 'NonDigit', 'Word', 'NonWord', 'Space', 'NonSpace'] as const;
export type BaseCharClass = typeof baseCharClassTuple[number];
export interface CharClassEscapeNode extends NodeBase {
type: 'CharClassEscape';
charClass: UnicodeCharClass | BaseCharClass;
}
export interface CharRangeNode extends NodeBase {
type: 'CharRange';
begin: CharNode;
end: CharNode;
}
export type CharClassItem = CharRangeNode | CharNode | CharClassEscapeNode;
export interface CharClassNode extends NodeBase {
type: 'CharClass';
invert: boolean;
body: CharClassItem[];
}
export interface ListNode extends NodeBase {
type: 'List';
// Exclude<Expr,ListNode | DisjunctionNode> caused weird recursive ref type error
body: Array<Exclude<Exclude<Expr, ListNode>, DisjunctionNode>>;
}
export interface QuantifierNode extends NodeBase {
type: 'Quantifier';
min: number;
max: number;
greedy: boolean;
}
export interface RepeatNode extends NodeBase {
type: 'Repeat';
quantifier: QuantifierNode;
body: AtomNode;
}
export interface DisjunctionNode extends NodeBase {
type: 'Disjunction';
body: Array<Exclude<Expr, DisjunctionNode>>;
}
export type GroupBehavior =
| {type: 'Capturing'; index: number; name?: string}
| {type: 'NonCapturing'}
| {type: 'Atomic'}
| {type: 'EnableDup'};
export interface GroupNode extends NodeBase {
type: 'Group';
behavior: GroupBehavior;
body: Expr;
}
export interface GroupAssertionNode extends NodeBase {
type: 'GroupAssertion';
look: 'Lookahead' | 'Lookbehind';
negative: boolean;
body: Expr;
}
export const baseAssertionTypeTuple = ['WordBoundary', 'NonWordBoundary', 'Begin', 'End'] as const;
export type BaseAssertionType = typeof baseAssertionTypeTuple[number];
export interface BaseAssertionNode extends NodeBase {
type: 'BaseAssertion';
kind: BaseAssertionType;
}
export type AssertionNode = BaseAssertionNode | GroupAssertionNode;
export type AtomNode = DotNode | CharClassNode | CharClassEscapeNode | CharNode | BackrefNode | GroupNode;
export type LeafNode = CharNode | DotNode | CharClassEscapeNode | BackrefNode | BaseAssertionNode | QuantifierNode;
export type BranchNode =
| GroupAssertionNode
| GroupNode
| CharRangeNode
| CharClassNode
| RepeatNode
| ListNode
| DisjunctionNode;
/** Union of all RegExp syntax nodes */
export type Node = LeafNode | BranchNode;
/** Only top expr node types */
export type Expr = Exclude<Node, CharRangeNode | QuantifierNode>;
export class RegexFlags {
public readonly unicode: boolean = false;
public readonly dotAll: boolean = false;
public readonly global: boolean = false;
public readonly ignoreCase: boolean = false;
public readonly multiline: boolean = false;
public readonly sticky: boolean = false;
public readonly extended: boolean = false;
static parse(flags: string): RegexFlags;
static parse(flags: string, strict: true): K.Result<RegexFlags, string>;
static parse(flags: string, strict: boolean = false): RegexFlags | K.Result<RegexFlags, string> {
let reFlag = new RegexFlags() as K.Writable<RegexFlags>;
let invalid = [];
for (let c of flags) {
let p = RegexFlags.flagMap.get(c);
if (p) {
reFlag[p] = true;
} else {
invalid.push(c);
}
}
if (strict) {
if (invalid.length) {
return {error: K.sortUnique(invalid).join('')};
} else {
return {value: reFlag};
}
}
return reFlag;
}
static create(props?: {[K in UT.NonFunctionKeys<RegexFlags>]?: boolean}): RegexFlags {
let a = new RegexFlags();
if (props) {
Object.assign(a, props);
}
return a;
}
toString() {
let map = RegexFlags.invFlagMap;
let keys = Array.from(map.keys()).sort();
let flags = '';
for (let k of keys) {
if (this[k]) {
flags += map.get(k);
}
}
return flags;
}
static readonly flagMap = new Map<string, UT.NonFunctionKeys<RegexFlags>>([
['u', 'unicode'],
['g', 'global'],
['i', 'ignoreCase'],
['s', 'dotAll'],
['m', 'multiline'],
['y', 'sticky'],
['x', 'extended']
]);
static readonly invFlagMap = K.invertMap(RegexFlags.flagMap);
}
export interface Regex {
expr: Expr;
flags: RegexFlags;
source: string;
}
export function isBaseCharClass(node: Node): node is CharClassEscapeNode;
export function isBaseCharClass(node: NodeF<any>): node is CharClassEscapeNode;
export function isBaseCharClass(node: NodeF<any>): node is CharClassEscapeNode {
return node.type === 'CharClassEscape' && typeof node.charClass === 'string';
}
export function isAssertion(node: Node): node is AssertionNode;
export function isAssertion<X>(node: NodeF<X>): node is SubstIn<AssertionNode, Node, X>;
export function isAssertion<X>(node: NodeF<X>): node is SubstIn<AssertionNode, Node, X> {
return node.type === 'BaseAssertion' || node.type === 'GroupAssertion';
}
export function isEmptyNode(node: Node): node is ListNode;
export function isEmptyNode<X = any>(node: NodeF<X>): node is SubstIn<ListNode, Node, X>;
export function isEmptyNode<X = any>(node: NodeF<X>): node is SubstIn<ListNode, Node, X> {
if (node.type === 'List') {
return !node.body.length;
} else {
return false;
}
}
export function makeEmptyNode(position?: number): ListNode;
export function makeEmptyNode<X = any>(position?: number): SubstIn<ListNode, Node, X>;
export function makeEmptyNode<X = any>(position = 0): SubstIn<ListNode, Node, X> {
return {type: 'List', body: [], range: [position, position]};
}
const _BranchNodeTypeTuple = [
'GroupAssertion',
'Group',
'Repeat',
'List',
'Disjunction',
'CharClass',
'CharRange'
] as const;
export const BranchNodeTypeTuple: BranchNode['type'] extends typeof _BranchNodeTypeTuple[number]
? typeof _BranchNodeTypeTuple
: never = _BranchNodeTypeTuple; // The type is only used to assert the tuple included all BranchNode types.
export const BranchNodeTypeSet = new Set<BranchNode['type']>(BranchNodeTypeTuple);
export function isBranchNode(n: Node): n is BranchNode;
export function isBranchNode<X>(n: NodeF<X>): n is SubstIn<BranchNode, Node, X>;
export function isBranchNode<X>(n: NodeF<X>): n is SubstIn<BranchNode, Node, X> {
return BranchNodeTypeSet.has(n.type as any);
}
export interface INode extends NodeBase {
type: Node['type'];
}
export type PickByNodeType<N extends INode, T extends Node['type']> = N extends {type: T} ? N : never;
export type NodeOfType<T extends INode['type']> = PickByNodeType<Node, T>;
type VisitorFn<N extends INode, K extends N['type']> = (cur: PickByNodeType<N, K>, parent?: N) => void;
type VisitorCase<N extends INode, K extends N['type']> =
| VisitorFn<N, K>
| {
enter: VisitorFn<N, K>;
leave: VisitorFn<N, K>;
};
/**
Simple stateful visitor function executed top down or custom enter leave
*/
export type FullVisitor<N extends INode = Node> = {[K in N['type']]: VisitorCase<N, K>};
export type Visitor<N extends INode = Node> =
| FullVisitor<N>
| (UT.DeepPartial<FullVisitor<N>> & {defaults: VisitorCase<N, N['type']>});
export type FullMatchClause<A, B, N extends INode = Node> = {
[K in N['type']]: ((node: A extends N ? PickByNodeType<N, K> : SubstIn<PickByNodeType<N, K>, N, A>) => B);
};
export type MatchClause<A, B, N extends INode = Node> =
| FullMatchClause<A, B, N>
| (Partial<FullMatchClause<A, B, N>> & {defaults: (node: A extends N ? N : SubstIn<N, N, A>) => B});
export type NodeF<X, N = Node> = SubstIn<N, N, X>;
/**
Shallow dispatch visitor function by Node's type.
*/
export function match<T>(node: Node, clause: MatchClause<Node, T>): T;
export function match<A, B>(node: NodeF<A>, clause: MatchClause<A, B>): B;
export function match<N extends INode, A, B>(node: N, clause: MatchClause<A, B, N>): B;
export function match<T>(node: Node, clause: MatchClause<Node, T, Node>): T {
let v = clause as any;
return (v[node.type] || v.defaults)(node as any);
}
export function fmap<T>(node: Node, f: (n: Node) => T): NodeF<T>;
export function fmap<T, N extends Node = Node>(node: N, f: (n: N) => T): NodeF<T, N>;
export function fmap<A, B, N extends Node = Node>(node: NodeF<A, N>, f: (n: A) => B): NodeF<B, N>;
export function fmap<A, B>(node: NodeF<A>, f: (n: A) => B): NodeF<B> {
if (isBranchNode(node)) {
if (node.type === 'CharRange') {
let n: SubstIn<CharRangeNode, Node, B> = Object.create(node);
n.begin = f(node.begin);
n.end = f(node.end);
return n;
} else if (node.type === 'CharClass' || node.type === 'Disjunction' || node.type === 'List') {
let n: SubstIn<CharClassNode | DisjunctionNode | ListNode, Node, B> = Object.create(node);
n.body = node.body.map(f);
return n;
} else {
let n: SubstIn<GroupAssertionNode | RepeatNode | GroupNode, Node, B> = Object.create(node);
n.body = f(node.body);
if (node.type === 'Repeat') {
(n as any).quantifier = f(node.quantifier);
}
return n;
}
} else {
return node;
}
}
/**
Bottom up transform node, aka Catamorphism.
*/
export function bottomUp<T, N extends Node = Node>(n: N, f: (n: NodeF<T, N>, parent?: N) => T): T {
function cata(n: N, parent?: N): T {
return f(fmap<T, N>(n, a => cata(a, n)), parent);
}
return cata(n);
}
/** Simple Node Tree stateful visit, default top down */
export function visit(node: Node, visitor: Visitor, parent?: Node): void;
export function visit<N extends Node>(node: N, visitor: Visitor<N>, parent?: N): void;
export function visit(node: Node, visitor: Visitor, parent?: Node): void {
let vf: VisitorCase<Node, any> = visitor[node.type] || (visitor as any).defaults;
if (typeof vf !== 'function') {
if (vf.enter) {
vf.enter(node, parent);
}
down();
if (vf.leave) {
vf.leave(node, parent);
}
} else {
vf(node, parent);
down();
}
function down() {
if (isBranchNode(node)) {
if (node.type === 'CharRange') {
visit(node.begin, visitor, node);
visit(node.end, visitor, node);
} else if (node.type === 'CharClass' || node.type === 'Disjunction' || node.type === 'List') {
node.body.forEach((n: Node) => visit(n, visitor, node));
} else {
visit(node.body, visitor, node);
if (node.type === 'Repeat') {
visit(node.quantifier, visitor, node);
}
}
}
}
}
export function indent(n: Node, indent: number): Node {
visit(n, {
defaults(node) {
node.range[0] += indent;
node.range[1] += indent;
}
});
return n;
}
export interface RegexGroupsInfo {
count: number;
names: Set<string>;
}
export function getGroupsInfo(re: Node, _renumber: boolean): RegexGroupsInfo;
export function getGroupsInfo(re: NodeF<any>, _renumber: boolean): RegexGroupsInfo;
export function getGroupsInfo(re: Node, _renumber = false): RegexGroupsInfo {
let groups = {count: 0, names: new Set<string>()};
visit(re, {
Group(n) {
if (n.behavior.type === 'Capturing') {
if (n.behavior.name) {
groups.names.add(n.behavior.name);
}
groups.count++;
if (_renumber) {
n.behavior.index = groups.count;
}
}
},
defaults() {}
});
return groups;
}
export function renumberGroups(re: Node): RegexGroupsInfo;
export function renumberGroups(re: NodeF<any>): RegexGroupsInfo;
export function renumberGroups(re: Node): RegexGroupsInfo {
return getGroupsInfo(re, true);
} | the_stack |
import {KeyStore, Signer} from "../../../types/ExternalInterfaces";
import {TezosNodeReader} from "../TezosNodeReader";
import {TezosNodeWriter} from "../TezosNodeWriter";
import * as TezosTypes from "../../../types/tezos/TezosChainTypes";
import {TezosContractUtils} from './TezosContractUtils';
import {ConseilQueryBuilder} from "../../../reporting/ConseilQueryBuilder";
import {TezosMessageUtils} from "../TezosMessageUtil";
import {ConseilOperator, ConseilServerInfo, ConseilQuery, ConseilSortDirection} from "../../../types/conseil/QueryTypes";
import {TezosConseilClient} from "../../../reporting/tezos/TezosConseilClient";
import {JSONPath} from "jsonpath-plus";
import BigNumber from "bignumber.js";
import FetchSelector from '../../../utils/FetchSelector';
const fetch = FetchSelector.fetch;
export namespace KalamintHelper {
export const artHouseAddress: string = "KT1EpGgjQs73QfFJs9z7m1Mxm5MTnpC2tqse";
export const auctionFactoryAddress: string = "KT1MiSxkVDFDrAMYCZZXdBEkNrf1NWzfnnRR";
export const ledgerMapId: number = 857;
export const metadataMapId: number = 860;
export const tokenMapId: number = 861;
export type Auctions = { [ id: number]: string };
export interface KalamintStorage {
administrator: string;
allCollections: number;
allTokens: number;
auctionsFactory: string;
auctions: Auctions;
biddingFee: number;
collections: number;
idMaxIncrement: number;
ipfsRegistry: string;
ledger: number;
maxEditions: number;
maxRoyalty: number;
metadata: number;
operators: number;
paused: boolean;
tokenMetadata: number;
tokens: number;
tradingFee: number;
tradingFeeCollector: string;
x: number;
}
/*
* Get an instance of the Kalamint contract's storage.
*
* @param server The Tezos node to communicate with
* @param address Contract address, i.e. KalamintHelper.kalamintAddress
*/
export async function getStorage(server: string, address: string): Promise<KalamintStorage> {
const storageResult = await TezosNodeReader.getContractStorage(server, address);
const auctionsArray = JSONPath({path: '$.args[0].args[0].args[3]', json: storageResult })[0];
let auctions: Auctions = {};
for (const elt of auctionsArray) {
auctions[elt.args[0].int] = elt.args[1].string;
}
return {
administrator: JSONPath({path: '$.args[0].args[0].args[0].args[0].string', json: storageResult })[0],
allCollections: JSONPath({path: '$.args[0].args[0].args[0].args[1].int', json: storageResult })[0],
allTokens: JSONPath({path: '$.args[0].args[0].args[1].int', json: storageResult })[0],
auctionsFactory: JSONPath({path: '$.args[0].args[0].args[2].string', json: storageResult })[0],
auctions: auctions,
biddingFee: JSONPath({path: '$.args[0].args[1].args[0].int', json: storageResult })[0],
collections: JSONPath({path: '$.args[0].args[1].args[1].int', json: storageResult })[0],
idMaxIncrement: JSONPath({path: '$.args[0].args[2].int', json: storageResult })[0],
ipfsRegistry: JSONPath({path: '$.args[0].args[3].string', json: storageResult })[0],
ledger: JSONPath({path: '$.args[0].args[4].int', json: storageResult })[0],
maxEditions: JSONPath({path: '$.args[1].args[0].args[0].int', json: storageResult })[0],
maxRoyalty: JSONPath({path: '$.args[1].args[0].args[1].int', json: storageResult })[0],
metadata: JSONPath({path: '$.args[1].args[1].int', json: storageResult })[0],
operators: JSONPath({path: '$.args[1].args[3].int', json: storageResult })[0],
paused: JSON.parse(JSONPath({path: '$.args[2].args[0].prim', json: storageResult })[0].toLowerCase()),
tokenMetadata: JSONPath({path: '$.args[2].args[1].int', json: storageResult })[0],
tokens: JSONPath({path: '$.args[2].args[2].int', json: storageResult })[0],
tradingFee: JSONPath({path: '$.args[3].int', json: storageResult })[0],
tradingFeeCollector: JSONPath({path: '$.args[4].int', json: storageResult })[0],
x: JSONPath({path: '$.args[5].int', json: storageResult })[0]
};
}
export interface BidPair {
tokenId: number;
amount: number;
}
/*
* Submit bid to the Kalamint contract
*
* @param bid Invocation parameters
*/
export async function bid(server: string, address: string, signer: Signer, keystore: KeyStore, bid: BidPair ,fee: number, gas: number = 800_000, freight: number = 20_000): Promise<string> {
const entryPoint = 'bid';
const parameters = `${bid.tokenId}`;
const nodeResult = await TezosNodeWriter.sendContractInvocationOperation(server, signer, keystore, address, bid.amount, fee, freight, gas, entryPoint, parameters, TezosTypes.TezosParameterFormat.Michelson);
return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID);
}
export interface BuyPair {
tokenId: number;
amount: number;
}
/*
* Buy NFT from the Kalamint contract
*
* @param buy Invocation parameters
*/
export async function buy(server: string, address: string, signer: Signer, keystore: KeyStore, buy: BuyPair, fee: number, gas: number = 800_000, freight: number = 20_000): Promise<string> {
const entryPoint = 'buy';
const parameters = `{"int": "${buy.tokenId}"}`;
const nodeResult = await TezosNodeWriter.sendContractInvocationOperation(server, signer, keystore, address, buy.amount, fee, freight, gas, entryPoint, parameters, TezosTypes.TezosParameterFormat.Micheline);
return TezosContractUtils.clearRPCOperationGroupHash(nodeResult.operationGroupID);
}
/*
* Collection metadata
*
* @param collectionName
* @param creatorName
* @param creatorAddress
* @param editionNumber
* @param editions
*/
export interface CollectionInfo {
collectionName: string;
creatorName: string;
creatorAddress: string;
editionNumber: number;
editions: number;
}
/*
* Representation of a Kalamint artwork
*
* @param tokenId The FA2 token Id of the artwork
* @param name Artwork's name
* @param description Artwork's description
* @param collection The metadata for the collection to which the artwork belongs
* @param currentPrice The price for which it is currently on sale for
* @param onSale Indicator for if the artwork is currently on sale
* @param onAuction Indicator for if an auction is currently active for the artwork
* @param metadataURI IPFS URI for Artwork's metadata
* @param artifactURI IPFS URI for Artwork's artifact
*/
export interface Artwork {
tokenId: number;
name: string;
description: string | undefined;
acquisition: InvocationMetadata;
collection: CollectionInfo;
currentPrice: BigNumber;
onSale: boolean;
onAuction: boolean;
metadataURI: string;
artifactURI: string;
}
/*
* Retreives the collection of tokens owned by managerAddress.
*
* @param ledgerMapId
* @param tokenMapId
* @param metadataMapId
* @param address
* @param serverInfo
*/
export async function getArtworks(ledgerMapId: number, tokenMapId: number, metadataMapId: number, address: string, serverInfo: ConseilServerInfo): Promise<Artwork[]> {
// get all assets of address from the ledger
const operationsQuery = makeOperationsQuery(address, ledgerMapId);
const operationsResult = await TezosConseilClient.getTezosEntityData(serverInfo, serverInfo.network, 'big_map_contents', operationsQuery);
const operationGroupIds = operationsResult.map((r) => r.operation_group_id);
const operationChunks = chunkArray(operationGroupIds, 30);
// save each tokenId's invocation
const invocations = {};
operationsResult.map((row) => invocations[row.key.replace(/.* ([0-9]{1,})/, '$1')] = row.operation_group_id);
const invocationChunks = chunkArray(Object.entries(invocations).map(([id, operation]) => id), 30);
// fetch and save each invocation's metadata
const invocationMetadataQueries = operationChunks.map((c) => makeInvocationMetadataQuery(c));
const invocationMetadata = {};
// winning bids need to be queried for internal operations
const endAuctionOperations: string[] = [];
await Promise.all(
invocationMetadataQueries.map(async (q) => {
const invocationsResult = await TezosConseilClient.getTezosEntityData(serverInfo, serverInfo.network, 'operations', q);
invocationsResult.map(async (row) => {
const metadata: InvocationMetadata = await parseInvocationMetadataResult(row);
// save which bids need to be retrieved
if (metadata.amount === undefined)
endAuctionOperations.push(row.operation_group_hash);
invocationMetadata[row.operation_group_hash] = metadata;
});
}));
// get winning bid amounts from internal operations
const endAuctionChunks = chunkArray(endAuctionOperations, 30);
const endAuctionQueries = endAuctionChunks.map((c) => makeEndAuctionQuery(c));
await Promise.all(
endAuctionQueries.map(async (q) => {
const endAuctionResult = await TezosConseilClient.getTezosEntityData(serverInfo, serverInfo.network, 'operations', q);
endAuctionResult.map((row) => invocationMetadata[row.operation_group_hash].price = parseEndAuctionResult(row));
})
);
// get token metadata
const tokenMetadataQueries = invocationChunks.map((c) => [makeTokenQuery(tokenMapId, c), makeTokenQuery(metadataMapId, c)]);
const artworks: Artwork[] = [];
await Promise.all(
tokenMetadataQueries.map(async ([tokenQuery, metadataQuery]) => {
const tokenResult = await TezosConseilClient.getTezosEntityData(serverInfo, serverInfo.network, 'big_map_contents', tokenQuery);
const metadataResult = await TezosConseilClient.getTezosEntityData(serverInfo, serverInfo.network, 'big_map_contents', metadataQuery);
// zip the results into artworks
tokenResult.map((row, i) => {
const metadataURI: string = parseMetadataResult(metadataResult[i]);
artworks.push(parseTokenResult(row, invocations, invocationMetadata, metadataURI));
});
}));
// return assets sorted chronlogically
return artworks.sort((a, b) => b.acquisition.timestamp.getTime() - a.acquisition.timestamp.getTime());
}
/*
* Craft the query for operations from the ledger big map
*
* @param address The address for which to query data
* @param ledgerMapId The ledger big map id
*/
function makeOperationsQuery(address: string, ledgerMapId: number): ConseilQuery {
let operationsQuery = ConseilQueryBuilder.blankQuery();
operationsQuery = ConseilQueryBuilder.addFields(operationsQuery, 'key', 'value', 'operation_group_id');
operationsQuery = ConseilQueryBuilder.addPredicate(operationsQuery, 'big_map_id', ConseilOperator.EQ, [ledgerMapId]);
operationsQuery = ConseilQueryBuilder.addPredicate(operationsQuery, 'key', ConseilOperator.STARTSWITH, [
`Pair 0x${TezosMessageUtils.writeAddress(address)}`,
]);
operationsQuery = ConseilQueryBuilder.addPredicate(operationsQuery, 'value', ConseilOperator.EQ, [0], true);
operationsQuery = ConseilQueryBuilder.setLimit(operationsQuery, 10_000);
return operationsQuery;
}
/*
* Returns a query for the last price.
*
* @param operations Array of chunks of operations (see `chunkArray()`)
*/
function makeInvocationMetadataQuery(operations: ConseilQuery[]): ConseilQuery {
let invocationsQuery = ConseilQueryBuilder.blankQuery();
invocationsQuery = ConseilQueryBuilder.addFields(invocationsQuery, 'timestamp', 'amount', 'operation_group_hash', 'parameters_entrypoints');
invocationsQuery = ConseilQueryBuilder.addPredicate(invocationsQuery, 'kind', ConseilOperator.EQ, ['transaction']);
invocationsQuery = ConseilQueryBuilder.addPredicate(invocationsQuery, 'status', ConseilOperator.EQ, ['applied']);
invocationsQuery = ConseilQueryBuilder.addPredicate(invocationsQuery, 'internal', ConseilOperator.EQ, ['false']);
invocationsQuery = ConseilQueryBuilder.addPredicate(
invocationsQuery,
'operation_group_hash',
operations.length > 1 ? ConseilOperator.IN : ConseilOperator.EQ,
operations
);
invocationsQuery = ConseilQueryBuilder.setLimit(invocationsQuery, operations.length);
return invocationsQuery;
}
/*
* The parsed results of invocation metadata queries
*
* @param entryPoint The entrypoint invoked
* @param amount The purchase price or winning bid (0 if minted or transfered)
* @param timestamp Invocation timestamp
*/
interface InvocationMetadata {
entryPoint: string;
amount: BigNumber | undefined;
timestamp: Date;
}
/*
* Parse the results of the invocation metadata queries
*
* @param row
*/
async function parseInvocationMetadataResult(row): Promise<InvocationMetadata> {
let entryPoint = row.parameters_entrypoints;
// parse purchase or winning bid price
let price: BigNumber | undefined;
if (entryPoint === 'buy') {
price = new BigNumber(parseInt(row.amount));
} else if (entryPoint === 'resolve_auction') {
// need to get winning bid operation
price = undefined;
} else
price = new BigNumber(0);
return {
entryPoint: entryPoint,
amount: price,
timestamp: new Date(row.timestamp)
};
}
/*
* Craft the query for the winning bid
*
* @param operations Array of chunks of operations (see `chunkArray()`)
*/
function makeEndAuctionQuery(operations: string[]): ConseilQuery {
let endAuctionQuery = ConseilQueryBuilder.blankQuery();
endAuctionQuery = ConseilQueryBuilder.addFields(endAuctionQuery, 'amount', 'operation_group_hash');
endAuctionQuery = ConseilQueryBuilder.addPredicate(endAuctionQuery, 'internal', ConseilOperator.EQ, ['true'])
endAuctionQuery = ConseilQueryBuilder.addPredicate(endAuctionQuery, 'parameters_entrypoints', ConseilOperator.EQ, ['end_auction'])
endAuctionQuery = ConseilQueryBuilder.addPredicate(
endAuctionQuery,
'operation_group_hash',
operations.length > 1 ? ConseilOperator.IN : ConseilOperator.EQ,
operations
);
endAuctionQuery = ConseilQueryBuilder.setLimit(endAuctionQuery, operations.length);
return endAuctionQuery;
}
/*
* Parse the winning bid query results
*
* @param row
*/
function parseEndAuctionResult(row): BigNumber {
return new BigNumber(row.amount);
}
/*
* Craft the query for the token metadata
*
* @param tokenMapId The token bigmap id
* @param tokenIds The array of token ids to query data for
*/
function makeTokenQuery(tokenMapId: number, tokenIds: number[]): ConseilQuery {
let tokensQuery = ConseilQueryBuilder.blankQuery();
tokensQuery = ConseilQueryBuilder.addFields(tokensQuery, 'key', 'value', 'operation_group_id');
tokensQuery = ConseilQueryBuilder.addPredicate(tokensQuery, 'big_map_id', ConseilOperator.EQ, [tokenMapId]);
tokensQuery = ConseilQueryBuilder.addPredicate(
tokensQuery,
'key',
tokenIds.length > 1 ? ConseilOperator.IN : ConseilOperator.EQ,
tokenIds);
tokensQuery = ConseilQueryBuilder.setLimit(tokensQuery, tokenIds.length);
return tokensQuery;
}
/*
* Parse the results of the metadata map queries for the IPFS URI
*
* @param row
*/
function parseMetadataResult(row): string {
const metadataURIBytes = row.value.toString().replace(/.*? 0x([a-zA-Z0-9]*).*/, '$1');
return TezosMessageUtils.readString(metadataURIBytes).slice(3); // get rid of leading `://`
}
/*
* Parse the results of the token map queries
*
* @param row
* @param invocations Map from tokenId -> operationGroupId
* @param invocationsMetadata Map from operationGroupId -> InvocationMetadata
* @param metadataURI IPFS URI for token metadata
*/
function parseTokenResult(row, invocations, invocationsMetadata, metadataURI: string): Artwork {
let tokenId = parseInt(row.key);
let invocationOperation = invocations[tokenId];
let invocationMetadata = invocationsMetadata[invocationOperation];
return {
tokenId: parseInt(row.key),
name: row.value.toString().replace(/.* \"name\" "(.*?)" .*/, '$1'),
description: undefined,
acquisition: invocationMetadata,
collection: {
collectionName: row.value.toString().replace(/.* "collection_name" "(.*?)" .*/, '$1'),
creatorName: row.value.toString().replace(/.* "creator_name" "(.*?)" .*/, '$1'),
editions: parseInt(row.value.toString().replace(/.* ([0-9]*?) }/, '$1')),
editionNumber: parseInt(row.value.toString().replace(/.* ([0-9]*?) ; [0-9]* }/, '$1'))
} as CollectionInfo,
currentPrice: new BigNumber(parseInt(row.value.toString().replace(/.* } ; [0-9]+ ; ([0-9]*?) .*/, '$1'))),
onSale: row.value.toString().replace(/.* "ipfs:.*" ; .*? ; \b(False|True)\b .*/, '$1').toLowerCase().startsWith('t'),
onAuction: row.value.toString().replace(/.* "ipfs:.*" ; .*? ; \b(False|True)\b ; \b(False|True)\b.*/, '$2').toLowerCase().startsWith('t'),
metadataURI: metadataURI,
artifactURI: row.value.toString().replace(/.* \"ipfs:\\\/\\\/([a-zA-Z0-9]*?)" .*/, '$1')
}
}
/*
* Represents a transaction
*
* @param source
* @param destination
* @param invocation
* @param operationGroupHash
* @param fee
*/
export interface Transaction {
source: string;
destination: string;
invocation: InvocationMetadata;
operationGroupHash: string;
fee: BigNumber;
}
/*
* Get the Kalamint transactions for the given address
*
* @param artHouseAddress
* @param auctionFactoryAddress
* @param address
* @param serverInfo
*/
export async function getTokenTransactions(artHouseAddress: string, auctionFactoryAddress: string, address: string, serverInfo: ConseilServerInfo): Promise<Transaction[]> {
const direct: ConseilQuery = makeDirectTxQuery(address, [artHouseAddress, auctionFactoryAddress]);
const indirect: ConseilQuery = makeIndirectTxQuery(address, artHouseAddress);
let transactions: Transaction[] = [];
await Promise.all([direct, indirect].map(async (q) => {
const transactionsResult = await TezosConseilClient.getOperations(serverInfo, serverInfo.network, q);
transactionsResult.map((row) => transactions.push(parseTransactionsQuery(row)));
}));
return transactions.sort((a, b) => a.invocation.timestamp.getTime() - b.invocation.timestamp.getTime());
}
/*
* Craft the query for transactions made by address
*
* @param address The source address for transaction
* @param contracts Array with the relevant contracts (e.g. ArtHouse, AuctionFactory)
*/
function makeDirectTxQuery(address: string, contracts: string[]): ConseilQuery {
let direct = ConseilQueryBuilder.blankQuery();
direct = ConseilQueryBuilder.addFields(direct,
'timestamp',
'source',
'destination',
'amount',
'fee',
'operation_group_hash',
'parameters_entrypoints');
direct = ConseilQueryBuilder.addPredicate(direct, 'kind', ConseilOperator.EQ, ['transaction'], false);
direct = ConseilQueryBuilder.addPredicate(direct, 'status', ConseilOperator.EQ, ['applied'], false);
direct = ConseilQueryBuilder.addPredicate(direct, 'destination', ConseilOperator.IN, contracts, false);
direct = ConseilQueryBuilder.addPredicate(direct, 'source', ConseilOperator.EQ, [address], false);
direct = ConseilQueryBuilder.addOrdering(direct, 'timestamp', ConseilSortDirection.DESC);
direct = ConseilQueryBuilder.setLimit(direct, 5_000);
return direct;
}
/*
* Craft the query for transactions made to contractAddress that affect address
*
* @param address The affected address
* @param contractAddress The Kalamint contract address
*/
function makeIndirectTxQuery(address: string, contractAddress: string): ConseilQuery {
let indirect = ConseilQueryBuilder.blankQuery();
indirect = ConseilQueryBuilder.addFields(indirect,
'timestamp',
'source',
'destination',
'amount',
'fee',
'operation_group_hash',
'parameters_entrypoints');
indirect = ConseilQueryBuilder.addPredicate(indirect, 'kind', ConseilOperator.EQ, ['transaction'], false);
indirect = ConseilQueryBuilder.addPredicate(indirect, 'status', ConseilOperator.EQ, ['applied'], false);
indirect = ConseilQueryBuilder.addPredicate(indirect, 'destination', ConseilOperator.EQ, [contractAddress], false);
indirect = ConseilQueryBuilder.addPredicate(indirect, 'parameters', ConseilOperator.LIKE, [address], false);
indirect = ConseilQueryBuilder.addOrdering(indirect, 'timestamp', ConseilSortDirection.DESC);
indirect = ConseilQueryBuilder.setLimit(indirect, 5_000);
return indirect
}
/*
* Parse direct and indirect transaction queries
*
* @param row
*/
function parseTransactionsQuery(row): Transaction {
let invocationMetadata: InvocationMetadata = {
entryPoint: row.parameters_entrypoints,
amount: new BigNumber(row.amount),
timestamp: new Date(row.timestamp)
};
return {
source: row.source,
destination: row.destination,
invocation: invocationMetadata,
operationGroupHash: row.operation_group_hash,
fee: new BigNumber(row.fee)
};
}
/*
* Populate an Artwork's description and artifact from IPFS
*
* @param artwork The Artwork object
*/
export async function getArtworkDescription(artwork: Artwork): Promise<Artwork> {
const metadata = await fetch(`https://cloudflare-ipfs.com/ipfs/${artwork.metadataURI}`, { cache: 'no-store' });
const metadataJSON = await metadata.json();
artwork.description = metadataJSON.description;
return artwork;
}
/*
* Turn an array of n=k*len elements into an array of k arrays of length len.
*
* @param arr
* @param len
*/
function chunkArray(arr: any[], len: number) {
const chunks: any[] = [];
const n = arr.length;
let i = 0;
while (i < n) {
chunks.push(arr.slice(i, (i += len)));
}
return chunks;
}
} | the_stack |
export interface A { readonly name: string }
export interface B { readonly id: number }
export namespace N {
/** get */
const v1: string;
/** get */
const f1: (value: string) => number;
/** get */
const f2: <T>(value: T) => number;
/** get */
const f3: <T>(value: string) => T;
/** get */
const f4: <T>(value: T) => T;
/** get, set */
let f5: <T>(value: T) => T;
/** get, set */
var f6: <T>(value: T) => T;
/** get */
const f7: <T>(v1: T, v2: T) => T;
/** get */
const f8: <T>(v1: T | string, v2: string | number | T) => T;
/** get */
const f9: <T>(f1: ((v1: T, v2: T) => T), f2: ((v1: string | T, v2: T | number) => string | T)) => T | string
/** get, set */
let f10: <T>(f1: ((v1: T, v2: T) => T), f2: ((v1: string | T, v2: T | number) => string | T)) => T | string
/** get */
const f11: <T>(v1: T, v2: T) => T;
/** get, set */
let f12: <T>(v1: T, v2: T) => T;
/** get */
const f13: (v1: string, v2: string) => string;
/** get, set */
let f14: (v1: string, v2: string) => string;
/**
* get
*
* T extends A
*/
const gf1: <T extends A>(value: T) => T
/**
* get, set
*
* T extends A
*/
let gf2: <T extends A>(value: T) => T
/**
* get
*
* T extends A
*/
const gf3: <T extends A>(v1: T, v2: T) => T
/**
* get, set
*
* T extends A
*/
let gf4: <T extends A>(v1: T, v2: T) => T
/**
* get
*
* T extends A
* U extends A & B
*/
const gf5: <T extends A, U extends A & B>(v1: T, v2: U) => U
/**
* get, set
*
* T extends A
* U extends A & B
*/
let gf6: <T extends A, U extends A & B>(v1: T, v2: U) => U
/** get */
const arrayify: <T>(obj: T | T[]) => T[];
/** get */
const izi1: (v1: string, v2: string) => void;
/** get, set */
let izi3: (v1: string, v2: string) => void;
/** get */
const izi4: <T>(v1: T, v2: T) => T;
/** get, set */
let izi5: <T>(v1: T, v2: T) => T;
/** get */
const t1: [string, string];
/** get */
const ft1: <T>(vs: [T, T]) => T;
/** get, set */
let ft2: <T>(vs: [T, T]) => T;
/**
* get
*
* v2 optional
*/
const o1: <T>(v1: T, v2?: T) => T;
/**
* get, set
*
* v2 optional
*/
let o2: <T>(v1: T, v2?: T) => T;
/**
* get
*
* v2 optional
*/
const o3: <T>(v1: T, v2?: [T, T]) => T;
/**
* get, set
*
* v2 optional
*/
let o4: <T>(v1: T, v2?: [T, T]) => T;
/** function */
function ff1<T>(f: ((value: T) => T)): ((value: T) => T);
/** function */
function ff2<T>(f: ((value: T) => T), v: T): string;
/** function */
function ff3<T>(v1: T, v2: T | string): T | number
}
export interface I {
/** get */
readonly v1: string;
/** get */
readonly f1: (value: string) => number;
/** get */
readonly f2: <T>(value: T) => number;
/** get */
readonly f3: <T>(value: string) => T;
/** get */
readonly f4: <T>(value: T) => T;
/** get, set */
f5: <T>(value: T) => T;
/** get, set */
f6: <T>(value: T) => T;
/** get */
readonly f7: <T>(v1: T, v2: T) => T;
/** get */
readonly f8: <T>(v1: T | string, v2: string | number | T) => T;
/** get */
readonly f9: <T>(f1: ((v1: T, v2: T) => T), f2: ((v1: string | T, v2: T | number) => string | T)) => T | string
/** get, set */
f10: <T>(f1: ((v1: T, v2: T) => T), f2: ((v1: string | T, v2: T | number) => string | T)) => T | string
/** get */
readonly f11: <T>(v1: T, v2: T) => T;
/** get, set */
f12: <T>(v1: T, v2: T) => T;
/** get */
readonly f13: (v1: string, v2: string) => string;
/** get, set */
f14: (v1: string, v2: string) => string;
/**
* get
*
* T extends A
*/
readonly gf1: <T extends A>(value: T) => T
/**
* get, set
*
* T extends A
*/
gf2: <T extends A>(value: T) => T
/**
* get
*
* T extends A
*/
readonly gf3: <T extends A>(v1: T, v2: T) => T
/**
* get, set
*
* T extends A
*/
gf4: <T extends A>(v1: T, v2: T) => T
/**
* get
*
* T extends A
* U extends A & B
*/
readonly gf5: <T extends A, U extends A & B>(v1: T, v2: U) => U
/**
* get, set
*
* T extends A
* U extends A & B
*/
gf6: <T extends A, U extends A & B>(v1: T, v2: U) => U
/** get */
readonly arrayify: <T>(obj: T | T[]) => T[];
/** get */
readonly izi1: (v1: string, v2: string) => void;
/** get, set */
izi3: (v1: string, v2: string) => void;
/** get */
readonly izi4: <T>(v1: T, v2: T) => T;
/** get, set */
izi5: <T>(v1: T, v2: T) => T;
/** get */
readonly t1: [string, string];
/** get */
readonly ft1: <T>(vs: [T, T]) => T;
/** get, set */
ft2: <T>(vs: [T, T]) => T;
/**
* get
*
* v2 optional
*/
readonly o1: <T>(v1: T, v2?: T) => T;
/**
* get, set
*
* v2 optional
*/
o2: <T>(v1: T, v2?: T) => T;
/**
* get
*
* v2 optional
*/
readonly o3: <T>(v1: T, v2?: [T, T]) => T;
/**
* get, set
*
* v2 optional
*/
o4: <T>(v1: T, v2?: [T, T]) => T;
/**
* get
*
* optional
*/
readonly opt1?: string;
/**
* get, set
*
* optional
*/
opt2?: string;
// // F#: `abstract opt2: ('T -> 'T) option`
// // -> The type parameter 'T is not defined.
// // Note: same `with get, set` is allowed (but neither `with get` nor `with set`)
// /**
// * get
// *
// * optional
// */
// readonly opt3?: <T>(v1: T) => T;
/**
* get, set
*
* optional
*/
opt4?: <T>(v1: T) => T;
/**
* get
*
* optional
*/
readonly opt5?: (v1: string, v2: string) => string;
// /**
// * get
// *
// * optional
// */
// readonly opt6?: <T>(v1: T, v2: T) => T;
/**
* get, set
*
* optional
*/
opt7?: (v1: string, v2: string) => string;
/**
* get, set
*
* optional
*/
opt8?: <T>(v1: T, v2: T) => T;
/** function */
ff1<T>(f: ((value: T) => T)): ((value: T) => T);
/** function */
ff2<T>(f: ((value: T) => T), v: T): string;
/** function */
ff3<T>(v1: T, v2: T | string): T | number
}
export class C {
/** get */
readonly v1: string;
/** get */
readonly f1: (value: string) => number;
/** get */
readonly f2: <T>(value: T) => number;
/** get */
readonly f3: <T>(value: string) => T;
/** get */
readonly f4: <T>(value: T) => T;
/** get, set */
f5: <T>(value: T) => T;
/** get, set */
f6: <T>(value: T) => T;
/** get */
readonly f7: <T>(v1: T, v2: T) => T;
/** get */
readonly f8: <T>(v1: T | string, v2: string | number | T) => T;
/** get */
readonly f9: <T>(f1: ((v1: T, v2: T) => T), f2: ((v1: string | T, v2: T | number) => string | T)) => T | string
/** get, set */
f10: <T>(f1: ((v1: T, v2: T) => T), f2: ((v1: string | T, v2: T | number) => string | T)) => T | string
/** get */
readonly f11: <T>(v1: T, v2: T) => T;
/** get, set */
f12: <T>(v1: T, v2: T) => T;
/** get */
readonly f13: (v1: string, v2: string) => string;
/** get, set */
f14: (v1: string, v2: string) => string;
/**
* get
*
* T extends A
*/
readonly gf1: <T extends A>(value: T) => T
/**
* get, set
*
* T extends A
*/
gf2: <T extends A>(value: T) => T
/**
* get
*
* T extends A
*/
readonly gf3: <T extends A>(v1: T, v2: T) => T
/**
* get, set
*
* T extends A
*/
gf4: <T extends A>(v1: T, v2: T) => T
/**
* get
*
* T extends A
* U extends A & B
*/
readonly gf5: <T extends A, U extends A & B>(v1: T, v2: U) => U
/**
* get, set
*
* T extends A
* U extends A & B
*/
gf6: <T extends A, U extends A & B>(v1: T, v2: U) => U
/** get */
readonly arrayify: <T>(obj: T | T[]) => T[];
/** get */
readonly izi1: (v1: string, v2: string) => void;
/** get, set */
izi3: (v1: string, v2: string) => void;
/** get */
readonly izi4: <T>(v1: T, v2: T) => T;
/** get, set */
izi5: <T>(v1: T, v2: T) => T;
/** get */
readonly t1: [string, string];
/** get */
readonly ft1: <T>(vs: [T, T]) => T;
/** get, set */
ft2: <T>(vs: [T, T]) => T;
/**
* get
*
* v2 optional
*/
readonly o1: <T>(v1: T, v2?: T) => T;
/**
* get, set
*
* v2 optional
*/
o2: <T>(v1: T, v2?: T) => T;
/**
* get
*
* v2 optional
*/
readonly o3: <T>(v1: T, v2?: [T, T]) => T;
/**
* get, set
*
* v2 optional
*/
o4: <T>(v1: T, v2?: [T, T]) => T;
/** function */
ff1<T>(f: ((value: T) => T)): ((value: T) => T);
/** function */
ff2<T>(f: ((value: T) => T), v: T): string;
/** function */
ff3<T>(v1: T, v2: T | string): T | number
}
/** static */
export class CS {
/** get */
static readonly v1: string;
/** get */
static readonly f1: (value: string) => number;
/** get */
static readonly f2: <T>(value: T) => number;
/** get */
static readonly f3: <T>(value: string) => T;
/** get */
static readonly f4: <T>(value: T) => T;
/** get, set */
static f5: <T>(value: T) => T;
/** get, set */
static f6: <T>(value: T) => T;
/** get */
static readonly f7: <T>(v1: T, v2: T) => T;
/** get */
static readonly f8: <T>(v1: T | string, v2: string | number | T) => T;
/** get */
static readonly f9: <T>(f1: ((v1: T, v2: T) => T), f2: ((v1: string | T, v2: T | number) => string | T)) => T | string
/** get, set */
static f10: <T>(f1: ((v1: T, v2: T) => T), f2: ((v1: string | T, v2: T | number) => string | T)) => T | string
/** get */
static readonly f11: <T>(v1: T, v2: T) => T;
/** get, set */
static f12: <T>(v1: T, v2: T) => T;
/** get */
static readonly f13: (v1: string, v2: string) => string;
/** get, set */
static f14: (v1: string, v2: string) => string;
/**
* get
*
* T extends A
*/
static readonly gf1: <T extends A>(value: T) => T
/**
* get, set
*
* T extends A
*/
static gf2: <T extends A>(value: T) => T
/**
* get
*
* T extends A
*/
static readonly gf3: <T extends A>(v1: T, v2: T) => T
/**
* get, set
*
* T extends A
*/
static gf4: <T extends A>(v1: T, v2: T) => T
/**
* get
*
* T extends A
* U extends A & B
*/
static readonly gf5: <T extends A, U extends A & B>(v1: T, v2: U) => U
/**
* get, set
*
* T extends A
* U extends A & B
*/
static gf6: <T extends A, U extends A & B>(v1: T, v2: U) => U
/** get */
static readonly arrayify: <T>(obj: T | T[]) => T[];
/** get */
static readonly izi1: (v1: string, v2: string) => void;
/** get, set */
static izi3: (v1: string, v2: string) => void;
/** get */
static readonly izi4: <T>(v1: T, v2: T) => T;
/** get, set */
static izi5: <T>(v1: T, v2: T) => T;
/** get */
static readonly t1: [string, string];
/** get */
static readonly ft1: <T>(vs: [T, T]) => T;
/** get, set */
static ft2: <T>(vs: [T, T]) => T;
/**
* get
*
* v2 optional
*/
static readonly o1: <T>(v1: T, v2?: T) => T;
/**
* get, set
*
* v2 optional
*/
static o2: <T>(v1: T, v2?: T) => T;
/**
* get
*
* v2 optional
*/
static readonly o3: <T>(v1: T, v2?: [T, T]) => T;
/**
* get, set
*
* v2 optional
*/
static o4: <T>(v1: T, v2?: [T, T]) => T;
/** function */
static ff1<T>(f: ((value: T) => T)): ((value: T) => T);
/** function */
static ff2<T>(f: ((value: T) => T), v: T): string;
/** function */
static ff3<T>(v1: T, v2: T | string): T | number
} | the_stack |
import { WcCustomAction, WcCustomActionCase, WcCustomActionGrid, WcCustomActionShowMode } from '../../types/other';
import { MpEvent, MpViewContext, MpViewContextAny } from '../../types/view';
import { WeComponent } from '../mixins/component';
import { getCustomActions } from '../modules/custom-action';
import EbusMixin from '../mixins/ebus';
import { MpJSONViewerComponentEbusDetail } from '../../types/json-viewer';
import { DataGridCol, MpDataGridComponentExports } from '../../types/data-grid';
import { MpNameValue } from '../../types/common';
import { each } from '../../modules/util';
const NoUICaseId = '$$$NO_UI$$$';
WeComponent<MpViewContext & MpViewContextAny>(EbusMixin, {
properties: {
action: {
type: String,
observer() {
this.setAction();
}
}
},
data: {
caseList: [],
noUICaseList: [],
everyNoUI: false,
activeCaseIndex: 0,
caseState: {},
caseTabState: {
s0: 1
},
gridSelected: {}
},
methods: {
setAction() {
const actions = getCustomActions();
this.actionDetail = actions.find((item) => item.id === this.data.action);
if (!this.actionDetail) {
this.setData({
caseList: null,
noUICaseList: null,
caseState: {},
caseTabState: {
s0: 1
}
});
delete this.caseResultState;
return;
}
const action: WcCustomAction = this.actionDetail;
const noneCases: WcCustomActionCase[] = [];
const uiCases: WcCustomActionCase[] = [];
const buttonTexts: [MpNameValue<string>[], MpNameValue<string>[]] = [[], []];
action.cases.forEach((item) => {
const nv = {
name: item.button || item.id,
value: item.id
};
if (!item.showMode || item.showMode === WcCustomActionShowMode.none) {
noneCases.push(item);
buttonTexts[0].push(nv);
} else {
uiCases.push(item);
buttonTexts[1].push(nv);
}
});
let caseList: MpNameValue<string>[];
let noUICaseList: MpNameValue<string>[];
const everyNoUI: boolean = noneCases.length === action.cases.length;
if (noneCases.length <= 1) {
caseList = buttonTexts[0].concat(buttonTexts[1]);
noUICaseList = [];
} else {
noUICaseList = buttonTexts[0];
caseList = buttonTexts[1];
caseList.unshift({
name: '无界面',
value: NoUICaseId
});
}
this.setData({
everyNoUI,
caseList,
noUICaseList,
activeCaseIndex: 0,
caseTabState: {
s0: 1
},
gridSelected: {}
});
if (action.autoCase) {
this.changeCaseTab(action.autoCase);
this.execCase(action.autoCase);
}
},
tapCaseButton(e) {
this.execCase(e.currentTarget.dataset.id);
},
changeCaseTab(e: MpEvent | string) {
let caseId: string;
let caseIndex = -1;
if (typeof e === 'object' && e && e.currentTarget) {
const item = this.data.caseList[e.detail];
if (!item) {
return;
}
caseIndex = e.detail;
} else {
caseId = String(e);
}
const action: WcCustomAction = this.actionDetail as WcCustomAction;
if (!action) {
return;
}
if (caseIndex === -1) {
caseIndex = this.data.caseList.findIndex((item) => item.value === caseId);
if (caseIndex === -1) {
return;
}
}
this.setData({
activeCaseIndex: caseIndex,
[`caseTabState.s${caseIndex}`]: 1
});
},
execCase(id: string) {
const action: WcCustomAction = this.actionDetail as WcCustomAction;
if (!action) {
return;
}
const caseIndex = action.cases.findIndex((item) => item.id === id);
if (caseIndex === -1) {
return;
}
const caseItem = action.cases[caseIndex];
const show = (err: Error, res?: any) => {
if (!this.caseResultState) {
this.caseResultState = {};
}
this.caseResultState[caseItem.id] = {
res,
err
};
const state: any = {
mode: caseItem.showMode,
errMsg: err ? err.message : '',
errStack: err ? err.stack : ''
};
if (!err) {
if (caseItem.showMode === WcCustomActionShowMode.text) {
state.data = typeof res === 'object' ? JSON.stringify(res) : String(res);
} else if (caseItem.showMode === WcCustomActionShowMode.component) {
state.data = res;
} else if (caseItem.showMode === WcCustomActionShowMode.grid) {
const options: WcCustomActionGrid = res as WcCustomActionGrid;
state.cols = options.cols;
this.appendDataToGrid(caseItem.id, options.data);
} else if (caseItem.showMode === WcCustomActionShowMode.json) {
if (this?.caseJSONViewer && this.caseJSONViewer[caseItem.id]) {
this.caseJSONViewer[caseItem.id].setTarget(res);
this.caseJSONViewer[caseItem.id].openPath();
}
}
// else if (
// caseItem.showMode === WcCustomActionShowMode.jsonGrid
// ) {
// const options: WcCustomActionGrid =
// res as WcCustomActionGrid;
// state.cols = options.cols;
// const data: any[] = Array.isArray(options.data)
// ? options.data
// : [];
// let list = data;
// if (options.cols.some((item) => item.json)) {
// list = data.map((item) =>
// this.convertJSONGridItem(
// caseItem,
// item,
// options.cols
// )
// );
// }
// this.appendDataToGrid(caseItem.id, list);
// }
}
this.setData({
[`caseLoading.${caseItem.id}`]: false,
[`caseState.${caseItem.id}`]: state
});
};
const res = caseItem.handler();
if (typeof res === 'object' && res.then) {
this.setData({
[`caseLoading.${caseItem.id}`]: true
});
res.then((val) => show(null, val));
res.catch((err) => show(err));
} else {
show(null, res);
}
},
getCase(id: string) {
const action: WcCustomAction = this.actionDetail as WcCustomAction;
if (!action) {
return;
}
return action.cases.find((item) => item.id === id);
},
convertJSONGridItem(caseItem: WcCustomActionCase, item: any, cols: DataGridCol[]): any {
const res: any = {};
each(item, (prop, val) => {
const col = cols.find((c) => c.field === prop);
if (col?.json) {
res[prop] = {
json: 1,
key: `CustomAction_${caseItem.id}_${item.id}_${prop}`
};
} else {
res[prop] = val;
}
});
return res;
},
appendDataToGrid(caseId: string, data: any) {
if (this.caseGrid?.[caseId]) {
return (this.caseGrid[caseId] as MpDataGridComponentExports).replaceAllList(data);
}
},
tapGridCell(e) {
const caseId = e.currentTarget.dataset.case;
this.setData({
[`gridSelected.${caseId}`]: e.detail.rowId || ''
});
},
gridReady(e: MpEvent<MpDataGridComponentExports>) {
const caseId = e.currentTarget.dataset.case;
const caseItem = this.getCase(caseId);
if (!caseItem) {
return;
}
if (!this.caseGrid) {
this.caseGrid = {};
}
this.caseGrid[caseId] = e.detail;
e.detail.onJSONReady((data: MpJSONViewerComponentEbusDetail) => {
const { from, viewer } = data;
if (from?.startsWith('GridCol_CustomAction')) {
const [, , caseId, itemId, field] = from.split('_');
const list =
this?.caseResultState &&
this.caseResultState[caseId] &&
this.caseResultState[caseId]?.res &&
this.caseResultState[caseId]?.res?.data
? this.caseResultState[caseId].res.data
: [];
if (!this.caseResultState[caseId].JSONViewerMap) {
this.caseResultState[caseId].JSONViewerMap = {};
}
this.caseResultState[caseId].JSONViewerMap[field] = viewer;
const readyItem = list.find((item) => {
if (typeof item.id === 'number') {
return item.id === parseFloat(itemId);
}
return item.id === itemId;
});
if (readyItem) {
viewer.setTarget(readyItem[field]);
viewer.init();
}
}
});
if (
this?.caseResultState &&
this.caseResultState[caseId] &&
this.caseResultState[caseId]?.res &&
this.caseResultState[caseId]?.res?.data
) {
const list: any[] = this.caseResultState[caseId].res.data;
e.detail.replaceAllList(list);
// if (
// caseItem.showMode === WcCustomActionShowMode.jsonGrid &&
// this.data.caseState[caseItem.id].cols &&
// this.data.caseState[caseItem.id].cols.some(
// (item) => item.json
// )
// ) {
// e.detail.replaceAllList(
// list.map((item) =>
// this.convertJSONGridItem(
// caseItem,
// item,
// this.data.caseState[caseItem.id].cols
// )
// )
// );
// } else {
// }
}
}
},
attached() {
this.setAction();
// const action: WcCustomAction = {
// id: 'd1',
// cases: [
// {
// id: 'c1',
// showMode: WcCustomActionShowMode.none,
// handler: () => console.log('d1-c1')
// },
// {
// id: 'c2',
// showMode: WcCustomActionShowMode.none,
// handler: () => console.log('d1-c2')
// },
// {
// id: 'c2',
// showMode: WcCustomActionShowMode.json,
// handler: () => ({
// name: 'Tom'
// })
// }
// ]
// };
},
created() {
this.$wcOn('JSONViewerReady', (type, data: MpJSONViewerComponentEbusDetail) => {
if (
data.from.startsWith(`CustomAction_${this.data.action}`) &&
data.viewer.selectOwnerComponent &&
data.viewer.selectOwnerComponent() === this
) {
const caseId = data.from.split('_')[2];
const caseItem = this.getCase(caseId);
if (!caseItem) {
return;
}
if (!this.caseJSONViewer) {
this.caseJSONViewer = {};
}
this.caseJSONViewer[caseId] = data.viewer;
data.viewer.init().then(() => {
const caseItem = this.getCase(caseId);
if (!caseItem) {
return;
}
if (this?.caseResultState && this.caseResultState[caseItem.id]) {
data.viewer.setTarget(this.caseResultState[caseItem.id].res);
data.viewer.openPath();
}
});
}
});
}
}); | the_stack |
import { Market, Order } from 'ccxt';
import * as moment from 'moment';
import { logger } from '@src/logger';
import { Influx } from '@core/Influx/Influx';
import { MEASUREMENT_INPUTS } from '@core/Influx/constants';
import { EnvConfig, Env } from '@core/Env/Env';
import { CandleSet } from '@core/Env/CandleSet';
import { Candle } from '@core/Env/Candle';
import { Exchange } from './Exchange/Exchange';
import { Portfolio } from './Portfolio/Portfolio';
import { TraderModel } from './model';
import { flatten, requireUncached } from '../helpers';
import { PortfolioModel } from '@src/_core/Trader/Portfolio/model';
export interface TraderConfig {
name: string;
restart?: boolean;
silent?: boolean;
flush?: boolean;
persist?: boolean;
saveInputs?: boolean;
env: EnvConfig;
strategie: string;
stratOpts: any;
capital: number;
percentInvest: number;
test: boolean;
base: string;
quote: string;
exchange: {
name: string;
apiKey?: string;
apiSecret?: string;
};
}
export enum Status {
RUNNING = 'RUNNING',
STOP = 'STOP',
ERROR = 'ERROR',
}
/**
* Trader is use to run a strategy on the configured environment (live/simulation/backtest)
* This class take care of calculating different protfolio metric and flushing it to influxDB
*
* @export
* @class Trader
*/
export class Trader {
public env: Env;
public portfolio: Portfolio;
public status: Status;
public strategy: {
beforeAll?: (env: EnvConfig, trader: Trader, stratOpts: any) => Promise<void>;
before?: (candleSet: CandleSet, trader: Trader, stratOpts: any) => Promise<void>;
run: (candleSet: CandleSet, trader: Trader, stratOpts: any) => Promise<string>;
after?: (candleSet: CandleSet, trader: Trader, stratOpts: any) => Promise<void>;
afterAll?: (candleSet: CandleSet, trader: Trader, stratOpts: any) => Promise<void>;
};
// Hook can be usefull for ML algorithm (Override if after creating trader)
public afterStrategy: (candleSet: CandleSet | undefined, trader: Trader, error?: boolean) => Promise<void>;
private influx: Influx;
private symbol: string;
private exchange: Exchange;
private shouldStop: boolean = false;
// Buffer for writing candles data (with indicators) to influxDB
private bufferInputs: any[] = [];
private saveInputs: boolean;
private flushTimeout = 10;
private lastBufferFlush: number = new Date().getTime();
private persist: boolean;
private lastPersistTime: number = new Date().getTime();
constructor(public config: TraderConfig) {
this.symbol = Env.makeSymbol({
base: this.config.base,
exchange: this.config.exchange.name,
quote: this.config.quote,
});
this.config.flush = this.config.flush === false ? false : true;
this.saveInputs = this.config.saveInputs ? true : false;
this.persist = this.config.persist === false ? false : true;
}
/**
* Init the trader
* Bind the strategy, Init the environment, create the echange, create the portfolio
*
* @returns {Promise<void>}
* @memberof Trader
*/
public async init(): Promise<void> {
try {
// Bind trader strategy if needed (override allowed)
if (!this.strategy) {
// Reload strategy module
this.strategy = requireUncached(`${process.cwd()}/strategies/${this.config.strategie}`).default;
}
// beforeAll callback (can be use to change config or set fixed indicator for the strat)
if (this.strategy.beforeAll) await this.strategy.beforeAll(this.config.env, this, this.config.stratOpts);
// Smart aggTimes discovery (from plugin)
if (this.config.env.candleSetPlugins) {
const aggTimePlugins: any[] = this.config.env.candleSetPlugins.map(p => p.opts.aggTime).filter(agg => agg);
this.config.env.aggTimes = [...new Set(this.config.env.aggTimes.concat(aggTimePlugins))];
}
// Init Env
this.env = new Env(this.config.env);
this.influx = await this.env.init();
if (this.config.flush) await this.cleanInflux();
// Init exchange
this.exchange = new Exchange({
name: this.config.exchange.name,
test: this.config.test === true ? true : false,
apiKey: this.config.exchange.apiKey,
apiSecret: this.config.exchange.apiSecret,
});
// Init portfolio
this.portfolio = new Portfolio({
name: this.config.name,
capital: this.config.capital,
base: this.config.base,
quote: this.config.quote,
exchange: this.config.exchange.name,
backtest: this.config.env.backtest ? true : false,
});
if (this.config.restart) await this.portfolio.reload(this.influx, this.config.flush);
else await this.portfolio.init(this.influx, this.config.flush);
} catch (error) {
logger.error(error);
throw new Error(`[${this.config.name}] Problem during trader initialization`);
}
}
/**
* Stop the trader (stop environment)
*
* @returns {Promise<void>}
* @memberof Trader
*/
public async stop(status?: Status): Promise<void> {
if (this.status !== Status.STOP) {
this.status = status || Status.STOP;
this.shouldStop = true;
this.env.stop();
await this.portfolio.flush(true);
await this.flushInputs(true);
await this.save(true);
logger.info(`[${this.config.name}] Trader ${this.config.name} stopped`);
}
}
/**
* Start the trader, loop over environment candle generator
*
* @returns {Promise<void>}
* @memberof Trader
*/
public async start(): Promise<void> {
try {
// Set trader status and save
this.shouldStop = false;
this.status = Status.RUNNING;
await this.save(true);
logger.info(
`[${this.config.name}] Trader ${this.config.name} started on ${this.config.base}/${this.config.quote}`
);
// Get generator and fetch first candles (warmup)
const fetcher = this.env.getGenerator();
let data: { done: boolean; value: CandleSet | undefined } = { done: false, value: undefined };
let candleSet: CandleSet | undefined;
while (!this.shouldStop && !data.done) {
if (await this.checkTrader()) {
// Fetch data
data = await fetcher.next();
if (!data.done) {
candleSet = data.value as CandleSet;
const lastCandle = candleSet.getLast(this.symbol) as Candle;
// Push indicators to bufferInputs (will write it to influx)
if (this.saveInputs && Object.keys(lastCandle.indicators || {}).length > 0) {
// TODO Write multiple INPUT serie (ETH,BTC, ETH15m, BTC15m, ...)
// this.env.watchers.forEach ...
this.bufferInputs.push({
time: lastCandle.time,
values: flatten(lastCandle.indicators),
});
}
// Update portfolio with new candle
this.portfolio.update(lastCandle);
// Before strat callback
if (this.strategy.before) await this.strategy.before(candleSet, this, this.config.stratOpts);
// Run strategy
const advice = await this.strategy.run(candleSet, this, this.config.stratOpts);
// Check if advice is correct (cant buy more than one order at a time)
const error = this.checkAdvice(advice);
// Process advice (if error => wait)
if (!error) {
if (advice === 'buy') {
await this.buy(lastCandle);
} else if (advice === 'sell') {
await this.sell(lastCandle);
}
} else {
// WAIT
logger.info(error);
}
// After strat callback
if (this.strategy.after) await this.strategy.after(candleSet, this, this.config.stratOpts);
// Persist inputs/portfolio to influx
await this.flushInputs();
await this.portfolio.save();
}
}
}
// Strat finished
if (this.strategy.afterAll) await this.strategy.afterAll(candleSet as CandleSet, this, this.config.stratOpts);
// Stop trader (will flush buffers influx/mongo)
await this.stop();
} catch (error) {
await this.stop(Status.ERROR);
throw error;
}
}
/**
* Delete the trader related data from InfluxDB and MongoDB
*
* @returns {Promise<void>}
* @memberof Trader
*/
public async delete(): Promise<void> {
await this.stop();
await this.portfolio.cleanInflux();
await TraderModel.findOneAndDelete({ name: this.config.name });
await PortfolioModel.findOneAndDelete({ name: this.config.name });
}
/**
* Reset the portfolio
*
* @memberof Trader
*/
public resetPortfolio(): void {
this.portfolio.reset();
}
/**
* Check if trader can trade
*
* @private
* @memberof Trader
*/
private async checkTrader(): Promise<boolean> {
const errorHandler = (error: any) => {
throw error;
};
if (this.portfolio.indicators.currentProfit < -0.5) {
logger.info(`[${this.config.name}] Stop trader too much damage (50% deficit)`);
await this.stop().catch(errorHandler);
return false;
}
return true;
}
/**
* Helper check if advice is correct (follow buy/sell/buy/sell)
*
* @private
* @param {string} advice
* @memberof Trader
*/
private checkAdvice(advice: string): string | undefined {
let error;
if (advice === 'buy' && this.portfolio.trade) {
error = `[${this.config.name}] Trying to buy but there is already one order bought`;
}
if (advice === 'sell' && !this.portfolio.trade) {
error = `[${this.config.name}] Trying to sell but there is no order to sell`;
}
return error;
}
/**
* Buy an order
*
* @private
* @param {Candle} lastCandle
* @returns {Promise<void>}
* @memberof Trader
*/
private async buy(lastCandle: Candle): Promise<void> {
try {
const exchangeInfo: Market = await this.exchange.getExchangeInfo(
this.config.base,
this.config.quote,
this.config.env.backtest ? true : false
);
const minCost = exchangeInfo.limits.cost ? exchangeInfo.limits.cost.min : 0;
if (this.portfolio.indicators.currentCapital < minCost) {
logger.error(
`[${this.config.name}] Capital not sufficient to buy in market (${this.symbol}), currentCapital: ${
this.config.capital
}`
);
await this.stop();
}
const investExpected = this.portfolio.indicators.currentCapital * this.config.percentInvest;
const invest = investExpected < minCost ? minCost : investExpected;
const amount: number = +(invest / lastCandle.close).toFixed(8);
const order: Order = await this.exchange.buyMarket(this.config.base, this.config.quote, amount, lastCandle);
await this.portfolio.notifyBuy(order);
} catch (error) {
logger.error(error);
throw new Error(`[${this.config.name}] Problem while buying`);
}
}
/**
* Sell an order
*
* @private
* @param {Candle} lastCandle
* @returns {Promise<void>}
* @memberof Trader
*/
private async sell(lastCandle: Candle): Promise<void> {
if (this.portfolio.trade) {
try {
const order: Order = await this.exchange.sellMarket(
this.config.base,
this.config.quote,
this.portfolio.trade.orderBuy.amount,
lastCandle
);
await this.portfolio.notifySell(order);
} catch (error) {
logger.error(error);
throw new Error(`[${this.config.name}] Problem while selling`);
}
}
}
/**
* Save trader in MongoDB
*
* @memberof Trader
*/
private async save(force = false): Promise<void> {
if (this.persist && (force || Math.abs(moment().diff(this.lastPersistTime, 's')) > this.flushTimeout)) {
try {
const trader = { ...this.config, status: this.status };
await TraderModel.findOneAndUpdate({ name: this.config.name }, trader, { upsert: true });
await this.portfolio.persistMongo(true);
} catch (error) {
logger.error(error);
logger.error(new Error(`[${this.config.name}] Error while saving trader ${this.config.name}`));
}
// Reset timeout (even if error)
this.lastPersistTime = new Date().getTime();
}
}
/**
* Flush related data (portfolio/buy/sell/...)
*
* @private
* @param {boolean} [force=false]
* @returns {Promise<void>}
* @memberof Trader
*/
private async flushInputs(force: boolean = false): Promise<void> {
// If data to write and more than 5 second since last save (or force=true)
if (
this.bufferInputs.length > 0 &&
(force || Math.abs(moment().diff(this.lastBufferFlush, 's')) > this.flushTimeout)
) {
try {
await this.influx.writeData({ name: this.config.name }, this.bufferInputs, MEASUREMENT_INPUTS);
this.bufferInputs = [];
} catch (error) {
logger.error(error);
logger.error(
new Error(`[${this.config.name}] Error while saving candles to measurement ${MEASUREMENT_INPUTS}`)
);
}
// Reset timeout (even if error)
this.lastBufferFlush = new Date().getTime();
}
}
/**
* Clean influxDB data related to the trader
*
* @private
* @memberof Trader
*/
private async cleanInflux() {
await this.influx.dropSerie(MEASUREMENT_INPUTS, { name: this.config.name });
}
} | the_stack |
import * as types from '@babel/types'
import {
ComponentPluginFactory,
ComponentPlugin,
ChunkType,
FileType,
PluginStyledComponent,
} from '@teleporthq/teleport-types'
import { UIDLUtils, StringUtils } from '@teleporthq/teleport-shared'
import { ASTUtils } from '@teleporthq/teleport-plugin-common'
import {
generateStyledComponent,
removeUnusedDependencies,
generateVariantsfromStyleSet,
generateStyledComponentStyles,
} from './utils'
import { createStyleSheetPlugin } from './style-sheet'
import {
componentVariantPropKey,
componentVariantPropPrefix,
projectVariantPropKey,
projectVariantPropPrefix,
VARIANT_DEPENDENCY,
} from './constants'
interface StyledComponentsConfig {
componentChunkName: string
importChunkName?: string
componentLibrary?: 'react' | 'reactnative'
illegalComponentNames?: string[]
classAttributeName?: string
}
export const createReactStyledComponentsPlugin: ComponentPluginFactory<StyledComponentsConfig> = (
config
) => {
const {
componentChunkName = 'jsx-component',
importChunkName = 'import-local',
componentLibrary = 'react',
illegalComponentNames = [],
classAttributeName = 'className',
} = config || {}
const reactStyledComponentsPlugin: ComponentPlugin = async (structure) => {
const { uidl, chunks, dependencies, options } = structure
const { node, name, styleSetDefinitions: componentStyleSheet = {} } = uidl
const { projectStyleSet } = options
const componentChunk = chunks.find((chunk) => chunk.name === componentChunkName)
if (!componentChunk) {
return structure
}
const jsxNodesLookup = componentChunk.meta.nodesLookup as Record<string, types.JSXElement>
const propsPrefix = componentChunk.meta.dynamicRefPrefix.prop as string
const cssMap: Record<string, types.ObjectExpression> = {}
const tokensReferred: Set<string> = new Set()
if (Object.keys(componentStyleSheet).length > 0) {
const variants = generateVariantsfromStyleSet(
componentStyleSheet,
componentVariantPropPrefix,
componentVariantPropKey,
tokensReferred
)
chunks.push({
name: 'variant',
type: ChunkType.AST,
content: variants,
fileType: FileType.JS,
linkAfter: ['jsx-component'],
})
dependencies.variant = VARIANT_DEPENDENCY
}
UIDLUtils.traverseElements(node, (element) => {
const { style = {} } = element
const { key, elementType, referencedStyles = {} } = element
const propsReferred: Set<string> = new Set()
const componentStyleReferences: Set<string> = new Set()
const projectStyleReferences: Set<string> = new Set()
const staticClasses: Set<types.Identifier> = new Set()
if (Object.keys(style).length === 0 && Object.keys(referencedStyles).length === 0) {
return
}
const root = jsxNodesLookup[key]
let className = StringUtils.dashCaseToUpperCamelCase(key)
if (style && Object.keys(style).length > 0) {
/* Styled components might create an element that
clashes with native element (Text, View, Image, etc.) */
if (
illegalComponentNames.includes(className) ||
StringUtils.dashCaseToUpperCamelCase(key) === name ||
Object.keys(dependencies).includes(className)
) {
className = `Styled${className}`
}
if (componentLibrary === 'reactnative') {
if (referencedStyles && Object.keys(referencedStyles).length > 0) {
Object.keys(referencedStyles).forEach((styleId) => {
const styleRef = referencedStyles[styleId]
if (styleRef.content.mapType === 'inlined') {
referencedStyles[styleId] = {
...referencedStyles[styleId],
content: {
...referencedStyles[styleId].content,
// @ts-ignore
styles: styleRef.content.styles,
},
}
}
})
}
}
cssMap[className] = generateStyledComponentStyles({
styles: style,
propsReferred,
tokensReferred,
propsPrefix,
tokensPrefix: 'TOKENS',
})
}
if (referencedStyles && Object.keys(referencedStyles)?.length > 0) {
Object.values(referencedStyles).forEach((styleRef) => {
switch (styleRef.content?.mapType) {
case 'inlined': {
const { conditions } = styleRef.content
const [condition] = conditions
if (condition.conditionType === 'screen-size') {
const nodeStyle = cssMap[className]
const mediaStyles = types.objectProperty(
types.stringLiteral(`@media(max-width: ${condition.maxWidth}px)`),
generateStyledComponentStyles({
styles: styleRef.content.styles,
propsReferred,
tokensReferred,
propsPrefix,
tokensPrefix: 'TOKENS',
})
)
if (nodeStyle?.type === 'ObjectExpression') {
nodeStyle.properties.push(mediaStyles)
} else {
cssMap[className] = ASTUtils.wrapObjectPropertiesWithExpression([mediaStyles])
}
}
if (condition.conditionType === 'element-state') {
const nodeStyle = cssMap[className]
const mediaStyles = types.objectProperty(
types.stringLiteral(`&:${condition.content}`),
generateStyledComponentStyles({
styles: styleRef.content.styles,
propsReferred,
tokensReferred,
propsPrefix,
tokensPrefix: 'TOKENS',
})
)
if (nodeStyle?.type === 'ObjectExpression') {
nodeStyle.properties.push(mediaStyles)
} else {
cssMap[className] = ASTUtils.wrapObjectPropertiesWithExpression([mediaStyles])
}
}
return
}
case 'component-referenced': {
if (componentStyleReferences.size > 0) {
throw new PluginStyledComponent(`Styled Component can have only one reference per node.
i.e either a direct static reference from component style sheet or from props. Got both. ${JSON.stringify(
Array.from(componentStyleReferences),
null,
2
)}`)
}
if (styleRef.content.content.type === 'static') {
staticClasses.add(types.identifier(`'${styleRef.content.content.content}'`))
}
if (
styleRef.content.content.type === 'dynamic' &&
styleRef.content.content.content.referenceType === 'comp'
) {
componentStyleReferences.add(componentVariantPropPrefix)
ASTUtils.addAttributeToJSXTag(
root,
componentVariantPropKey,
styleRef.content.content.content.id
)
}
if (
styleRef.content.content.type === 'dynamic' &&
styleRef.content.content.content.referenceType === 'prop'
) {
componentStyleReferences.add(componentVariantPropPrefix)
ASTUtils.addDynamicAttributeToJSXTag(
root,
componentVariantPropKey,
`${propsPrefix}.${styleRef.content.content.content.id}`
)
}
return
}
case 'project-referenced': {
if (!projectStyleSet) {
throw new Error(
`Project Style Sheet is missing, but the node is referring to it ${element}`
)
}
const { content } = styleRef
const referedStyle = projectStyleSet.styleSetDefinitions[content.referenceId]
if (!referedStyle) {
throw new Error(
`Style that is being used for reference is missing - ${content.referenceId}`
)
}
dependencies[projectVariantPropPrefix] = {
type: 'local',
path: `${projectStyleSet.path}${projectStyleSet.fileName}`,
meta: {
namedImport: true,
},
}
projectStyleReferences.add(projectVariantPropPrefix)
ASTUtils.addAttributeToJSXTag(root, projectVariantPropKey, content.referenceId)
return
}
default: {
throw new Error(`
We support only inlined and project-referenced styles as of now, received ${JSON.stringify(
styleRef.content,
null,
2
)}
`)
}
}
})
}
if (propsReferred.size > 0) {
ASTUtils.addSpreadAttributeToJSXTag(root, propsPrefix)
}
if (staticClasses.size > 0) {
ASTUtils.addMultipleDynamicAttributesToJSXTag(
root,
classAttributeName,
Array.from(staticClasses)
)
}
ASTUtils.renameJSXTag(root, className)
const code = {
type: ChunkType.AST,
fileType: FileType.JS,
name: className,
linkAfter: [importChunkName],
content: generateStyledComponent({
name: className,
styles: cssMap[className],
elementType,
propsReferred,
componentStyleReferences,
projectStyleReferences,
}),
}
chunks.push(code)
})
if (Object.keys(cssMap).length === 0) {
return structure
}
if (tokensReferred.size > 0) {
dependencies.TOKENS = {
type: 'local',
path: `${projectStyleSet.path}${projectStyleSet.fileName}`,
meta: {
namedImport: true,
},
}
}
dependencies.styled = {
type: 'package',
path: componentLibrary === 'react' ? 'styled-components' : 'styled-components/native',
version: '^5.3.0',
}
/* React Native elements are imported from styled-components/native,
so direct dependency to `react-native` is removed */
if (componentLibrary === 'reactnative') {
removeUnusedDependencies(dependencies, jsxNodesLookup)
}
return structure
}
return reactStyledComponentsPlugin
}
export { createStyleSheetPlugin }
export default createReactStyledComponentsPlugin() | the_stack |
import * as path from 'path';
import * as fs from 'fs-extra';
import chalk from 'chalk';
import webpack, { MultiStats } from 'webpack';
import { Logger } from 'npmlog';
import { AggregatedResult } from '@jest/test-result';
import { GlobalConfig } from '@jest/types/build/Config';
import * as fg from 'fast-glob';
import type WebpackDevServer from 'webpack-dev-server';
import {
IHash,
Json,
JsonValue,
MaybeArray,
MaybePromise,
JsonArray,
} from '../types';
import hijackWebpackResolve from '../utils/hijackWebpack';
import loadConfig from '../utils/loadConfig';
import assert = require('assert');
import _ = require('lodash');
import camelCase = require('camelcase');
import WebpackChain = require('webpack-chain');
import deepmerge = require('deepmerge');
import log = require('../utils/log');
const PKG_FILE = 'package.json';
const USER_CONFIG_FILE = ['build.json', 'build.config.(js|ts)'];
const PLUGIN_CONTEXT_KEY = [
'command' as 'command',
'commandArgs' as 'commandArgs',
'rootDir' as 'rootDir',
'userConfig' as 'userConfig',
'originalUserConfig' as 'originalUserConfig',
'pkg' as 'pkg',
'webpack' as 'webpack',
];
const VALIDATION_MAP = {
string: 'isString' as 'isString',
number: 'isNumber' as 'isNumber',
array: 'isArray' as 'isArray',
object: 'isObject' as 'isObject',
boolean: 'isBoolean' as 'isBoolean',
};
const BUILTIN_CLI_OPTIONS = [
{ name: 'port', commands: ['start'] },
{ name: 'host', commands: ['start'] },
{ name: 'disableAsk', commands: ['start'] },
{ name: 'config', commands: ['start', 'build', 'test'] },
];
export type IWebpack = typeof webpack;
export type PluginContext = Pick<Context, typeof PLUGIN_CONTEXT_KEY[number]>;
export type UserConfigContext = PluginContext & {
taskName: string;
};
export type ValidationKey = keyof typeof VALIDATION_MAP;
export interface IJestResult {
results: AggregatedResult;
globalConfig: GlobalConfig;
}
export interface IOnHookCallbackArg {
err?: Error;
args?: CommandArgs;
stats?: MultiStats;
url?: string;
devServer?: WebpackDevServer;
config?: any;
result?: IJestResult;
}
export interface IOnHookCallback {
(arg?: IOnHookCallbackArg): MaybePromise<void>;
}
export interface IOnHook {
(eventName: string, callback: IOnHookCallback): void;
}
export interface IPluginConfigWebpack {
(config: WebpackChain): Promise<void> | void;
}
export interface IUserConfigWebpack {
(config: WebpackChain, value: JsonValue, context: UserConfigContext): Promise<void> | void;
}
export interface IValidation {
(value: any): boolean;
}
export interface IUserConfigArgs {
name: string;
configWebpack?: IUserConfigWebpack;
defaultValue?: any;
validation?: ValidationKey | IValidation;
ignoreTasks?: string[];
}
export interface ICliOptionArgs {
name: string;
configWebpack?: IUserConfigWebpack;
commands?: string[];
ignoreTasks?: string[];
}
export interface IOnGetWebpackConfig {
(name: string, fn: IPluginConfigWebpack): void;
(fn: IPluginConfigWebpack): void;
}
export interface IOnGetJestConfig {
(fn: IJestConfigFunction): void;
}
export interface IRegisterTask {
(name: string, chainConfig: WebpackChain): void;
}
export interface ICancelTask {
(name: string): void;
}
export interface IMethodRegistration {
(args?: any): void;
}
export interface IMethodCurry {
(data?: any): IMethodRegistration;
}
export type IMethodFunction = IMethodRegistration | IMethodCurry;
export interface IMethodOptions {
pluginName?: boolean;
}
export interface IRegisterMethod {
(name: string, fn: IMethodFunction, options?: IMethodOptions): void;
}
type IMethod = [string, string] | string;
export interface IApplyMethod {
(config: IMethod, ...args: any[]): any;
}
export interface IApplyMethodAPI {
(name: string, ...args: any[]): any;
}
export interface IHasMethod {
(name: string): boolean;
}
export interface IModifyConfig {
(userConfig: IUserConfig): Omit<IUserConfig, 'plugins'>;
}
export interface IModifyUserConfig {
(configKey: string | IModifyConfig, value?: any, options?: { deepmerge: boolean }): void;
}
export interface IGetAllPlugin {
(dataKeys?: string[]): Partial<IPluginInfo>[];
}
export interface IPluginAPI {
log: Logger;
context: PluginContext;
registerTask: IRegisterTask;
getAllTask: () => string[];
getAllPlugin: IGetAllPlugin;
onGetWebpackConfig: IOnGetWebpackConfig;
onGetJestConfig: IOnGetJestConfig;
onHook: IOnHook;
setValue: <T>(name: string, value: T) => void;
getValue: <T>(name: string) => T;
registerUserConfig: (args: MaybeArray<IUserConfigArgs>) => void;
hasRegistration: (name: string, type?: 'cliOption' | 'userConfig') => boolean;
registerCliOption: (args: MaybeArray<ICliOptionArgs>) => void;
registerMethod: IRegisterMethod;
applyMethod: IApplyMethodAPI;
modifyUserConfig: IModifyUserConfig;
}
export interface IPluginInfo {
fn: IPlugin;
name?: string;
pluginPath?: string;
options: IPluginOptions;
}
export type IPluginOptions = Json | JsonArray;
export interface IPlugin {
(api: IPluginAPI, options?: IPluginOptions): MaybePromise<void>;
}
export type CommandName = 'start' | 'build' | 'test';
export type CommandArgs = IHash<any>;
export type IPluginList = (string | [string, Json])[];
export type IGetBuiltInPlugins = (userConfig: IUserConfig) => IPluginList;
export type CommandModule<T> = (context: Context, options: any) => Promise<T>;
export interface ICommandModules<T = any> {
[command: string]: CommandModule<T>;
}
export type RegisterCommandModules = (key: string, module: CommandModule<any>) => void;
export interface IContextOptions {
command: CommandName;
rootDir: string;
args: CommandArgs;
plugins?: IPluginList;
getBuiltInPlugins?: IGetBuiltInPlugins;
commandModules?: ICommandModules;
}
export interface ITaskConfig {
name: string;
chainConfig: WebpackChain;
modifyFunctions: IPluginConfigWebpack[];
}
export interface IUserConfig extends Json {
plugins: IPluginList;
}
export interface IModeConfig {
[name: string]: IUserConfig;
}
export interface IJestConfigFunction {
(JestConfig: Json): Json;
}
export interface IModifyRegisteredConfigCallbacks<T> {
(configArgs: T): T;
}
export interface IUserConfigRegistration {
[key: string]: IUserConfigArgs;
}
export interface ICliOptionRegistration {
[key: string]: ICliOptionArgs;
}
export interface IModifyConfigRegistration {
(configFunc: IModifyRegisteredConfigCallbacks<IUserConfigRegistration>): void;
(
configName: string,
configFunc: IModifyRegisteredConfigCallbacks<IUserConfigArgs>,
): void;
}
export interface IModifyCliRegistration {
(configFunc: IModifyRegisteredConfigCallbacks<ICliOptionRegistration>): void;
(
configName: string,
configFunc: IModifyRegisteredConfigCallbacks<ICliOptionArgs>,
): void;
}
export type IModifyRegisteredConfigArgs =
| [string, IModifyRegisteredConfigCallbacks<IUserConfigArgs>]
| [IModifyRegisteredConfigCallbacks<IUserConfigRegistration>];
export type IModifyRegisteredCliArgs =
| [string, IModifyRegisteredConfigCallbacks<ICliOptionArgs>]
| [IModifyRegisteredConfigCallbacks<ICliOptionRegistration>];
export type IOnGetWebpackConfigArgs =
| [string, IPluginConfigWebpack]
| [IPluginConfigWebpack];
export type IRegistrationKey =
| 'modifyConfigRegistrationCallbacks'
| 'modifyCliRegistrationCallbacks';
const mergeConfig = <T>(currentValue: T, newValue: T): T => {
// only merge when currentValue and newValue is object and array
const isBothArray = Array.isArray(currentValue) && Array.isArray(newValue);
const isBothObject = _.isPlainObject(currentValue) && _.isPlainObject(newValue);
if (isBothArray || isBothObject) {
return deepmerge(currentValue, newValue);
} else {
return newValue;
}
};
class Context {
public command: CommandName;
public commandArgs: CommandArgs;
public rootDir: string;
public webpack: IWebpack;
public pkg: Json;
public userConfig: IUserConfig;
public originalUserConfig: IUserConfig;
public plugins: IPluginInfo[];
private options: IContextOptions;
// 通过registerTask注册,存放初始的webpack-chain配置
private configArr: ITaskConfig[];
private modifyConfigFns: IOnGetWebpackConfigArgs[];
private modifyJestConfig: IJestConfigFunction[];
private modifyConfigRegistrationCallbacks: IModifyRegisteredConfigArgs[];
private modifyCliRegistrationCallbacks: IModifyRegisteredConfigArgs[];
private eventHooks: {
[name: string]: IOnHookCallback[];
};
private internalValue: IHash<any>;
private userConfigRegistration: IUserConfigRegistration;
private cliOptionRegistration: ICliOptionRegistration;
private methodRegistration: { [name: string]: [IMethodFunction, any] };
private cancelTaskNames: string[];
public commandModules: ICommandModules = {};
constructor(options: IContextOptions) {
const {
command,
rootDir = process.cwd(),
args = {},
} = options || {};
this.options = options;
this.command = command;
this.commandArgs = args;
this.rootDir = rootDir;
/**
* config array
* {
* name,
* chainConfig,
* webpackFunctions,
* }
*/
this.configArr = [];
this.modifyConfigFns = [];
this.modifyJestConfig = [];
this.modifyConfigRegistrationCallbacks = [];
this.modifyCliRegistrationCallbacks = [];
this.eventHooks = {}; // lifecycle functions
this.internalValue = {}; // internal value shared between plugins
this.userConfigRegistration = {};
this.cliOptionRegistration = {};
this.methodRegistration = {};
this.cancelTaskNames = [];
this.pkg = this.getProjectFile(PKG_FILE);
// register builtin options
this.registerCliOption(BUILTIN_CLI_OPTIONS);
}
private registerConfig = (
type: string,
args: MaybeArray<IUserConfigArgs> | MaybeArray<ICliOptionArgs>,
parseName?: (name: string) => string,
): void => {
const registerKey = `${type}Registration` as
| 'userConfigRegistration'
| 'cliOptionRegistration';
if (!this[registerKey]) {
throw new Error(
`unknown register type: ${type}, use available types (userConfig or cliOption) instead`,
);
}
const configArr = _.isArray(args) ? args : [args];
configArr.forEach((conf): void => {
const confName = parseName ? parseName(conf.name) : conf.name;
if (this[registerKey][confName]) {
throw new Error(`${conf.name} already registered in ${type}`);
}
this[registerKey][confName] = conf;
// set default userConfig
if (
type === 'userConfig' &&
_.isUndefined(this.userConfig[confName]) &&
Object.prototype.hasOwnProperty.call(conf, 'defaultValue')
) {
this.userConfig[confName] = (conf as IUserConfigArgs).defaultValue;
}
});
};
private async runConfigWebpack(
fn: IUserConfigWebpack,
configValue: JsonValue,
ignoreTasks: string[] | null,
): Promise<void> {
for (const webpackConfigInfo of this.configArr) {
const taskName = webpackConfigInfo.name;
let ignoreConfig = false;
if (Array.isArray(ignoreTasks)) {
ignoreConfig = ignoreTasks.some(ignoreTask =>
new RegExp(ignoreTask).exec(taskName),
);
}
if (!ignoreConfig) {
const userConfigContext: UserConfigContext = {
..._.pick(this, PLUGIN_CONTEXT_KEY),
taskName,
};
// eslint-disable-next-line no-await-in-loop
await fn(webpackConfigInfo.chainConfig, configValue, userConfigContext);
}
}
}
private getProjectFile = (fileName: string): Json => {
const configPath = path.resolve(this.rootDir, fileName);
let config = {};
if (fs.existsSync(configPath)) {
try {
config = fs.readJsonSync(configPath);
} catch (err) {
log.info(
'CONFIG',
`Fail to load config file ${configPath}, use empty object`,
);
}
}
return config;
};
private getUserConfig = async (): Promise<IUserConfig> => {
const { config } = this.commandArgs;
let configPath = '';
if (config) {
configPath = path.isAbsolute(config)
? config
: path.resolve(this.rootDir, config);
} else {
const [defaultUserConfig] = await fg(USER_CONFIG_FILE, { cwd: this.rootDir, absolute: true });
configPath = defaultUserConfig;
}
let userConfig: IUserConfig = {
plugins: [],
};
if (configPath && fs.existsSync(configPath)) {
try {
userConfig = await loadConfig(configPath, log);
} catch (err) {
log.info(
'CONFIG',
`Fail to load config file ${configPath}`,
);
log.error('CONFIG', err.stack || err.toString());
process.exit(1);
}
} else {
log.error(
'CONFIG',
`config file${`(${configPath})` || ''} is not exist`,
);
process.exit(1);
}
return this.mergeModeConfig(userConfig);
};
private mergeModeConfig = (userConfig: IUserConfig): IUserConfig => {
const { mode } = this.commandArgs;
// modify userConfig by userConfig.modeConfig
if (
userConfig.modeConfig &&
mode &&
(userConfig.modeConfig as IModeConfig)[mode]
) {
const {
plugins,
...basicConfig
} = (userConfig.modeConfig as IModeConfig)[mode] as IUserConfig;
const userPlugins = [...userConfig.plugins];
if (Array.isArray(plugins)) {
const pluginKeys = userPlugins.map(pluginInfo => {
return Array.isArray(pluginInfo) ? pluginInfo[0] : pluginInfo;
});
plugins.forEach(pluginInfo => {
const [pluginName] = Array.isArray(pluginInfo)
? pluginInfo
: [pluginInfo];
const pluginIndex = pluginKeys.indexOf(pluginName);
if (pluginIndex > -1) {
// overwrite plugin info by modeConfig
userPlugins[pluginIndex] = pluginInfo;
} else {
// push new plugin added by modeConfig
userPlugins.push(pluginInfo);
}
});
}
return { ...userConfig, ...basicConfig, plugins: userPlugins };
}
return userConfig;
};
private resolvePlugins = (builtInPlugins: IPluginList): IPluginInfo[] => {
const userPlugins = [
...builtInPlugins,
...(this.userConfig.plugins || []),
].map(
(pluginInfo): IPluginInfo => {
let fn;
if (_.isFunction(pluginInfo)) {
return {
fn: pluginInfo,
options: {},
};
}
const plugins: [string, IPluginOptions] = Array.isArray(pluginInfo)
? pluginInfo
: [pluginInfo, undefined];
const pluginResolveDir = process.env.EXTRA_PLUGIN_DIR
? [process.env.EXTRA_PLUGIN_DIR, this.rootDir]
: [this.rootDir];
const pluginPath = path.isAbsolute(plugins[0])
? plugins[0]
: require.resolve(plugins[0], { paths: pluginResolveDir });
const options = plugins[1];
try {
fn = require(pluginPath); // eslint-disable-line
} catch (err) {
log.error('CONFIG', `Fail to load plugin ${pluginPath}`);
log.error('CONFIG', err.stack || err.toString());
process.exit(1);
}
return {
name: plugins[0],
pluginPath,
fn: fn.default || fn || ((): void => {}),
options,
};
},
);
return userPlugins;
};
public getAllPlugin: IGetAllPlugin = (
dataKeys = ['pluginPath', 'options', 'name'],
) => {
return this.plugins.map(
(pluginInfo): Partial<IPluginInfo> => {
// filter fn to avoid loop
return _.pick(pluginInfo, dataKeys);
},
);
};
public registerTask: IRegisterTask = (name, chainConfig) => {
const exist = this.configArr.find((v): boolean => v.name === name);
if (!exist) {
this.configArr.push({
name,
chainConfig,
modifyFunctions: [],
});
} else {
throw new Error(`[Error] config '${name}' already exists!`);
}
};
public cancelTask: ICancelTask = name => {
if (this.cancelTaskNames.includes(name)) {
log.info('TASK', `task ${name} has already been canceled`);
} else {
this.cancelTaskNames.push(name);
}
};
public registerMethod: IRegisterMethod = (name, fn, options) => {
if (this.methodRegistration[name]) {
throw new Error(`[Error] method '${name}' already registered`);
} else {
const registration = [fn, options] as [IMethodFunction, IMethodOptions];
this.methodRegistration[name] = registration;
}
};
public applyMethod: IApplyMethod = (config, ...args) => {
const [methodName, pluginName] = Array.isArray(config) ? config : [config];
if (this.methodRegistration[methodName]) {
const [registerMethod, methodOptions] = this.methodRegistration[
methodName
];
if (methodOptions?.pluginName) {
return (registerMethod as IMethodCurry)(pluginName)(...args);
} else {
return (registerMethod as IMethodRegistration)(...args);
}
} else {
throw new Error(`apply unknown method ${methodName}`);
}
};
public hasMethod: IHasMethod = name => {
return !!this.methodRegistration[name];
};
public modifyUserConfig: IModifyUserConfig = (configKey, value, options) => {
const errorMsg = 'config plugins is not support to be modified';
const { deepmerge: mergeInDeep } = options || {};
if (typeof configKey === 'string') {
if (configKey === 'plugins') {
throw new Error(errorMsg);
}
const configPath = configKey.split('.');
const originalValue = _.get(this.userConfig, configPath);
const newValue = typeof value !== 'function' ? value : value(originalValue);
_.set(this.userConfig, configPath, mergeInDeep ? mergeConfig<JsonValue>(originalValue, newValue): newValue);
} else if (typeof configKey === 'function') {
const modifiedValue = configKey(this.userConfig);
if (_.isPlainObject(modifiedValue)) {
if (Object.prototype.hasOwnProperty.call(modifiedValue, 'plugins')) {
// remove plugins while it is not support to be modified
log.verbose('[modifyUserConfig]', 'delete plugins of user config while it is not support to be modified');
delete modifiedValue.plugins;
}
Object.keys(modifiedValue).forEach(modifiedConfigKey => {
const originalValue = this.userConfig[modifiedConfigKey];
this.userConfig[modifiedConfigKey] = mergeInDeep ? mergeConfig<JsonValue>(originalValue, modifiedValue[modifiedConfigKey]) : modifiedValue[modifiedConfigKey] ;
});
} else {
throw new Error(`modifyUserConfig must return a plain object`);
}
}
};
public modifyConfigRegistration: IModifyConfigRegistration = (
...args: IModifyRegisteredConfigArgs
) => {
this.modifyConfigRegistrationCallbacks.push(args);
};
public modifyCliRegistration: IModifyCliRegistration = (
...args: IModifyRegisteredCliArgs
) => {
this.modifyCliRegistrationCallbacks.push(args);
};
public getAllTask = (): string[] => {
return this.configArr.map(v => v.name);
};
public onGetWebpackConfig: IOnGetWebpackConfig = (
...args: IOnGetWebpackConfigArgs
) => {
this.modifyConfigFns.push(args);
};
public onGetJestConfig: IOnGetJestConfig = (fn: IJestConfigFunction) => {
this.modifyJestConfig.push(fn);
};
public runJestConfig = (jestConfig: Json): Json => {
let result = jestConfig;
for (const fn of this.modifyJestConfig) {
result = fn(result);
}
return result;
};
public onHook: IOnHook = (key, fn) => {
if (!Array.isArray(this.eventHooks[key])) {
this.eventHooks[key] = [];
}
this.eventHooks[key].push(fn);
};
public applyHook = async (key: string, opts = {}): Promise<void> => {
const hooks = this.eventHooks[key] || [];
for (const fn of hooks) {
// eslint-disable-next-line no-await-in-loop
await fn(opts);
}
};
public setValue = (key: string | number, value: any): void => {
this.internalValue[key] = value;
};
public getValue = (key: string | number): any => {
return this.internalValue[key];
};
public registerUserConfig = (args: MaybeArray<IUserConfigArgs>): void => {
this.registerConfig('userConfig', args);
};
public hasRegistration = (name: string, type: 'cliOption' | 'userConfig' = 'userConfig' ): boolean => {
const mappedType = type === 'cliOption' ? 'cliOptionRegistration' : 'userConfigRegistration';
return Object.keys(this[mappedType] || {}).includes(name);
};
public registerCliOption = (args: MaybeArray<ICliOptionArgs>): void => {
this.registerConfig('cliOption', args, name => {
return camelCase(name, { pascalCase: false });
});
};
public resolveConfig = async (): Promise<void> => {
this.userConfig = await this.getUserConfig();
// shallow copy of userConfig while userConfig may be modified
this.originalUserConfig = { ...this.userConfig };
const { plugins = [], getBuiltInPlugins = () => []} = this.options;
// run getBuiltInPlugins before resolve webpack while getBuiltInPlugins may add require hook for webpack
const builtInPlugins: IPluginList = [
...plugins,
...getBuiltInPlugins(this.userConfig),
];
// custom webpack
const webpackInstancePath = this.userConfig.customWebpack
? require.resolve('webpack', { paths: [this.rootDir] })
: 'webpack';
this.webpack = require(webpackInstancePath);
if (this.userConfig.customWebpack) {
hijackWebpackResolve(this.webpack, this.rootDir);
}
this.checkPluginValue(builtInPlugins); // check plugins property
this.plugins = this.resolvePlugins(builtInPlugins);
}
private runPlugins = async (): Promise<void> => {
for (const pluginInfo of this.plugins) {
const { fn, options, name: pluginName } = pluginInfo;
const pluginContext = _.pick(this, PLUGIN_CONTEXT_KEY);
const applyMethod: IApplyMethodAPI = (methodName, ...args) => {
return this.applyMethod([methodName, pluginName], ...args);
};
const pluginAPI = {
log,
context: pluginContext,
registerTask: this.registerTask,
getAllTask: this.getAllTask,
getAllPlugin: this.getAllPlugin,
cancelTask: this.cancelTask,
onGetWebpackConfig: this.onGetWebpackConfig,
onGetJestConfig: this.onGetJestConfig,
onHook: this.onHook,
setValue: this.setValue,
getValue: this.getValue,
registerUserConfig: this.registerUserConfig,
hasRegistration: this.hasRegistration,
registerCliOption: this.registerCliOption,
registerMethod: this.registerMethod,
applyMethod,
hasMethod: this.hasMethod,
modifyUserConfig: this.modifyUserConfig,
modifyConfigRegistration: this.modifyConfigRegistration,
modifyCliRegistration: this.modifyCliRegistration,
};
// eslint-disable-next-line no-await-in-loop
await fn(pluginAPI, options);
}
};
private checkPluginValue = (plugins: IPluginList): void => {
let flag;
if (!_.isArray(plugins)) {
flag = false;
} else {
flag = plugins.every(v => {
let correct = _.isArray(v) || _.isString(v) || _.isFunction(v);
if (correct && _.isArray(v)) {
correct = _.isString(v[0]);
}
return correct;
});
}
if (!flag) {
throw new Error('plugins did not pass validation');
}
};
private runConfigModification = async (): Promise<void> => {
const callbackRegistrations = [
'modifyConfigRegistrationCallbacks',
'modifyCliRegistrationCallbacks',
];
callbackRegistrations.forEach(registrationKey => {
const registrations = this[registrationKey as IRegistrationKey] as (
| IModifyRegisteredConfigArgs
| IModifyRegisteredConfigArgs
)[];
registrations.forEach(([name, callback]) => {
const modifyAll = _.isFunction(name);
const configRegistrations = this[
registrationKey === 'modifyConfigRegistrationCallbacks'
? 'userConfigRegistration'
: 'cliOptionRegistration'
];
if (modifyAll) {
const modifyFunction = name as IModifyRegisteredConfigCallbacks<IUserConfigRegistration>;
const modifiedResult = modifyFunction(configRegistrations);
Object.keys(modifiedResult).forEach(configKey => {
configRegistrations[configKey] = {
...(configRegistrations[configKey] || {}),
...modifiedResult[configKey],
};
});
} else if (typeof name === 'string') {
if (!configRegistrations[name]) {
throw new Error(`Config key '${name}' is not registered`);
}
const configRegistration = configRegistrations[name];
configRegistrations[name] = {
...configRegistration,
...callback(configRegistration),
};
}
});
});
};
private runUserConfig = async (): Promise<void> => {
for (const configInfoKey in this.userConfig) {
if (!['plugins', 'customWebpack'].includes(configInfoKey)) {
const configInfo = this.userConfigRegistration[configInfoKey];
if (!configInfo) {
throw new Error(
`[Config File] Config key '${configInfoKey}' is not supported`,
);
}
const { name, validation, ignoreTasks } = configInfo;
const configValue = this.userConfig[name];
if (validation) {
let validationInfo;
if (_.isString(validation)) {
// split validation string
const supportTypes = validation.split('|') as ValidationKey[];
const validateResult = supportTypes.some(supportType => {
const fnName = VALIDATION_MAP[supportType];
if (!fnName) {
throw new Error(`validation does not support ${supportType}`);
}
return _[fnName](configValue);
});
assert(
validateResult,
`Config ${name} should be ${validation}, but got ${configValue}`,
);
} else {
// eslint-disable-next-line no-await-in-loop
validationInfo = await validation(configValue);
assert(
validationInfo,
`${name} did not pass validation, result: ${validationInfo}`,
);
}
}
if (configInfo.configWebpack) {
// eslint-disable-next-line no-await-in-loop
await this.runConfigWebpack(
configInfo.configWebpack,
configValue,
ignoreTasks,
);
}
}
}
};
private runCliOption = async (): Promise<void> => {
for (const cliOpt in this.commandArgs) {
// allow all jest option when run command test
if (this.command !== 'test' || cliOpt !== 'jestArgv') {
const { commands, name, configWebpack, ignoreTasks } =
this.cliOptionRegistration[cliOpt] || {};
if (!name || !(commands || []).includes(this.command)) {
throw new Error(
`cli option '${cliOpt}' is not supported when run command '${this.command}'`,
);
}
if (configWebpack) {
// eslint-disable-next-line no-await-in-loop
await this.runConfigWebpack(
configWebpack,
this.commandArgs[cliOpt],
ignoreTasks,
);
}
}
}
};
private runWebpackFunctions = async (): Promise<void> => {
this.modifyConfigFns.forEach(([name, func]) => {
const isAll = _.isFunction(name);
if (isAll) {
// modify all
this.configArr.forEach(config => {
config.modifyFunctions.push(name as IPluginConfigWebpack);
});
} else {
// modify named config
this.configArr.forEach(config => {
if (config.name === name) {
config.modifyFunctions.push(func);
}
});
}
});
for (const configInfo of this.configArr) {
for (const func of configInfo.modifyFunctions) {
// eslint-disable-next-line no-await-in-loop
await func(configInfo.chainConfig);
}
}
};
public registerCommandModules (moduleKey: string, module: CommandModule<any>): void {
if (this.commandModules[moduleKey]) {
log.warn('CONFIG', `command module ${moduleKey} already been registered`);
}
this.commandModules[moduleKey] = module;
}
public getCommandModule (options: { command: CommandName; commandArgs: CommandArgs; userConfig: IUserConfig }): CommandModule<any> {
const { command } = options;
if (this.commandModules[command]) {
return this.commandModules[command];
} else {
throw new Error(`command ${command} is not support`);
}
};
public setUp = async (): Promise<ITaskConfig[]> => {
await this.resolveConfig();
await this.runPlugins();
await this.runConfigModification();
await this.runUserConfig();
await this.runWebpackFunctions();
await this.runCliOption();
// filter webpack config by cancelTaskNames
this.configArr = this.configArr.filter(
config => !this.cancelTaskNames.includes(config.name),
);
return this.configArr;
};
public getWebpackConfig = (): ITaskConfig[] => {
return this.configArr;
};
public run = async <T, P>(options?: T): Promise<P> => {
const { command, commandArgs } = this;
log.verbose(
'OPTIONS',
`${command} cliOptions: ${JSON.stringify(commandArgs, null, 2)}`,
);
try {
await this.setUp();
} catch (err) {
log.error('CONFIG', chalk.red('Failed to get config.'));
await this.applyHook(`error`, { err });
throw err;
}
const commandModule = this.getCommandModule({ command, commandArgs, userConfig: this.userConfig });
return commandModule(this, options);
}
}
export default Context; | the_stack |
const {ccclass, property} = cc._decorator;
class RenderBuff {
texture: cc.RenderTexture = null;
spriteFrame: cc.SpriteFrame = null;
cameraNode: cc.Node = null;
camera: cc.Camera = null;
/**
* 创建一个用于计算的RenderBuff(采样方式是邻近像素)
* @param width
* @param height
* @returns
*/
public static CreateComputeBuff(width: number, height: number): RenderBuff {
let result = new RenderBuff;
let texture = result.texture = new cc.RenderTexture();
texture.packable = false;
texture.setFilters(cc.Texture2D.Filter.NEAREST, cc.Texture2D.Filter.NEAREST);
texture.initWithSize(width, height);
result.spriteFrame = new cc.SpriteFrame(texture);
return result;
}
/**
* 创建一个用于计算的RenderBuff(采样方式是邻近像素)
* @param width
* @param height
* @returns
*/
public static CreateRederBuff(width: number, height: number): RenderBuff {
let result = new RenderBuff;
let texture = result.texture = new cc.RenderTexture();
texture.packable = false;
texture.initWithSize(width, height);
result.spriteFrame = new cc.SpriteFrame(texture);
return result;
}
/**
* 清空纹理内容
*/
public Clear() {
let texture = this.texture;
//@ts-ignore
let opts = texture._getOpts();
let size = texture.width * texture.height;
opts.image = new Uint8Array(size * 4);
texture.update(opts);
}
}
@ccclass
export default class SceneDrawingBoard extends cc.Component {
@property(cc.Node)
board: cc.Node = null;
@property(cc.Node)
pen: cc.Node = null;
@property(cc.Sprite)
singlePass: cc.Sprite = null;
@property(cc.Material)
matCapsule: cc.Material = null;
@property(cc.Material)
matBezier: cc.Material = null;
@property(cc.Graphics)
ctx: cc.Graphics = null;
protected _autoRender: boolean = true;
protected _renderBuffMap = new Map<cc.Node, RenderBuff>();
protected _isDragging: boolean = false;
protected _points: cc.Vec2[] = [];
protected _debug: boolean = false;
protected _lineWidth: number = 0.01; // ratio of screen width
onLoad() {
let renderBuff = RenderBuff.CreateRederBuff(this.board.width, this.board.height);
let sprite = this.board.getComponent(cc.Sprite);
sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM;
sprite.spriteFrame = renderBuff.spriteFrame;
this._renderBuffMap.set(this.board, renderBuff);
// 设置混合模式为max,主要为了避免线段衔接处颜色叠加导致变厚
// var ext = gl.getExtension('EXT_blend_minmax');
// let mat = this.singlePass.node.getComponent(cc.Sprite).getMaterial(0);
// mat?.setBlend(
// true,
// ext.MAX_EXT,
// gfx.BLEND_SRC_ALPHA,
// gfx.BLEND_ONE_MINUS_SRC_ALPHA,
// ext.MAX_EXT,
// gfx.BLEND_SRC_ALPHA,
// gfx.BLEND_ONE_MINUS_SRC_ALPHA,
// 0xffffffff,
// 0);
this.board.on(cc.Node.EventType.TOUCH_START, this.OnBoardTouchStart, this);
this.board.on(cc.Node.EventType.TOUCH_MOVE, this.OnBoardTouchMove, this);
this.board.on(cc.Node.EventType.TOUCH_END, this.OnBoardTouchEnd, this);
this.board.on(cc.Node.EventType.TOUCH_CANCEL, this.OnBoardTouchEnd, this);
}
start () {
}
OnRender() {
this.RenderToNode(this.pen, this.board);
}
protected SetBlendEqToMax(mat: cc.Material) {
if (this._debug)
return;
//@ts-ignore
let gl = cc.game._renderContext;
//@ts-ignore
let gfx = cc.gfx;
var ext = gl.getExtension('EXT_blend_minmax');
mat?.setBlend(
true,
ext.MAX_EXT,
gfx.BLEND_SRC_ALPHA,
gfx.BLEND_ONE_MINUS_SRC_ALPHA,
ext.MAX_EXT,
gfx.BLEND_SRC_ALPHA,
gfx.BLEND_ONE_MINUS_SRC_ALPHA,
0xffffffff,
0);
}
protected static _tmpV2 = cc.v2(0, 0);
update() {
let points = this._points;
if (points.length < 3)
return;
let A = points[0];
let B = points[1];
let C = points[2];
let sprite = this.singlePass;
let isValid: boolean = true;
let useBezier: boolean = true;
let halfBezier: boolean = true;
// ABC共线的情况用直线处理
if (Math.abs((B.x-A.x) * (C.y-A.y) - (B.y-A.y) * (C.x-A.x)) <= 1e-5) {
useBezier = false;
}
// 画直线时候点重叠,则不画
if (!useBezier && A.equals(B)) {
isValid = false;
}
// if (useBezier) {
// // 距离太短的也不要用bezier
// let tmpV2 = SceneDrawingBoard._tmpV2;
// A.sub(B, tmpV2);
// let dist2 = tmpV2.dot(tmpV2);
// if (dist2 < 16) {
// useBezier = false;
// }
// }
if (!useBezier) {
sprite.setMaterial(0, this.matCapsule);
let mat = sprite.getComponent(cc.Sprite).getMaterial(0);
this.SetBlendEqToMax(mat);
// sprite.node.color = cc.Color.WHITE;
mat.setProperty("width", this._lineWidth);
mat.setProperty("PP", [A.x, A.y, B.x, B.y]);
if (this.ctx.node.active) {
this.ctx.stroke();
this.ctx.moveTo(B.x, B.y);
}
} else {
sprite.setMaterial(0, this.matBezier);
let mat = sprite.getComponent(cc.Sprite).getMaterial(0);
this.SetBlendEqToMax(mat);
if (halfBezier) {
// 切分bezier曲线,只绘制AB段
// vec2 TC = PB;
// vec2 TB = (PA - PC) * 0.25 + PB;
// PB = TB;
// PC = TC;
let TB = A.sub(C);
TB.mulSelf(0.25).addSelf(B);
C = B;
B = TB;
} else {
// B从途经点变为控制点
// B = (4.0 * B - A - C) / 2.0
B = B.mul(4);
B.subSelf(A).subSelf(C).divSelf(2);
}
// sprite.node.color = cc.Color.YELLOW;
mat.setProperty("width", this._lineWidth);
mat.setProperty("PA", [A.x, A.y]);
mat.setProperty("PB", [B.x, B.y]);
mat.setProperty("PC", [C.x, C.y]);
if (this.ctx.node.active) {
this.ctx.bezierCurveTo(A.x, A.y, B.x, B.y, C.x, C.y);
this.ctx.stroke();
}
}
if (this._debug)
console.log(`${A}, ${B}, ${C}, color=${this._colorIndex}, useBezier=${useBezier}`);
if (isValid) {
sprite.enabled = true;
if (this._debug)
sprite.node.color = this._colors[this._colorIndex];
this._colorIndex = (this._colorIndex + 1) % this._colors.length;
this.RenderToNode(sprite.node, this.board);
sprite.enabled = false;
}
this._points.shift();
// this._points.shift();
return;
if (!this._autoRender)
return;
this.RenderToNode(this.pen, this.board);
}
protected TouchPosToPassPos(pos: cc.Vec2): cc.Vec2 {
let node = this.singlePass.node;
node.convertToNodeSpaceAR(pos, pos);
// map to [-0.5, 0.5]
pos.x /= node.width;
pos.y /= node.height;
// [-0.5, 0.5] map to [-1, 1]
pos.mulSelf(2.0);
// scale Y, same as in shader
pos.y *= node.height / node.width;
return pos;
}
protected OnBoardTouchStart(e: cc.Event.EventTouch) {
this._isDragging = true;
this._points.length = 0;
this._points.push(this.TouchPosToPassPos(e.getLocation()));
if (this.ctx.node.active) {
let localPos = this.node.convertToNodeSpaceAR(e.getLocation());
this.ctx.moveTo(localPos.x, localPos.y);
}
}
protected _colorIndex: number = 0;
protected _colors = [cc.Color.WHITE, cc.Color.RED, cc.Color.GREEN, cc.Color.BLUE, cc.Color.YELLOW, cc.Color.CYAN];
protected OnBoardTouchMove(e: cc.Event.EventTouch) {
if (!this._isDragging)
return;
let cur = this.TouchPosToPassPos(e.getLocation());
this._points.push(cur);
if (this.ctx.node.active) {
// let localPos = this.node.convertToNodeSpaceAR(e.getLocation());
// this.ctx.lineTo(localPos.x, localPos.y);
// this.ctx.stroke();
}
}
protected OnBoardTouchEnd() {
this._isDragging = false;
// simply clear points
// todo: draw last segment
this._points.length = 0;
if (this._debug)
console.log(`---------------------------- end ------------------------`)
}
/**
* 1:1将root内容渲染到target
* @param root
* @param target
* @returns
*/
public RenderToNode(root: cc.Node, target: cc.Node): cc.RenderTexture {
let renderBuff = this._renderBuffMap.get(target);
if (!renderBuff)
return null;
if (!renderBuff.cameraNode || !renderBuff.camera) {
// 创建截图专用的camera
// 使截屏处于被截屏对象中心(两者有同样的父节点)
let node = renderBuff.cameraNode = new cc.Node;
node.parent = target;
node.x = (0.5 - target.anchorX) * target.width;
node.y = (0.5 - target.anchorY) * target.height;
let camera = renderBuff.camera = node.addComponent(cc.Camera);
camera.backgroundColor = new cc.Color(255, 255, 255, 0); // 透明区域仍然保持透明,半透明区域和白色混合
// camera.clearFlags = cc.Camera.ClearFlags.DEPTH | cc.Camera.ClearFlags.STENCIL | cc.Camera.ClearFlags.COLOR;
// 设置你想要的截图内容的 cullingMask
camera.cullingMask = 0xffffffff;
// let targetWidth = root.width;
let targetHeight = root.height;
camera.alignWithScreen = true;
camera.orthoSize = targetHeight / 2;
camera.targetTexture = renderBuff.texture;
}
let success: boolean = false;
let camera = renderBuff.camera;
// let node = renderBuff.cameraNode;
try {
// 渲染一次摄像机,即更新一次内容到 RenderTexture 中
camera.enabled = true;
camera.render(root);
success = true;
} finally {
// 隐藏额外的camera避免在本帧再次渲染
camera.enabled = false;
}
return renderBuff.texture;
}
} | the_stack |
import * as THREE from 'three';
// @ts-ignore
import julian from 'julian';
import { Ephem } from './Ephem';
import { EphemerisTable } from './EphemerisTable';
import { rescaleArray, rescaleXYZ } from './Scale';
import type { Coordinate3d } from './Coordinates';
import type { LineBasicMaterial } from 'three';
export enum OrbitType {
UNKNOWN = 0,
PARABOLIC = 1,
HYPERBOLIC = 2,
ELLIPTICAL = 3,
TABLE = 4,
}
interface OrbitOptions {
color?: number;
eclipticLineColor?: number;
orbitPathSettings?: {
leadDurationYears?: number;
trailDurationYears?: number;
numberSamplePoints?: number;
};
}
const { sin, cos, sqrt } = Math;
const DEFAULT_LEAD_TRAIL_YEARS = 10;
const DEFAULT_SAMPLE_POINTS = 360;
const DEFAULT_ORBIT_PATH_SETTINGS = {
leadDurationYears: DEFAULT_LEAD_TRAIL_YEARS,
trailDurationYears: DEFAULT_LEAD_TRAIL_YEARS,
numberSamplePoints: DEFAULT_SAMPLE_POINTS,
};
/**
* Special cube root function that assumes input is always positive.
*/
function cbrt(x: number) {
return Math.exp(Math.log(x) / 3.0);
}
/**
* A class that builds a visual representation of a Kepler orbit.
* @example
* ```
* const orbit = new Spacekit.Orbit({
* ephem: new Spacekit.Ephem({...}),
* options: {
* color: 0xFFFFFF,
* eclipticLineColor: 0xCCCCCC,
* },
* });
* ```
*/
export class Orbit {
private ephem: Ephem | EphemerisTable;
private options: OrbitOptions;
private orbitPoints?: THREE.Vector3[];
private eclipticDropLines?: THREE.LineSegments;
private orbitShape?: THREE.Line;
private orbitStart: number;
private orbitStop: number;
private orbitType: OrbitType;
/**
* @param {(Ephem | EphemerisTable)} ephem The ephemeris that define this orbit.
* @param {Object} options
* @param {Number} options.color The color of the orbital ellipse.
* @param {Number} options.eclipticLineColor The color of lines drawn
* @param {Object} options.orbitPathSettings settings for the path
* @param {Number} options.orbitPathSettings.leadDurationYears orbit path lead time in years
* @param {Number} options.orbitPathSettings.trailDurationYears orbit path trail time in years
* @param {Number} options.orbitPathSettings.numberSamplePoints number of
* points to use when drawing the orbit line. Only applicable for
* non-elliptical and ephemeris table orbits. perpendicular to the ecliptic
* in order to illustrate depth (defaults to 0x333333).
*/
constructor(ephem: Ephem | EphemerisTable, options: OrbitOptions) {
/**
* Ephem object
* @type {(Ephem | EphemerisTable)}
*/
this.ephem = ephem;
/**
* Options (see class definition for details)
*/
this.options = options || {};
/**
* configuring orbit path lead/trail data
*/
if (!this.options.orbitPathSettings) {
this.options.orbitPathSettings = JSON.parse(
JSON.stringify(DEFAULT_ORBIT_PATH_SETTINGS),
);
}
if (!this.options.orbitPathSettings?.leadDurationYears) {
this.options.orbitPathSettings!.leadDurationYears =
DEFAULT_LEAD_TRAIL_YEARS;
}
if (!this.options.orbitPathSettings?.trailDurationYears) {
this.options.orbitPathSettings!.trailDurationYears =
DEFAULT_LEAD_TRAIL_YEARS;
}
if (!this.options.orbitPathSettings?.numberSamplePoints) {
this.options.orbitPathSettings!.numberSamplePoints =
DEFAULT_SAMPLE_POINTS;
}
/**
* Cached orbital points.
* @type {Array.<THREE.BufferGeometry>}
*/
this.orbitPoints = undefined;
/**
* Cached ecliptic drop lines.
* @type {Array.<THREE.LineSegments>}
*/
this.eclipticDropLines = undefined;
/**
* Cached orbit shape.
* @type {THREE.Line}
*/
this.orbitShape = undefined;
/**
* Time span of the drawn orbit line
*/
this.orbitStart = 0;
this.orbitStop = 0;
/**
* Orbit type
* @type {OrbitType}
*/
this.orbitType = Orbit.getOrbitType(this.ephem);
}
/**
* Get heliocentric position of object at a given JD.
* @param {Number} jd Date value in JD.
* @param {boolean} debug Set true for debug output.
* @return {Array.<Number>} [X, Y, Z] coordinates
*/
getPositionAtTime(jd: number, debug: boolean = false): Coordinate3d {
// Note: logic below must match the vertex shader.
// This position calculation is used to create orbital ellipses.
switch (this.orbitType) {
case OrbitType.PARABOLIC:
return this.getPositionAtTimeNearParabolic(jd, debug);
case OrbitType.HYPERBOLIC:
return this.getPositionAtTimeHyperbolic(jd, debug);
case OrbitType.ELLIPTICAL:
return this.getPositionAtTimeElliptical(jd, debug);
case OrbitType.TABLE:
return this.getPositionAtTimeTable(jd, debug);
default:
throw new Error('No handler for this type of orbit');
}
}
getPositionAtTimeParabolic(jd: number, debug: boolean = false): Coordinate3d {
// See https://stjarnhimlen.se/comp/ppcomp.html#17
const eph = this.ephem;
if (eph instanceof EphemerisTable) {
throw new Error('Attempted to compute coordinates from ephemeris table');
}
// The Guassian gravitational constant
const k = 0.01720209895;
// Perihelion distance
const q = eph.get('q');
// Compute time since perihelion
const d = jd - eph.get('tp');
const H = (d * (k / sqrt(2))) / sqrt(q * q * q);
const h = 1.5 * H;
const g = sqrt(1.0 + h * h);
const s = cbrt(g + h) - cbrt(g - h);
// True anomaly
const v = 2.0 * Math.atan(s);
// Heliocentric distance
const r = q * (1.0 + s * s);
return this.vectorToHeliocentric(v, r);
}
getPositionAtTimeNearParabolic(
jd: number,
debug: boolean = false,
): Coordinate3d {
// See https://stjarnhimlen.se/comp/ppcomp.html#17
const eph = this.ephem;
if (eph instanceof EphemerisTable) {
throw new Error('Attempted to compute coordinates from ephemeris table');
}
// The Guassian gravitational constant
const k = 0.01720209895;
// Eccentricity
const e = eph.get('e');
// Perihelion distance
const q = eph.get('q');
// Compute time since perihelion
const d = jd - eph.get('tp');
const a = 0.75 * d * k * sqrt((1 + e) / (q * q * q));
const b = sqrt(1 + a * a);
const W = cbrt(b + a) - cbrt(b - a);
const f = (1 - e) / (1 + e);
const a1 = 2 / 3 + (2 / 5) * W * W;
const a2 = 7 / 5 + (33 / 35) * W * W + (37 / 175) * W ** 4;
const a3 =
W * W * (432 / 175 + (956 / 1125) * W * W + (84 / 1575) * W ** 4);
const C = (W * W) / (1 + W * W);
const g = f * C * C;
const w = W * (1 + f * C * (a1 + a2 * g + a3 * g * g));
// True anomaly
const v = 2 * Math.atan(w);
// Heliocentric distance
const r = (q * (1 + w * w)) / (1 + w * w * f);
return this.vectorToHeliocentric(v, r);
}
getPositionAtTimeHyperbolic(
jd: number,
debug: boolean = false,
): Coordinate3d {
// See https://stjarnhimlen.se/comp/ppcomp.html#17
const eph = this.ephem;
if (eph instanceof EphemerisTable) {
throw new Error('Attempted to compute coordinates from ephemeris table');
}
// Eccentricity
const e = eph.get('e');
// Semimajor axis
const a = eph.get('a');
// Mean anomaly
const ma = eph.get('ma');
// Calculate mean anomaly at jd
const n = eph.get('n', 'rad');
const epoch = eph.get('epoch');
const d = jd - epoch;
const M = ma + n * d;
let F0 = M;
for (let count = 0; count < 100; count++) {
const F1 =
(M + e * (F0 * Math.cosh(F0) - Math.sinh(F0))) /
(e * Math.cosh(F0) - 1);
const lastdiff = Math.abs(F1 - F0);
F0 = F1;
if (lastdiff < 0.0000001) {
break;
}
}
const F = F0;
const v = 2 * Math.atan(sqrt((e + 1) / (e - 1))) * Math.tanh(F / 2);
const r = (a * (1 - e * e)) / (1 + e * cos(v));
return this.vectorToHeliocentric(v, r);
}
getPositionAtTimeElliptical(
jd: number,
debug: boolean = false,
): Coordinate3d {
const eph = this.ephem;
if (eph instanceof EphemerisTable) {
throw new Error('Attempted to compute coordinates from ephemeris table');
}
// Eccentricity
const e = eph.get('e');
// Mean anomaly
const ma = eph.get('ma', 'rad');
// Calculate mean anomaly at jd
const n = eph.get('n', 'rad');
const epoch = eph.get('epoch');
const d = jd - epoch;
const M = ma + n * d;
if (debug) {
console.info('period=', eph.get('period'));
console.info('n=', n);
console.info('ma=', ma);
console.info('d=', d);
console.info('M=', M);
}
// Estimate eccentric and true anom using iterative approx
let E0 = M;
for (let count = 0; count < 100; count++) {
const E1 = M + e * sin(E0);
const lastdiff = Math.abs(E1 - E0);
E0 = E1;
if (lastdiff < 0.0000001) {
break;
}
}
const E = E0;
const v = 2 * Math.atan(sqrt((1 + e) / (1 - e)) * Math.tan(E / 2));
// Radius vector, in AU
const a = eph.get('a');
const r = (a * (1 - e * e)) / (1 + e * cos(v));
return this.vectorToHeliocentric(v, r);
}
getPositionAtTimeTable(jd: number, debug: boolean = false): Coordinate3d {
if (this.ephem instanceof EphemerisTable) {
const point = this.ephem.getPositionAtTime(jd);
return rescaleXYZ(point[0], point[1], point[2]);
}
throw new Error('Attempted to read ephemeris table of non-table data');
}
/**
* Given true anomaly and heliocentric distance, returns the scaled heliocentric coordinates (X, Y, Z)
* @param {Number} v True anomaly
* @param {Number} r Heliocentric distance
* @return {Array.<Number>} Heliocentric coordinates
*/
vectorToHeliocentric(v: number, r: number): Coordinate3d {
const eph = this.ephem;
if (eph instanceof EphemerisTable) {
throw new Error('Attempted to compute coordinates from ephemeris table');
}
// Inclination, Longitude of ascending node, Longitude of perihelion
const i = eph.get('i', 'rad');
const o = eph.get('om', 'rad');
const p = eph.get('wBar', 'rad');
// Heliocentric coords
const X = r * (cos(o) * cos(v + p - o) - sin(o) * sin(v + p - o) * cos(i));
const Y = r * (sin(o) * cos(v + p - o) + cos(o) * sin(v + p - o) * cos(i));
const Z = r * (sin(v + p - o) * sin(i));
return rescaleXYZ(X, Y, Z);
}
/**
* Returns whether the requested epoch is within the current orbit's
* definition. Used only for ephemeris tables.
* @param {Number} jd
* @return {boolean} true if it is within the orbit span, false if not
*/
needsUpdateForTime(jd: number): boolean {
if (this.orbitType === OrbitType.TABLE) {
return jd < this.orbitStart || jd > this.orbitStop;
}
// Renderings for other types are static.
return false;
}
/**
* Calculates, caches, and returns the orbit state for this orbit around this time
* @param {Number} jd center time of the orbit (only used for ephemeris table ephemeris)
* @param {boolean} forceCompute forces the recomputing of the orbit on this call
* @return {THREE.Line}
*/
getOrbitShape(jd?: number, forceCompute = false): THREE.Line {
if (forceCompute) {
if (this.orbitShape) {
this.orbitShape.geometry.dispose();
(this.orbitShape.material as LineBasicMaterial).dispose();
}
this.orbitShape = undefined;
this.orbitPoints = undefined;
if (this.eclipticDropLines) {
this.eclipticDropLines.geometry.dispose();
(this.eclipticDropLines.material as LineBasicMaterial).dispose();
}
this.eclipticDropLines = undefined;
}
if (this.orbitShape) {
// Orbit shape is already computed.
return this.orbitShape;
}
if (this.orbitType === OrbitType.ELLIPTICAL) {
return this.getEllipse();
}
// Decide on a time range to draw orbits.
// TODO(ian): Should we compute around current position, not time of perihelion?
let tp;
if (this.ephem instanceof EphemerisTable) {
tp = jd;
} else {
tp = this.ephem.getUnsafe('tp');
}
// Use current date as a fallback if time of perihelion is not available.
const centerDate = tp ? tp : julian.toJulianDay(new Date());
const startJd =
centerDate - this.options.orbitPathSettings!.trailDurationYears! * 365.25;
const endJd =
centerDate + this.options.orbitPathSettings!.leadDurationYears! * 365.25;
const step =
(endJd - startJd) / this.options.orbitPathSettings!.numberSamplePoints!;
this.orbitStart = startJd;
this.orbitStop = endJd;
switch (this.orbitType) {
case OrbitType.HYPERBOLIC:
return this.getLine(
this.getPositionAtTimeHyperbolic.bind(this),
startJd,
endJd,
step,
);
case OrbitType.PARABOLIC:
return this.getLine(
this.getPositionAtTimeNearParabolic.bind(this),
startJd,
endJd,
step,
);
case OrbitType.TABLE:
return this.getTableOrbit(startJd, endJd, step);
default:
throw new Error('Unknown orbit shape');
}
}
/**
* Compute a line between a given date range.
* @private
*/
private getLine(
orbitFn: (jd: number) => Coordinate3d,
startJd: number,
endJd: number,
step: number,
) {
const points: THREE.Vector3[] = [];
for (let jd = startJd; jd <= endJd; jd += step) {
const pos = orbitFn(jd);
points.push(new THREE.Vector3(pos[0], pos[1], pos[2]));
}
return this.generateAndCacheOrbitShape(points);
}
/**
* Returns the orbit for a table lookup orbit definition
* @private
* @param {Number} startJd start of orbit in JDate format
* @param {Number} stopJd end of orbit in JDate format
* @param {Number} step step size in days
* @return {THREE.Line}
*/
private getTableOrbit(
startJd: number,
stopJd: number,
step: number,
): THREE.Line {
if (this.ephem instanceof Ephem) {
throw new Error(
'Attempted to compute table orbit on non-table ephemeris',
);
}
const rawPoints = this.ephem.getPositions(startJd, stopJd, step);
const points = rawPoints
.map((values) => rescaleArray(values))
.map((values) => new THREE.Vector3(values[0], values[1], values[2]));
return this.generateAndCacheOrbitShape(points);
}
/**
* @private
* @return {THREE.Line} The ellipse object that represents this orbit.
*/
private getEllipse() {
const points = this.getEllipsePoints();
return this.generateAndCacheOrbitShape(points);
}
/**
* @private
* @return {THREE.Vector3[]} A THREE.js geometry
*/
private getEllipsePoints(): THREE.Vector3[] {
const eph = this.ephem;
if (eph instanceof EphemerisTable) {
throw new Error('Attempted to compute coordinates from ephemeris table');
}
const a = eph.get('a');
const ecc = eph.get('e');
const twoPi = Math.PI * 2;
const step = twoPi / 90;
const pts = [];
for (let E = 0; E < twoPi; E += step) {
const v = 2 * Math.atan(sqrt((1 + ecc) / (1 - ecc)) * Math.tan(E / 2));
const r = (a * (1 - ecc * ecc)) / (1 + ecc * cos(v));
const pos = this.vectorToHeliocentric(v, r);
if (isNaN(pos[0]) || isNaN(pos[1]) || isNaN(pos[2])) {
console.error(
'NaN position value - you may have bad or incomplete data in the following ephemeris:',
);
console.error(eph);
}
pts.push(new THREE.Vector3(pos[0], pos[1], pos[2]));
}
pts.push(pts[0]);
return pts;
}
/**
* @private
* @return {THREE.Line} Line object
*/
private generateAndCacheOrbitShape(
pointVectors: THREE.Vector3[],
): THREE.Line {
this.orbitPoints = pointVectors;
this.orbitShape = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(pointVectors),
new THREE.LineBasicMaterial({
color: new THREE.Color(this.options.color || 0x444444),
}),
);
return this.orbitShape;
}
/**
* A geometry containing line segments that run between the orbit ellipse and
* the ecliptic plane of the solar system. This is a useful visual effect
* that makes it easy to tell when an orbit goes below or above the ecliptic
* plane.
* @return {THREE.LineSegments} A geometry with many line segments.
*/
getLinesToEcliptic(): THREE.LineSegments {
if (this.eclipticDropLines) {
return this.eclipticDropLines;
}
if (!this.orbitPoints) {
// Generate the orbitPoints cache.
this.getOrbitShape();
}
// Place a cap on visible lines, for large or highly inclined orbits.
const points = this.orbitPoints || [];
let filteredPoints: THREE.Vector3[] = [];
points.forEach((vertex, idx) => {
// Drop last point because it's a repeat of the first point.
if (
idx === points.length - 1 &&
this.orbitType === OrbitType.ELLIPTICAL
) {
return;
}
filteredPoints.push(vertex);
filteredPoints.push(new THREE.Vector3(vertex.x, vertex.y, 0));
});
const geometry = new THREE.BufferGeometry().setFromPoints(filteredPoints);
this.eclipticDropLines = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color: this.options.eclipticLineColor || 0x333333,
blending: THREE.AdditiveBlending,
}),
);
return this.eclipticDropLines;
}
/**
* Get the color of this orbit.
* @return {Number} The hexadecimal color of the orbital ellipse.
*/
getHexColor(): number {
return (this.getOrbitShape().material as LineBasicMaterial).color.getHex();
}
/**
* @param {Number} hexVal The hexadecimal color of the orbital ellipse.
*/
setHexColor(hexVal: number) {
(this.getOrbitShape().material as LineBasicMaterial).color =
new THREE.Color(hexVal);
}
/**
* Get the visibility of this orbit.
* @return {boolean} Whether the orbital ellipse is visible. Note that
* although the ellipse may not be visible, it is still present in the
* underlying Scene and Simultation.
*/
getVisibility(): boolean {
return this.getOrbitShape().visible;
}
/**
* Change the visibility of this orbit.
* @param {boolean} val Whether to show the orbital ellipse.
*/
setVisibility(val: boolean) {
this.getOrbitShape().visible = val;
}
/**
* Get the type of orbit. Returns one of OrbitType.PARABOLIC, HYPERBOLIC,
* ELLIPTICAL, or UNKNOWN.
* @param {(Ephem | EphemerisTable)} Ephemeris
* @return {OrbitType} Name of orbit type
*/
static getOrbitType(ephem: Ephem | EphemerisTable): OrbitType {
if (ephem instanceof EphemerisTable) {
return OrbitType.TABLE;
}
const e = ephem.get('e');
if (e > 0.9 && e < 1.2) {
return OrbitType.PARABOLIC;
}
if (e > 1.2) {
return OrbitType.HYPERBOLIC;
}
return OrbitType.ELLIPTICAL;
}
} | the_stack |
// import { ZodUndefined } from './undefined';
// import { ZodNull } from './null';
// import { ZodUnion } from './union';
import { objectUtil } from "../helpers/objectUtil.ts";
// import { mergeShapes } from "../helpers/objectUtil/merge";
import { partialUtil } from "../helpers/partialUtil.ts";
import { Scalars } from "../helpers/primitive.ts";
import { isScalar } from "../isScalar.ts";
import { ZodTypes } from "../ZodTypes.ts";
import { ZodRawShape, ZodType, ZodTypeDef, ZodTypeAny } from "./base.ts";
import { ZodNever } from "./never.ts";
export const mergeObjects = <First extends AnyZodObject>(first: First) => <
Second extends AnyZodObject
>(
second: Second
): ZodObject<
First["_shape"] & Second["_shape"],
First["_unknownKeys"],
First["_catchall"]
// MergeObjectParams<First['_params'], Second['_params']>,
// First['_input'] & Second['_input'],
// First['_output'] & Second['_output']
> => {
const mergedShape = objectUtil.mergeShapes(
first._def.shape(),
second._def.shape()
);
const merged: any = new ZodObject({
t: ZodTypes.object,
effects: [...(first._def.effects || []), ...(second._def.effects || [])],
unknownKeys: first._def.unknownKeys,
catchall: first._def.catchall,
// params: {
// strict: first.params.strict && second.params.strict,
// },
shape: () => mergedShape,
}) as any;
return merged;
};
const AugmentFactory = <Def extends ZodObjectDef>(def: Def) => <
Augmentation extends ZodRawShape
>(
augmentation: Augmentation
): ZodObject<
{
[k in Exclude<
keyof ReturnType<Def["shape"]>,
keyof Augmentation
>]: ReturnType<Def["shape"]>[k];
} &
{ [k in keyof Augmentation]: Augmentation[k] },
Def["unknownKeys"],
Def["catchall"]
> => {
return new ZodObject({
...def,
shape: () => ({
...def.shape(),
...augmentation,
}),
}) as any;
};
type UnknownKeysParam = "passthrough" | "strict" | "strip";
export interface ZodObjectDef<
T extends ZodRawShape = ZodRawShape,
UnknownKeys extends UnknownKeysParam = UnknownKeysParam,
Catchall extends ZodTypeAny = ZodTypeAny
// Params extends ZodObjectParams = ZodObjectParams
> extends ZodTypeDef {
t: ZodTypes.object;
shape: () => T;
catchall: Catchall;
unknownKeys: UnknownKeys;
// params: Params;
}
export type baseObjectOutputType<
Shape extends ZodRawShape
// Catchall extends ZodTypeAny
> = objectUtil.flatten<
objectUtil.addQuestionMarks<
{
[k in keyof Shape]: Shape[k]["_output"];
}
> //{ [k: string]: Catchall['_output'] }
>;
export type objectOutputType<
Shape extends ZodRawShape,
Catchall extends ZodTypeAny
> = ZodTypeAny extends Catchall
? baseObjectOutputType<Shape>
: objectUtil.flatten<
baseObjectOutputType<Shape> & { [k: string]: Catchall["_output"] }
>;
export type baseObjectInputType<Shape extends ZodRawShape> = objectUtil.flatten<
objectUtil.addQuestionMarks<
{
[k in keyof Shape]: Shape[k]["_input"];
}
>
>;
export type objectInputType<
Shape extends ZodRawShape,
Catchall extends ZodTypeAny
> = ZodTypeAny extends Catchall
? baseObjectInputType<Shape>
: objectUtil.flatten<
baseObjectInputType<Shape> & { [k: string]: Catchall["_input"] }
>;
const objectDefToJson = (def: ZodObjectDef<any, any>) => ({
t: def.t,
shape: Object.assign(
{},
...Object.keys(def.shape()).map((k) => ({
[k]: def.shape()[k].toJSON(),
}))
),
});
// interface ZodObjectParams {
// strict: boolean;
// }
// type SetKey<
// Target extends object,
// Key extends string,
// Value extends any
// > = objectUtil.Flatten<
// { [k in Exclude<keyof Target, Key>]: Target[k] } & { [k in Key]: Value }
// >;
// type makeKeysRequired<T extends ZodObject<any, any, any>> = T extends ZodObject<
// infer U,
// infer P,
// infer C
// >
// ? ZodObject<objectUtil.NoNever<{ [k in keyof U]: makeRequired<U[k]> }>, P, C>
// : never;
// type makeRequired<T extends ZodType<any>> = T extends ZodUnion<infer U>
// ? U extends [infer Y, ZodUndefined]
// ? Y
// : U extends [ZodUndefined, infer Z]
// ? Z
// : T
// : T;
// type ZodObjectType<
// T extends ZodRawShape,
// Params extends ZodObjectParams
// > = Params['strict'] extends true
// ? objectUtil.ObjectType<T>
// : objectUtil.Flatten<objectUtil.ObjectType<T> & { [k: string]: any }>;
export class ZodObject<
T extends ZodRawShape,
UnknownKeys extends UnknownKeysParam = "strip",
Catchall extends ZodTypeAny = ZodTypeAny,
// Params extends ZodObjectParams = { strict: true },
// Type extends ZodObjectType<T, Params> = ZodObjectType<T, Params>
Output = objectOutputType<T, Catchall>,
Input = objectInputType<T, Catchall>
> extends ZodType<
// objectUtil.objectOutputType<T, UnknownKeys, Catchall>,
Output,
ZodObjectDef<T, UnknownKeys, Catchall>,
Input
> {
readonly _shape!: T;
readonly _unknownKeys!: UnknownKeys;
readonly _catchall!: Catchall;
get shape() {
return this._def.shape();
}
// get params() {
// return this._def.params;
// }
// get t() {
// return this;
// }
toJSON = () => objectDefToJson(this._def);
strict = (): ZodObject<T, "strict", Catchall> =>
new ZodObject({
...this._def,
unknownKeys: "strict",
});
strip = (): ZodObject<T, "strip", Catchall> =>
new ZodObject({
...this._def,
unknownKeys: "strip",
});
passthrough = (): ZodObject<T, "passthrough", Catchall> =>
new ZodObject({
...this._def,
unknownKeys: "passthrough",
});
nonstrict = this.passthrough;
// opt optional: () => ZodUnion<[this, ZodUndefined]> = () => ZodUnion.create([this, ZodUndefined.create()]);
// nullable: () => ZodUnion<[this, ZodNull]> = () => ZodUnion.create([this, ZodNull.create()]);
augment = AugmentFactory<ZodObjectDef<T, UnknownKeys, Catchall>>(this._def);
extend = AugmentFactory<ZodObjectDef<T, UnknownKeys, Catchall>>(this._def);
setKey = <Key extends string, Schema extends ZodTypeAny>(
key: Key,
schema: Schema
): ZodObject<T & { [k in Key]: Schema }, UnknownKeys, Catchall> => {
return this.augment({ [key]: schema }) as any;
};
/**
* Prior to zod@1.0.12 there was a bug in the
* inferred type of merged objects. Please
* upgrade if you are experiencing issues.
*/
merge: <Incoming extends AnyZodObject>(
other: Incoming
) => ZodObject<
T & Incoming["_shape"],
UnknownKeys,
Catchall
// objectUtil.MergeObjectParams<Params, MergeUnknownKeys>
> = mergeObjects(this as any) as any;
catchall = <Index extends ZodTypeAny>(
index: Index
): ZodObject<
T,
UnknownKeys,
Index
// objectUtil.MergeObjectParams<Params, MergeUnknownKeys>
> => {
return new ZodObject({
...this._def,
// unknownKeys: 'passthrough',
catchall: index,
});
};
pick = <Mask extends { [k in keyof T]?: true }>(
mask: Mask
): ZodObject<
objectUtil.NoNever<{ [k in keyof Mask]: k extends keyof T ? T[k] : never }>,
UnknownKeys,
Catchall
> => {
const shape: any = {};
Object.keys(mask).map((key) => {
shape[key] = this.shape[key];
});
return new ZodObject({
...this._def,
shape: () => shape,
});
};
omit = <Mask extends { [k in keyof T]?: true }>(
mask: Mask
): ZodObject<
objectUtil.NoNever<{ [k in keyof T]: k extends keyof Mask ? never : T[k] }>,
UnknownKeys,
Catchall
> => {
const shape: any = {};
Object.keys(this.shape).map((key) => {
if (Object.keys(mask).indexOf(key) === -1) {
shape[key] = this.shape[key];
}
});
return new ZodObject({
...this._def,
shape: () => shape,
});
};
partial = (): ZodObject<
{ [k in keyof T]: ReturnType<T[k]["optional"]> },
UnknownKeys,
Catchall
> => {
const newShape: any = {};
for (const key in this.shape) {
const fieldSchema = this.shape[key];
newShape[key] = fieldSchema.isOptional()
? fieldSchema
: fieldSchema.optional();
}
return new ZodObject({
...this._def,
shape: () => newShape,
});
};
// require: <This extends this>() => makeKeysRequired<This> = () => {
// const newShape: any = {};
// for (const key in this.shape) {
// const val = this.shape[key];
// if (val instanceof ZodUnion) {
// const options = (val as ZodUnion<any>)._def.options;
// if (options.length === 2) {
// // .length === 2;
// if (options[0] instanceof ZodUndefined) {
// newShape[key] = options[1];
// } else if (options[1] instanceof ZodUndefined) {
// newShape[key] = options[0];
// }
// } else {
// newShape[key] = val;
// }
// } else {
// newShape[key] = val;
// }
// }
// return new ZodObject({
// ...this._def,
// shape: () => newShape,
// }) as any;
// };
primitives = (): ZodObject<
objectUtil.NoNever<
{
[k in keyof T]: [T[k]["_output"]] extends [Scalars] ? T[k] : never;
}
>,
UnknownKeys,
Catchall
> => {
const newShape: any = {};
for (const key in this.shape) {
if (isScalar(this.shape[key])) {
newShape[key] = this.shape[key];
}
}
return new ZodObject({
...this._def,
shape: () => newShape,
});
};
nonprimitives = (): ZodObject<
objectUtil.NoNever<
{
[k in keyof T]: [T[k]["_output"]] extends [Scalars] ? never : T[k];
}
>,
UnknownKeys,
Catchall
> => {
const newShape: any = {};
for (const key in this.shape) {
if (!isScalar(this.shape[key])) {
newShape[key] = this.shape[key];
}
}
return new ZodObject({
...this._def,
shape: () => newShape,
});
};
deepPartial: () => partialUtil.RootDeepPartial<this> = () => {
const newShape: any = {};
for (const key in this.shape) {
const fieldSchema = this.shape[key];
if (fieldSchema instanceof ZodObject) {
newShape[key] = fieldSchema.isOptional()
? fieldSchema
: (fieldSchema.deepPartial() as any).optional();
} else {
newShape[key] = fieldSchema.isOptional()
? fieldSchema
: fieldSchema.optional();
}
}
return new ZodObject({
...this._def,
shape: () => newShape,
}) as any;
};
// keyof: ()=>ZodEnum<{[k in T]: k}>
static create = <T extends ZodRawShape>(shape: T): ZodObject<T> => {
return new ZodObject({
t: ZodTypes.object,
shape: () => shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
// params: {
// strict: true,
// },
}) as any;
};
static lazycreate = <T extends ZodRawShape>(shape: () => T): ZodObject<T> => {
return new ZodObject({
t: ZodTypes.object,
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
}) as any;
};
}
export type AnyZodObject = ZodObject<any, any, any>; | the_stack |
import {options} from './options';
import * as colour from './colour';
import * as local from './local';
import {themes, Themes} from './themes';
import {AppTheme, ColourScheme, ColourSchemeInfo} from './colour';
import {Hub} from './hub';
import {EventHub} from './event-hub';
export type FormatBase = 'Google' | 'LLVM' | 'Mozilla' | 'Chromium' | 'WebKit' | 'Microsoft' | 'GNU';
export interface SiteSettings {
autoCloseBrackets: boolean;
autoIndent: boolean;
allowStoreCodeDebug: boolean;
alwaysEnableAllSchemes: boolean;
colouriseAsm: boolean;
colourScheme: ColourScheme;
compileOnChange: boolean;
// TODO(supergrecko): make this more precise
defaultLanguage?: string;
delayAfterChange: number;
enableCodeLens: boolean;
enableCommunityAds: boolean;
enableCtrlS: string;
enableSharingPopover: boolean;
enableCtrlStree: boolean;
editorsFFont: string;
editorsFLigatures: boolean;
defaultFontScale?: number; // the font scale widget can check this setting before the default has been populated
formatBase: FormatBase;
formatOnCompile: boolean;
hoverShowAsmDoc: boolean;
hoverShowSource: boolean;
keepSourcesOnLangChange: boolean;
newEditorLastLang: boolean;
showMinimap: boolean;
showQuickSuggestions: boolean;
tabWidth: number;
theme: Themes;
useCustomContextMenu: boolean;
useSpaces: boolean;
useVim: boolean;
wordWrap: boolean;
}
class BaseSetting {
constructor(public elem: JQuery, public name: string) {}
// Can be undefined if the element doesn't exist which is the case in embed mode
protected val(): string | number | string[] | undefined {
return this.elem.val();
}
getUi(): any {
return this.val();
}
putUi(value: any): void {
this.elem.val(value);
}
}
class Checkbox extends BaseSetting {
override getUi(): boolean {
return !!this.elem.prop('checked');
}
override putUi(value: any) {
this.elem.prop('checked', !!value);
}
}
class Select extends BaseSetting {
constructor(elem: JQuery, name: string, populate: {label: string; desc: string}[]) {
super(elem, name);
elem.empty();
for (const e of populate) {
elem.append($(`<option value="${e.label}">${e.desc}</option>`));
}
}
override putUi(value: string | number | boolean | null) {
this.elem.val(value?.toString() ?? '');
}
}
class NumericSelect extends Select {
constructor(elem: JQuery, name: string, populate: {label: string; desc: string}[]) {
super(elem, name, populate);
}
override getUi(): number {
return Number(this.val() as string);
}
}
interface SliderSettings {
min: number;
max: number;
step: number;
display: JQuery;
formatter: (number) => string;
}
class Slider extends BaseSetting {
private readonly formatter: (number) => string;
private display: JQuery;
private max: number;
private min: number;
constructor(elem: JQuery, name: string, sliderSettings: SliderSettings) {
super(elem, name);
this.formatter = sliderSettings.formatter;
this.display = sliderSettings.display;
this.max = sliderSettings.max || 100;
this.min = sliderSettings.min || 1;
elem.prop('max', this.max)
.prop('min', this.min)
.prop('step', sliderSettings.step || 1);
elem.on('change', this.updateDisplay.bind(this));
}
override putUi(value: number) {
this.elem.val(value);
this.updateDisplay();
}
override getUi(): number {
return parseInt(this.val()?.toString() ?? '0');
}
private updateDisplay() {
this.display.text(this.formatter(this.getUi()));
}
}
class Textbox extends BaseSetting {}
class Numeric extends BaseSetting {
private readonly min: number;
private readonly max: number;
constructor(elem: JQuery, name: string, params: Record<'min' | 'max', number>) {
super(elem, name);
this.min = params.min;
this.max = params.max;
elem.attr('min', this.min).attr('max', this.max);
}
override getUi(): number {
return this.clampValue(parseInt(this.val()?.toString() ?? '0'));
}
override putUi(value: number) {
this.elem.val(this.clampValue(value));
}
private clampValue(value: number): number {
return Math.min(Math.max(value, this.min), this.max);
}
}
export class Settings {
private readonly settingsObjs: BaseSetting[];
private eventHub: EventHub;
constructor(
hub: Hub,
private root: JQuery,
private settings: SiteSettings,
private onChange: (SiteSettings) => void,
private subLangId: string | null
) {
this.eventHub = hub.createEventHub();
this.settings = settings;
this.settingsObjs = [];
this.addCheckboxes();
this.addSelectors();
this.addSliders();
this.addNumerics();
this.addTextBoxes();
this.setSettings(this.settings);
this.handleThemes();
}
public static getStoredSettings(): SiteSettings {
return JSON.parse(local.get('settings', '{}'));
}
public setSettings(newSettings: SiteSettings) {
this.onSettingsChange(newSettings);
this.onChange(newSettings);
}
private onUiChange() {
for (const setting of this.settingsObjs) {
this.settings[setting.name] = setting.getUi();
}
this.onChange(this.settings);
}
private onSettingsChange(settings: SiteSettings) {
this.settings = settings;
for (const setting of this.settingsObjs) {
setting.putUi(this.settings[setting.name]);
}
}
private add<T extends BaseSetting>(setting: T, defaultValue: any) {
const key = setting.name;
if (this.settings[key] === undefined) this.settings[key] = defaultValue;
this.settingsObjs.push(setting);
setting.elem.on('change', this.onUiChange.bind(this));
}
private addCheckboxes() {
// Known checkbox options in order [selector, key, defaultValue]
const checkboxes: [string, keyof SiteSettings, boolean][] = [
['.allowStoreCodeDebug', 'allowStoreCodeDebug', true],
['.alwaysEnableAllSchemes', 'alwaysEnableAllSchemes', false],
['.autoCloseBrackets', 'autoCloseBrackets', true],
['.autoIndent', 'autoIndent', true],
['.colourise', 'colouriseAsm', true],
['.compileOnChange', 'compileOnChange', true],
['.editorsFLigatures', 'editorsFLigatures', false],
['.enableCodeLens', 'enableCodeLens', true],
['.enableCommunityAds', 'enableCommunityAds', true],
['.enableCtrlStree', 'enableCtrlStree', true],
['.enableSharingPopover', 'enableSharingPopover', true],
['.formatOnCompile', 'formatOnCompile', false],
['.hoverShowAsmDoc', 'hoverShowAsmDoc', true],
['.hoverShowSource', 'hoverShowSource', true],
['.keepSourcesOnLangChange', 'keepSourcesOnLangChange', false],
['.newEditorLastLang', 'newEditorLastLang', true],
['.showMinimap', 'showMinimap', true],
['.showQuickSuggestions', 'showQuickSuggestions', false],
['.useCustomContextMenu', 'useCustomContextMenu', true],
['.useSpaces', 'useSpaces', true],
['.useVim', 'useVim', false],
['.wordWrap', 'wordWrap', false],
];
for (const [selector, name, defaultValue] of checkboxes) {
this.add(new Checkbox(this.root.find(selector), name), defaultValue);
}
}
private addSelectors() {
const addSelector = <Name extends keyof SiteSettings>(
selector: string,
name: Name,
populate: {label: string; desc: string}[],
defaultValue: SiteSettings[Name],
component = Select
) => {
const instance = new component(this.root.find(selector), name, populate);
this.add(instance, defaultValue);
return instance;
};
const colourSchemesData = colour.schemes.map(scheme => {
return {label: scheme.name, desc: scheme.desc};
});
addSelector('.colourScheme', 'colourScheme', colourSchemesData, colour.schemes[0].name);
// keys(themes) is Themes[] but TS does not realize without help
const themesData = (Object.keys(themes) as Themes[]).map((theme: Themes) => {
return {label: themes[theme].id, desc: themes[theme].name};
});
let defaultThemeId = themes.default.id;
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
defaultThemeId = themes.dark.id;
}
addSelector('.theme', 'theme', themesData, defaultThemeId);
const langs = options.languages;
const defaultLanguageSelector = this.root.find('.defaultLanguage');
const defLang = this.settings.defaultLanguage || Object.keys(langs)[0] || 'c++';
const defaultLanguageData = Object.keys(langs).map(lang => {
return {label: langs[lang].id, desc: langs[lang].name};
});
addSelector('.defaultLanguage', 'defaultLanguage', defaultLanguageData, defLang);
if (this.subLangId) {
defaultLanguageSelector
.prop('disabled', true)
.prop('title', 'Default language inherited from subdomain')
.css('cursor', 'not-allowed');
}
const defaultFontScale = options.defaultFontScale;
const fontScales: {label: string; desc: string}[] = [];
for (let i = 8; i <= 30; i++) {
fontScales.push({label: i.toString(), desc: i.toString()});
}
const defaultFontScaleSelector = addSelector(
'.defaultFontScale',
'defaultFontScale',
fontScales,
defaultFontScale,
NumericSelect
).elem;
defaultFontScaleSelector.on('change', e => {
this.eventHub.emit('broadcastFontScale', parseInt((e.target as HTMLSelectElement).value));
});
const formats: FormatBase[] = ['Google', 'LLVM', 'Mozilla', 'Chromium', 'WebKit', 'Microsoft', 'GNU'];
const formatsData = formats.map(format => {
return {label: format, desc: format};
});
addSelector('.formatBase', 'formatBase', formatsData, formats[0]);
const enableCtrlSData = [
{label: 'true', desc: 'Save To Local File'},
{label: 'false', desc: 'Create Short Link'},
{label: '2', desc: 'Reformat code'},
{label: '3', desc: 'Do nothing'},
];
addSelector('.enableCtrlS', 'enableCtrlS', enableCtrlSData, 'true');
}
private addSliders() {
// Handle older settings
if (this.settings.delayAfterChange === 0) {
this.settings.delayAfterChange = 750;
this.settings.compileOnChange = false;
}
const delayAfterChangeSettings: SliderSettings = {
max: 3000,
step: 250,
min: 250,
display: this.root.find('.delay-current-value'),
formatter: x => (x / 1000.0).toFixed(2) + 's',
};
this.add(new Slider(this.root.find('.delay'), 'delayAfterChange', delayAfterChangeSettings), 750);
}
private addNumerics() {
this.add(
new Numeric(this.root.find('.tabWidth'), 'tabWidth', {
min: 1,
max: 80,
}),
4
);
}
private addTextBoxes() {
this.add(
new Textbox(this.root.find('.editorsFFont'), 'editorsFFont'),
'Consolas, "Liberation Mono", Courier, monospace'
);
}
private handleThemes() {
const themeSelect = this.root.find('.theme');
themeSelect.on('change', () => {
this.onThemeChange();
$.data(themeSelect, 'last-theme', themeSelect.val() as string);
});
const colourSchemeSelect = this.root.find('.colourScheme');
colourSchemeSelect.on('change', e => {
const currentTheme = this.settings.theme;
$.data(themeSelect, 'theme-' + currentTheme, colourSchemeSelect.val() as ColourScheme);
});
const enableAllSchemesCheckbox = this.root.find('.alwaysEnableAllSchemes');
enableAllSchemesCheckbox.on('change', this.onThemeChange.bind(this));
$.data(themeSelect, 'last-theme', themeSelect.val() as string);
}
private fillThemeSelector(colourSchemeSelect: JQuery, newTheme?: AppTheme) {
for (const scheme of colour.schemes) {
if (this.isSchemeUsable(scheme, newTheme)) {
colourSchemeSelect.append($(`<option value="${scheme.name}">${scheme.desc}</option>`));
}
}
}
private isSchemeUsable(scheme: ColourSchemeInfo, newTheme?: AppTheme): boolean {
return (
this.settings.alwaysEnableAllSchemes ||
scheme.themes.length === 0 ||
(newTheme && scheme.themes.includes(newTheme)) ||
scheme.themes.includes('all')
);
}
private selectorHasOption(selector: JQuery, option: string): boolean {
return selector.children(`[value=${option}]`).length > 0;
}
private onThemeChange() {
// We can be called when:
// Site is initializing (settings and dropdowns are already done)
// "Make all colour schemes available" changes
// Selected theme changes
const themeSelect = this.root.find('.theme');
const colourSchemeSelect = this.root.find('.colourScheme');
const oldScheme = colourSchemeSelect.val() as string;
const newTheme = themeSelect.val() as colour.AppTheme;
colourSchemeSelect.empty();
this.fillThemeSelector(colourSchemeSelect, newTheme);
const newThemeStoredScheme = $.data(themeSelect, 'theme-' + newTheme) as colour.AppTheme | undefined;
// If nothing else, set the new scheme to the first of the available ones
let newScheme = colourSchemeSelect.first().val() as string;
// If we have one old one stored, check if it's still valid and set it if so
if (newThemeStoredScheme && this.selectorHasOption(colourSchemeSelect, newThemeStoredScheme)) {
newScheme = newThemeStoredScheme;
} else if (this.selectorHasOption(colourSchemeSelect, oldScheme)) {
newScheme = oldScheme;
}
colourSchemeSelect.val(newScheme);
colourSchemeSelect.trigger('change');
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormEntry_Edit_Form {
interface tab__9C558780_D2CE_4E55_8FDD_37082D8196BE_Sections {
notes: DevKit.Controls.Section;
}
interface tab__AE8B7CDD_484B_49A8_A00D_C201927D5729_Sections {
}
interface tab__9C558780_D2CE_4E55_8FDD_37082D8196BE extends DevKit.Controls.ITab {
Section: tab__9C558780_D2CE_4E55_8FDD_37082D8196BE_Sections;
}
interface tab__AE8B7CDD_484B_49A8_A00D_C201927D5729 extends DevKit.Controls.ITab {
Section: tab__AE8B7CDD_484B_49A8_A00D_C201927D5729_Sections;
}
interface Tabs {
_9C558780_D2CE_4E55_8FDD_37082D8196BE: tab__9C558780_D2CE_4E55_8FDD_37082D8196BE;
_AE8B7CDD_484B_49A8_A00D_C201927D5729: tab__AE8B7CDD_484B_49A8_A00D_C201927D5729;
}
interface Body {
Tab: Tabs;
/** Type the description of the time entry. */
msdyn_description: DevKit.Controls.String;
/** Shows the time spent. */
msdyn_duration: DevKit.Controls.Integer;
/** Select the entry status. */
msdyn_entryStatus: DevKit.Controls.OptionSet;
/** Type the external description of the time entry. */
msdyn_externalDescription: DevKit.Controls.String;
/** Unique identifier for Time Source associated with Time Entry. */
msdyn_timeentrysettingId: DevKit.Controls.Lookup;
notescontrol: DevKit.Controls.Note;
}
}
class FormEntry_Edit_Form extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Entry_Edit_Form
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Entry_Edit_Form */
Body: DevKit.FormEntry_Edit_Form.Body;
}
namespace Formmsdyn_timeentry_Field_Service_Information {
interface tab_General_Sections {
tab_2_section_1: DevKit.Controls.Section;
tab_2_section_2: DevKit.Controls.Section;
tab_2_section_3: DevKit.Controls.Section;
}
interface tab_General extends DevKit.Controls.ITab {
Section: tab_General_Sections;
}
interface Tabs {
General: tab_General;
}
interface Body {
Tab: Tabs;
/** Shows the bookable resource. */
msdyn_bookableresource: DevKit.Controls.Lookup;
/** Unique identifier for Resource Booking associated with Time Entry. */
msdyn_BookableResourceBooking: DevKit.Controls.Lookup;
/** Booking Status */
msdyn_BookingStatus: DevKit.Controls.Lookup;
/** Type the description of the time entry. */
msdyn_description: DevKit.Controls.String;
/** Shows the time spent. */
msdyn_duration: DevKit.Controls.Integer;
/** The end time of the time entry. */
msdyn_end: DevKit.Controls.DateTime;
/** Select the entry status. */
msdyn_entryStatus: DevKit.Controls.OptionSet;
/** Type the external description of the time entry. */
msdyn_externalDescription: DevKit.Controls.String;
/** The start time of the time entry. */
msdyn_start: DevKit.Controls.DateTime;
/** Unique identifier for Time Source associated with Time Entry. */
msdyn_timeentrysettingId: DevKit.Controls.Lookup;
/** Unique identifier for Time Off Request associated with Time Entry. This field is auto-populated when a Time Entry is auto-created from a Time Off Request. */
msdyn_timeoffrequest: DevKit.Controls.Lookup;
/** Select the time entry type. */
msdyn_type: DevKit.Controls.OptionSet;
/** Unique identifier for Work Orders associated with Time Entry. */
msdyn_WorkOrder: DevKit.Controls.Lookup;
}
}
class Formmsdyn_timeentry_Field_Service_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_timeentry_Field_Service_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_timeentry_Field_Service_Information */
Body: DevKit.Formmsdyn_timeentry_Field_Service_Information.Body;
}
namespace Formmsdyn_timeentry_Information {
interface tab__AE8B7CDD_484B_49A8_A00D_C201927D5729_Sections {
_AE8B7CDD_484B_49A8_A00D_C201927D5729: DevKit.Controls.Section;
}
interface tab__AE8B7CDD_484B_49A8_A00D_C201927D5729 extends DevKit.Controls.ITab {
Section: tab__AE8B7CDD_484B_49A8_A00D_C201927D5729_Sections;
}
interface Tabs {
_AE8B7CDD_484B_49A8_A00D_C201927D5729: tab__AE8B7CDD_484B_49A8_A00D_C201927D5729;
}
interface Body {
Tab: Tabs;
/** Enter the time entry date. */
msdyn_date: DevKit.Controls.Date;
/** Type the description of the time entry. */
msdyn_description: DevKit.Controls.String;
/** Shows the time spent. */
msdyn_duration: DevKit.Controls.Integer;
/** Select the entry status. */
msdyn_entryStatus: DevKit.Controls.OptionSet;
/** Type the external description of the time entry. */
msdyn_externalDescription: DevKit.Controls.String;
/** Select the project that the time entry is related to. */
msdyn_project: DevKit.Controls.Lookup;
/** Select the project task that the time entry is related to. */
msdyn_projectTask: DevKit.Controls.Lookup;
/** Select the role that the user has in the project that the time entry is for. */
msdyn_resourceCategory: DevKit.Controls.Lookup;
/** Unique identifier for Time Source associated with Time Entry. */
msdyn_timeentrysettingId: DevKit.Controls.Lookup;
/** Select the time entry type. */
msdyn_type: DevKit.Controls.OptionSet;
notescontrol: DevKit.Controls.Note;
}
interface Navigation {
nav_msdyn_msdyn_timeentry_msdyn_timeoffcalendar_timeEntry: DevKit.Controls.NavigationItem
}
}
class Formmsdyn_timeentry_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_timeentry_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_timeentry_Information */
Body: DevKit.Formmsdyn_timeentry_Information.Body;
/** The Navigation of form msdyn_timeentry_Information */
Navigation: DevKit.Formmsdyn_timeentry_Information.Navigation;
}
namespace FormRow_Edit_Form {
interface tab__AE8B7CDD_484B_49A8_A00D_C201927D5729_Sections {
}
interface tab__AE8B7CDD_484B_49A8_A00D_C201927D5729 extends DevKit.Controls.ITab {
Section: tab__AE8B7CDD_484B_49A8_A00D_C201927D5729_Sections;
}
interface Tabs {
_AE8B7CDD_484B_49A8_A00D_C201927D5729: tab__AE8B7CDD_484B_49A8_A00D_C201927D5729;
}
interface Body {
Tab: Tabs;
/** Type the description of the time entry. */
msdyn_description: DevKit.Controls.String;
/** Select the entry status. */
msdyn_entryStatus: DevKit.Controls.OptionSet;
/** Select the project that the time entry is related to. */
msdyn_project: DevKit.Controls.Lookup;
/** Select the project task that the time entry is related to. */
msdyn_projectTask: DevKit.Controls.Lookup;
/** Select the role that the user has in the project that the time entry is for. */
msdyn_resourceCategory: DevKit.Controls.Lookup;
/** Unique identifier for Time Source associated with Time Entry. */
msdyn_timeentrysettingId: DevKit.Controls.Lookup;
/** Select the time entry type. */
msdyn_type: DevKit.Controls.OptionSet;
}
}
class FormRow_Edit_Form extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Row_Edit_Form
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form Row_Edit_Form */
Body: DevKit.FormRow_Edit_Form.Body;
}
namespace FormTESA_Time_Entry_Main_Form {
interface tab__AE8B7CDD_484B_49A8_A00D_C201927D5729_Sections {
_AE8B7CDD_484B_49A8_A00D_C201927D5729: DevKit.Controls.Section;
}
interface tab__AE8B7CDD_484B_49A8_A00D_C201927D5729 extends DevKit.Controls.ITab {
Section: tab__AE8B7CDD_484B_49A8_A00D_C201927D5729_Sections;
}
interface Tabs {
_AE8B7CDD_484B_49A8_A00D_C201927D5729: tab__AE8B7CDD_484B_49A8_A00D_C201927D5729;
}
interface Body {
Tab: Tabs;
/** Type the description of the time entry. */
msdyn_description: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
}
}
class FormTESA_Time_Entry_Main_Form extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form TESA_Time_Entry_Main_Form
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form TESA_Time_Entry_Main_Form */
Body: DevKit.FormTESA_Time_Entry_Main_Form.Body;
}
namespace FormCreate_Time_Entry {
interface tab_Time_Entry_Quick_Create_Form_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
}
interface tab_Time_Entry_Quick_Create_Form extends DevKit.Controls.ITab {
Section: tab_Time_Entry_Quick_Create_Form_Sections;
}
interface Tabs {
Time_Entry_Quick_Create_Form: tab_Time_Entry_Quick_Create_Form;
}
interface Body {
Tab: Tabs;
/** Enter the time entry date. */
msdyn_date: DevKit.Controls.Date;
/** Type the description of the time entry. */
msdyn_description: DevKit.Controls.String;
/** Shows the time spent. */
msdyn_duration: DevKit.Controls.Integer;
/** Type the external description of the time entry. */
msdyn_externalDescription: DevKit.Controls.String;
/** Select the project that the time entry is related to. */
msdyn_project: DevKit.Controls.Lookup;
/** Select the project task that the time entry is related to. */
msdyn_projectTask: DevKit.Controls.Lookup;
/** Select the role that the user has in the project that the time entry is for. */
msdyn_resourceCategory: DevKit.Controls.Lookup;
/** Unique identifier for Time Source associated with Time Entry. */
msdyn_timeentrysettingId: DevKit.Controls.Lookup;
/** Select the time entry type. */
msdyn_type: DevKit.Controls.OptionSet;
}
}
class FormCreate_Time_Entry extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Create_Time_Entry
* @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 Create_Time_Entry */
Body: DevKit.FormCreate_Time_Entry.Body;
}
namespace FormField_Service_Quick_Create {
interface tab_Time_Entry_Quick_Create_Form_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
}
interface tab_Time_Entry_Quick_Create_Form extends DevKit.Controls.ITab {
Section: tab_Time_Entry_Quick_Create_Form_Sections;
}
interface Tabs {
Time_Entry_Quick_Create_Form: tab_Time_Entry_Quick_Create_Form;
}
interface Body {
Tab: Tabs;
/** Shows the bookable resource. */
msdyn_bookableresource: DevKit.Controls.Lookup;
/** Unique identifier for Resource Booking associated with Time Entry. */
msdyn_BookableResourceBooking: DevKit.Controls.Lookup;
/** Booking Status */
msdyn_BookingStatus: DevKit.Controls.Lookup;
/** Type the description of the time entry. */
msdyn_description: DevKit.Controls.String;
/** Shows the time spent. */
msdyn_duration: DevKit.Controls.Integer;
/** The end time of the time entry. */
msdyn_end: DevKit.Controls.DateTime;
/** Select the entry status. */
msdyn_entryStatus: DevKit.Controls.OptionSet;
/** Type the external description of the time entry. */
msdyn_externalDescription: DevKit.Controls.String;
/** The start time of the time entry. */
msdyn_start: DevKit.Controls.DateTime;
/** Unique identifier for Time Source associated with Time Entry. */
msdyn_timeentrysettingId: DevKit.Controls.Lookup;
/** Unique identifier for Time Off Request associated with Time Entry. This field is auto-populated when a Time Entry is auto-created from a Time Off Request. */
msdyn_timeoffrequest: DevKit.Controls.Lookup;
/** Select the time entry type. */
msdyn_type: DevKit.Controls.OptionSet;
/** Unique identifier for Work Orders associated with Time Entry. */
msdyn_WorkOrder: DevKit.Controls.Lookup;
}
}
class FormField_Service_Quick_Create extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Field_Service_Quick_Create
* @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 Field_Service_Quick_Create */
Body: DevKit.FormField_Service_Quick_Create.Body;
}
namespace FormTESA_Time_Entry_Quick_Create_Form {
interface tab_tab_1_Sections {
tab_1_column_1_section_1: DevKit.Controls.Section;
tab_1_column_2_section_1: DevKit.Controls.Section;
tab_1_column_3_section_1: DevKit.Controls.Section;
}
interface tab_tab_1 extends DevKit.Controls.ITab {
Section: tab_tab_1_Sections;
}
interface Tabs {
tab_1: tab_tab_1;
}
interface Body {
Tab: Tabs;
}
}
class FormTESA_Time_Entry_Quick_Create_Form extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form TESA_Time_Entry_Quick_Create_Form
* @param executionContext the execution context
* @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource"
*/
constructor(executionContext: any, defaultWebResourceName?: string);
/** Utility functions/methods/objects for Dynamics 365 form */
Utility: DevKit.Utility;
/** The Body section of form TESA_Time_Entry_Quick_Create_Form */
Body: DevKit.FormTESA_Time_Entry_Quick_Create_Form.Body;
}
class msdyn_timeentryApi {
/**
* DynamicsCrm.DevKit msdyn_timeentryApi
* @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;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** 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;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the bookable resource. */
msdyn_bookableresource: DevKit.WebApi.LookupValue;
/** Unique identifier for Resource Booking associated with Time Entry. */
msdyn_BookableResourceBooking: DevKit.WebApi.LookupValue;
/** Booking Status */
msdyn_BookingStatus: DevKit.WebApi.LookupValue;
/** Enter the time entry date. */
msdyn_date_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Type the description of the time entry. */
msdyn_description: DevKit.WebApi.StringValue;
/** Shows the time spent. */
msdyn_duration: DevKit.WebApi.IntegerValue;
/** The end time of the time entry. */
msdyn_end_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Select the entry status. */
msdyn_entryStatus: DevKit.WebApi.OptionSetValue;
/** Type the external description of the time entry. */
msdyn_externalDescription: DevKit.WebApi.StringValue;
/** For internal use only. */
msdyn_internalflags: DevKit.WebApi.StringValue;
/** Select the manager of the time entry user. This field is used for approval. */
msdyn_manager: DevKit.WebApi.LookupValue;
/** Select the project that the time entry is related to. */
msdyn_project: DevKit.WebApi.LookupValue;
/** Select the project task that the time entry is related to. */
msdyn_projectTask: DevKit.WebApi.LookupValue;
/** The identifier of the related item. */
msdyn_relatedItemId: DevKit.WebApi.StringValue;
/** The related item type */
msdyn_relatedItemType: DevKit.WebApi.OptionSetValue;
/** Select the role that the user has in the project that the time entry is for. */
msdyn_resourceCategory: DevKit.WebApi.LookupValue;
/** Select the organizational unit at the time the entry was registered of the resource who performed the work. */
msdyn_ResourceOrganizationalUnitId: DevKit.WebApi.LookupValue;
/** The start time of the time entry. */
msdyn_start_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
msdyn_targetEntryStatus: DevKit.WebApi.OptionSetValue;
/** The unique identifier for a time entry. */
msdyn_timeentryId: DevKit.WebApi.GuidValue;
/** Unique identifier for Time Source associated with Time Entry. */
msdyn_timeentrysettingId: DevKit.WebApi.LookupValue;
/** Unique identifier for Time Off Request associated with Time Entry. This field is auto-populated when a Time Entry is auto-created from a Time Off Request. */
msdyn_timeoffrequest: DevKit.WebApi.LookupValue;
/** Shows the transaction category. */
msdyn_transactioncategory: DevKit.WebApi.LookupValue;
/** Select the time entry type. */
msdyn_type: DevKit.WebApi.OptionSetValue;
/** Unique identifier for Work Orders associated with Time Entry. */
msdyn_WorkOrder: DevKit.WebApi.LookupValue;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValue;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValue;
/** Unique identifier 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;
/** Contains the id of the process associated with the entity. */
processid: DevKit.WebApi.GuidValue;
/** Contains the id of the stage where the entity is located. */
stageid: DevKit.WebApi.GuidValue;
/** Status of the Time Entry */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Time Entry */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */
traversedpath: DevKit.WebApi.StringValue;
/** 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_timeentry {
enum msdyn_entryStatus {
/** 192350002 */
Approved,
/** 192354320 */
Cancelled,
/** 192350000 */
Draft,
/** 192350004 */
Recall_Requested,
/** 192350001 */
Returned,
/** 192350003 */
Submitted
}
enum msdyn_relatedItemType {
/** 192350100 */
Exchange_Appointments,
/** 192350000 */
None,
/** 192350002 */
Resource_Assignment,
/** 192350001 */
Resource_Booking
}
enum msdyn_targetEntryStatus {
/** 192350002 */
Approved,
/** 192354320 */
Cancelled,
/** 192350000 */
Draft,
/** 192350004 */
Recall_Requested,
/** 192350001 */
Returned,
/** 192350003 */
Submitted
}
enum msdyn_type {
/** 192350001 */
Absence,
/** 192355000 */
On_Break,
/** 192354320 */
Overtime,
/** 192355001 */
Travel,
/** 192350002 */
Vacation,
/** 192350000 */
Work
}
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':['Create Time Entry','Entry Edit Form','Field Service Information','Information','Row Edit Form','Quick Create','Main Form','Quick Create Form'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { Octokit } from "@octokit/rest";
import { OctokitResponse } from "@octokit/types";
import { beforeAll, expect, jest, test } from "@jest/globals";
import { git, gitConfig } from "../lib/git";
import { GitHubGlue, IGitHubUser, IPullRequestInfo } from "../lib/github-glue";
/*
This test requires setup. It will run successfully if setup has
not been done. If the test fails, there may be a pull request and a
branch to be deleted on github and the local repo. The test will
attempt cleanup of a previously failed test.
Setup:
gitgitgadget.githubTest.gitHubUser must be configured for this test to
identify your GitHub login.
The value must also be configured to identify a test repo to use as
gitgitgadget.<login>.gitHubRepo.
Additionally, a GitHub personal access token must be set for the
login to succeed. This can be restricted to the test repo.
For example, these configuration settings are needed (where
`octo-kitty` is your GitHub login):
git config --add gitgitgadget.CIGitHubTestUser octo-kitty
git config --add gitgitgadget.octo-kitty.gitHubRepo ggg-test
git config --add gitgitgadget.octo-kitty.gitHubToken feedbeef...
The test repo must exist in github and locally. It is expected to be
located at the same directory level as this project (ie ../).
*/
class GitHubProxy extends GitHubGlue {
public octo: Octokit;
public constructor(workDir?: string, repo = "git") {
super(workDir, repo);
this.octo = this.client;
}
public async authenticate(repositoryOwner: string): Promise<void> {
await this.ensureAuthenticated(repositoryOwner);
this.octo = this.client;
}
public fakeAuthenticated(repositoryOwner: string): void {
this.authenticated = repositoryOwner;
}
}
jest.setTimeout(180000);
let owner: string;
let repo: string;
beforeAll(async () => {
owner = await gitConfig(`gitgitgadget.CIGitHubTestUser`) || "";
repo = await gitConfig(`gitgitgadget.${owner}.gitHubRepo`) || "";
});
test("identify user", async () => {
if (owner && repo) {
const userName = await gitConfig(`user.name`, `../${repo}`) || "";
const github = new GitHubProxy(`../${repo}`, repo);
await github.authenticate(owner);
const ghUser = await github.getGitHubUserInfo(owner);
expect(ghUser.login).toMatch(owner);
expect(ghUser.name).toMatch(userName);
}
});
test("pull requests", async () => {
if (owner && repo) {
const repoDir = `../${repo}`;
const github = new GitHubProxy(repoDir, repo);
await github.authenticate(owner);
const content = Buffer.from("test data").toString("base64");
const branchBase = `ggg-test-branch-${process.platform}`;
const titleBase = `ggg Test pulls integration-${process.platform}`;
const oldPrs = await github.getOpenPRs(owner);
let suffix = "";
// Clean up in case a previous test failed
// NOTE: Runs on GitHub and Azure pipelines use a timestamped
// branch/PR request that gets cleaned up separately.
if (!process.env.GITHUB_WORKFLOW &&
!process.env.hasOwnProperty("system.definitionId")) {
let pullRequestURL = "";
oldPrs.map(pr => {
if (pr.title === titleBase) { // need to clean up?
pullRequestURL = pr.pullRequestURL;
}
});
if (pullRequestURL.length) {
await github.closePR(pullRequestURL, "Not merged");
}
try { // delete remote branch
await github.octo.rest.git.deleteRef({
owner,
ref: `heads/${branchBase}`,
repo,
});
} catch (e) {
const error = e as Error;
expect(error.toString()).toMatch(/Reference does not exist/);
}
try { // delete local branch
await git(["branch", "-D", branchBase], { workDir: repoDir });
} catch (e) {
const error = e as Error;
expect(error.toString()).toMatch(/not found/);
}
}
else
{
const now = new Date();
suffix = `_${now.toISOString().replace(/[:.]/g, "_")}`;
}
const branch = branchBase + suffix;
const branchRef = `refs/heads/${branch}`;
const title = titleBase + suffix;
const gRef = await github.octo.rest.git.getRef({
owner,
ref: `heads/master`,
repo,
});
const cRef = await github.octo.rest.git.createRef({
owner,
ref: branchRef,
repo,
sha: gRef.data.object.sha,
});
expect(cRef.data.object.sha).toMatch(gRef.data.object.sha);
const cFile = await github.octo.rest.repos.createOrUpdateFileContents({
branch,
content,
message: "Commit a new file",
owner,
path: "foo.txt",
repo,
});
const newPR = await github.octo.rest.pulls.create({
base: "master",
body: "Test for a pull request\r\non a test repo.",
head: branch,
owner,
repo,
title,
});
const prData = newPR.data;
const prs = await github.getOpenPRs(owner);
expect(prs[0].author).toMatch(owner);
const commits = await github.getPRCommits(owner, prData.number);
expect(commits[0].author.login).toMatch(owner);
expect(cFile.data.commit.sha).toMatch(commits[0].commit);
const prInfo = await github.getPRInfo(owner, prData.number);
expect(prInfo.headLabel).toMatch(branch);
// Test update to PR body
const prBody = `${prInfo.body}\r\nGlue`;
await github.updatePR(owner, prData.number, prBody);
const prNewInfo = await github.getPRInfo(owner, prData.number);
expect(prNewInfo.body).toMatch(prBody);
// Test update to PR title
const prTitle = `${prInfo.title} Glue`;
await github.updatePR(owner, prData.number, undefined, prTitle);
const prNewTitle = await github.getPRInfo(owner, prData.number);
expect(prNewTitle.title).toMatch(prTitle);
const newComment = "Adding a comment to the PR";
const {id, url} = await github.addPRComment(prData.html_url,
newComment);
expect(url).toMatch(id.toString());
const comment = await github.getPRComment(owner, id);
expect(comment.body).toMatch(newComment);
// update the local repo to test commit comment
await git(["fetch", "origin", "--", `+${branchRef}:${branchRef}`],
{ workDir: repoDir });
const commitComment = "comment about commit";
const reviewResult = await github
.addPRCommitComment(prData.html_url, cFile.data.commit.sha || '',
repoDir, commitComment);
const commentReply =
await github.addPRCommentReply(prData.html_url,
reviewResult.id, newComment);
expect(commentReply.url).toMatch(commentReply.id.toString());
await github.addPRLabels(prData.html_url, ["bug"]);
const cNumber = await github.closePR(prData.html_url, "Not merged");
expect(cNumber).toBeGreaterThan(id);
// delete local and remote branches
try {
await github.octo.rest.git.deleteRef({
owner,
ref: `heads/${branch}`,
repo,
});
await git(["branch", "-D", branch], { workDir: repoDir });
} catch (error) {
console.log(`command failed\n${error}`);
}
}
});
test("add PR cc requests", async () => {
const github = new GitHubGlue();
const prInfo = {
author: "ggg",
baseCommit: "A",
baseLabel: "gitgitgadget:next",
baseOwner: "gitgitgadget",
baseRepo: "git",
body: "Basic commit description.",
hasComments: true,
headCommit: "B",
headLabel: "somebody:master",
mergeable: true,
number: 59,
pullRequestURL: "https://github.com/webstech/gitout/pull/59",
title: "Submit a fun fix",
};
const commentInfo = { id: 1, url: "ok" };
github.addPRComment = jest.fn( async ():
// eslint-disable-next-line @typescript-eslint/require-await
Promise<{id: number; url: string}> => commentInfo );
const updatePR = jest.fn( async (_owner: string, _prNumber: number,
body: string):
// eslint-disable-next-line @typescript-eslint/require-await
Promise<number> => {
prInfo.body = body; // set new body for next test
return 1;
});
github.updatePR = updatePR;
github.getPRInfo = jest.fn( async ():
// eslint-disable-next-line @typescript-eslint/require-await
Promise<IPullRequestInfo> => prInfo);
const ghUser = {
email: "joe_kerr@example.org",
login: "joekerr",
name: "Joe Kerr",
type: "unknown",
};
github.getGitHubUserInfo= jest.fn( async ():
// eslint-disable-next-line @typescript-eslint/require-await
Promise<IGitHubUser> => ghUser);
// Test cc update to PR
const prCc = "Not Real <ReallyNot@saturn.cosmos>";
const prCc2 = "Not Real <RealNot@saturn.cosmos>";
const prCcGitster = "Git Real <gitster@pobox.com>"; // filtered out
// Test with no linefeed
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(1);
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(1);
updatePR.mock.calls.length = 0;
// Test with linefeeds present
prInfo.body = `Test\r\n\r\nGlue`;
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(1);
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(1);
await github.addPRCc(prInfo.pullRequestURL, prCc.toLowerCase());
expect(updatePR.mock.calls).toHaveLength(1);
await github.addPRCc(prInfo.pullRequestURL, prCc2);
expect(updatePR.mock.calls).toHaveLength(2);
await github.addPRCc(prInfo.pullRequestURL, prCcGitster);
expect(updatePR.mock.calls).toHaveLength(2);
const prCcOwner = `${ghUser.name} <${ghUser.email}>`;
await github.addPRCc(prInfo.pullRequestURL, prCcOwner);
expect(updatePR.mock.calls).toHaveLength(2);
await github.addPRCc(prInfo.pullRequestURL, prCcOwner.toUpperCase());
expect(updatePR.mock.calls).toHaveLength(2);
updatePR.mock.calls.length = 0;
// Test with 3 linefeeds present
prInfo.body = `Test\r\n\r\n\r\ncc: ${prCc}`;
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(0);
updatePR.mock.calls.length = 0;
// Test with linefeeds and unknown footers
prInfo.body = `Test\r\n \t\r\nbb: x\r\ncc: ${prCc}`;
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(0);
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(0);
// Test with linefeeds and unknown footer containing email
prInfo.body = `Test\r\n \t\r\nbb: ${prCc}`;
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(1);
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(1);
updatePR.mock.calls.length = 0;
// Test to ignore last block in body with cc: for last line
prInfo.body = `Test\r\n\r\nfoo\r\nCC: ${prCc}`;
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(1);
updatePR.mock.calls.length = 0;
// Test to catch only block in body is footers
prInfo.body = `CC: ${prCc}\r\nbb: bar`;
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(0);
// Test to catch only block in body is footers
prInfo.body = `CC: ${prCc}\r\nbb: bar`;
await github.addPRCc(prInfo.pullRequestURL, prCc2);
expect(updatePR.mock.calls).toHaveLength(1);
updatePR.mock.calls.length = 0;
// Test to catch only block in body is cc footer
prInfo.body = `CC: ${prCc}; ${prCc2}`;
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(0);
// Test to catch only block in body is not really footers
prInfo.body = `foo bar\r\nCC: ${prCc}`;
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(1);
updatePR.mock.calls.length = 0;
// Test to catch only block in body is not really footers
prInfo.body = `CC: ${prCc}\r\nfoo bar`;
await github.addPRCc(prInfo.pullRequestURL, prCc);
expect(updatePR.mock.calls).toHaveLength(1);
updatePR.mock.calls.length = 0;
});
test("test missing values in response using small schema", async () => {
if (!owner) {
owner = "tester";
}
const github = new GitHubProxy();
github.fakeAuthenticated(owner);
/**
* These tests use a basic schema consisting of only fields of interest. To
* use the full schema, the types have to match octokit.
*
* For example:
*
* @example Objects would be typed like this:
* const sampleUser: components["schemas"]["simple-user"] = {...};
* const pullRequestSimple:
* components["schemas"]["pull-request-simple"] = {...};
*
* @example Responses would be typed like this:
* const prListResponse:
* RestEndpointMethodTypes["pulls"]["list"]["response"] = {
* status: 200,
* headers: { status: "200 OK" },
* url: "",
* data: [pullRequestSimple],
* };
*
*/
interface IBasicUser {
login: string;
type: string;
email: string | null;
}
interface ISimpleUser extends IBasicUser {
name: string;
}
const sampleUser: ISimpleUser = {
login: "someString",
type: "someString",
name: "foo",
email: null,
};
interface IRepository {
name: string;
owner: ISimpleUser | null;
}
const testRepo: IRepository = {
name: "gitout",
owner: sampleUser,
};
interface IPullRequestSimple {
html_url: string;
number: number;
title: string;
user: ISimpleUser | null;
body: string | null;
created_at: string;
updated_at: string;
head: {
label: string;
repo: IRepository;
sha: string;
};
base: {
label: string;
repo: IRepository;
sha: string;
};
mergeable: boolean;
comments: number;
commits: number;
}
const pullRequestSimple: IPullRequestSimple = {
html_url: "someString",
number: 22,
title: "someString",
user: null, // ISimpleUser | null,
body: null, // string | null,
created_at: "someString",
updated_at: "someString",
head: {
label: "someString",
repo: testRepo,
sha: "someString",
},
base: {
label: "someString",
repo: testRepo,
sha: "someString",
},
mergeable: true,
comments: 0,
commits: 1,
};
const prListResponse: OctokitResponse<IPullRequestSimple[]> = {
status: 200,
headers: { status: "200 OK" },
url: "",
data: [pullRequestSimple],
};
// Response for any octokit calls - will be returned by the hook.wrap()
// being set below.
let response: OctokitResponse<IPullRequestSimple[]> |
OctokitResponse<IPullRequestSimple> |
OctokitResponse<IIssueComment> |
OctokitResponse<[ICommit]> |
OctokitResponse<IPrivateUser>;
response = prListResponse;
// eslint-disable-next-line @typescript-eslint/require-await
github.octo.hook.wrap("request", async () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return response;
});
// if (!pr.user || !pr.base.repo.owner) {
await expect(github.getOpenPRs(owner)).rejects.toThrow(/is missing info/);
pullRequestSimple.user = sampleUser;
pullRequestSimple.base.repo.owner = null;
await expect(github.getOpenPRs(owner)).rejects.toThrow(/is missing info/);
const prInfoResponse: OctokitResponse<IPullRequestSimple> = {
status: 200,
headers: { status: "200 OK" },
url: "",
data: pullRequestSimple,
};
response = prInfoResponse; // reset response value
pullRequestSimple.user = null;
pullRequestSimple.base.repo.owner = sampleUser;
// if (!pullRequest.user) {
await expect(github.getPRInfo(owner, 2)).rejects.toThrow(/is missing info/);
interface IIssueComment {
body?: string;
html_url: string;
user: ISimpleUser | null;
}
const issueCommentResponse: OctokitResponse<IIssueComment> = {
status: 200,
headers: { status: "200 OK" },
url: "",
data: {
html_url: "someString",
user: null, // sampleUser,
},
};
response = issueCommentResponse; // reset response value
// if (!response.data.user) {
await expect(github.getPRComment(owner, 77)).rejects.toThrow(
/is missing info/
);
interface ICommit {
commit: {
author: ISimpleUser | null;
committer: ISimpleUser | null;
message: string;
};
author: ISimpleUser | null;
committer: ISimpleUser | null;
parents: [{ sha: string; url: string; html_url?: string }];
}
const commitObj: ICommit = {
commit: {
author: sampleUser, // ISimpleUser | null;
committer: sampleUser, // ISimpleUser | null;
message: "someString",
},
author: null,
committer: null,
parents: [{ sha: "someString", url: "someString" }],
};
const getCommitsResponse: OctokitResponse<[ICommit]> = {
status: 200,
headers: { status: "200 OK" },
url: "",
data: [commitObj],
};
response = getCommitsResponse; // reset response value
// if (!cm.commit.committer || !cm.commit.author || !cm.sha) {
await expect(github.getPRCommits(owner, 22)).rejects.toThrow(
/information missing/
);
commitObj.commit.author = null;
await expect(github.getPRCommits(owner, 22)).rejects.toThrow(
/information missing/
);
commitObj.commit.committer = null;
await expect(github.getPRCommits(owner, 22)).rejects.toThrow(
/information missing/
);
interface IPrivateUser extends IBasicUser {
name: string | null;
}
const userNameResponse: OctokitResponse<IPrivateUser> = {
status: 200,
headers: { status: "200 OK" },
url: "",
data: sampleUser,
};
response = userNameResponse; // reset response value
(sampleUser as IPrivateUser).name = null;
expect(await github.getGitHubUserInfo(owner)).toBeTruthy();
}); | the_stack |
import {
AfterContentInit,
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
ElementRef,
Input,
OnInit,
Renderer2,
ViewChild,
ViewEncapsulation,
ContentChildren,
QueryList,
NgZone,
Directive,
OnDestroy,
HostListener,
HostBinding,
Optional,
Self,
DoCheck,
InjectionToken,
Inject,
} from '@angular/core';
import {
LyTheme2,
ThemeVariables,
toBoolean,
StyleCollection,
LyClasses,
StyleTemplate,
StyleRenderer,
lyl,
ThemeRef,
LY_COMMON_STYLES,
keyframesUniqueId,
WithStyles,
Style
} from '@alyle/ui';
import { LyLabel } from './label';
import { LyPlaceholder } from './placeholder';
import { LyHint } from './hint';
import { LyPrefix } from './prefix';
import { LySuffix } from './suffix';
import { Subject, merge } from 'rxjs';
import { NgControl, NgForm, FormGroupDirective } from '@angular/forms';
import { LyError } from './error';
import { LyFieldControlBase } from './field-control-base';
import { Platform } from '@angular/cdk/platform';
import { LyDisplayWith } from './display-with';
import { takeUntil, take } from 'rxjs/operators';
import { BooleanInput, coerceBooleanProperty } from '@angular/cdk/coercion';
export interface LyFieldTheme {
/** Styles for Field Component */
root?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
| ((classes: LyClasses<typeof STYLES>) => StyleTemplate);
appearance?: {
standard?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
| ((classes: LyClasses<typeof STYLES>) => StyleTemplate)
filled?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
| ((classes: LyClasses<typeof STYLES>) => StyleTemplate)
outlined?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
| ((classes: LyClasses<typeof STYLES>) => StyleTemplate)
[name: string]: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
| ((classes: LyClasses<typeof STYLES>) => StyleTemplate) | undefined
};
}
export interface LyFieldVariables {
field?: LyFieldTheme;
}
export interface LyFieldDefaultOptions {
appearance?: string;
/**
* Whether the label is floating.
* false (default): The label will only float when needed
* true: The label will always be floating
*/
floatingLabel?: boolean;
/**
* Whether the hint will always show.
* false (default): The hint will only be shown when the text is focused
* true: The hint will always show
*/
persistentHint?: boolean;
/**
* Floating label size
* Default: 0.75
*/
floatingLabelSize?: number;
/**
* Whether the required marker should be hidden.
*/
hideRequiredMarker?: boolean;
}
export const LY_FIELD_DEFAULT_OPTIONS =
new InjectionToken<LyFieldDefaultOptions>('LY_FIELD_DEFAULT_OPTIONS');
/** LyField */
const STYLE_PRIORITY = -2;
const DEFAULT_APPEARANCE = 'standard';
const DEFAULT_WITH_COLOR = 'primary';
const DEFAULT_FLOATING_LABEL_SIZE = 0.75;
const inputText = [
'text',
'number',
'password',
'search',
'tel',
'url'
];
export const STYLE_SELECT_ARROW = lyl `{
&::after {
position: absolute
content: ''
width: 0
height: 0
border-left: 0.3125em solid transparent
border-right: 0.3125em solid transparent
border-top: 0.3125em solid
top: 50%
{after}: 0
margin-top: -0.15625em
pointer-events: none
}
}`;
const MIXIN_CDK_TEXTAREA_AUTOSIZE_MEASURING_BASE = lyl `{
padding: 2px 0 !important
box-sizing: content-box !important
}`;
const STYLE_AUTOSIZE = lyl `{
textarea.cdk-textarea-autosize {
resize: none
}
textarea.cdk-textarea-autosize-measuring {
...${MIXIN_CDK_TEXTAREA_AUTOSIZE_MEASURING_BASE}
height: auto !important
overflow: hidden !important
}
textarea.cdk-textarea-autosize-measuring-firefox {
...${MIXIN_CDK_TEXTAREA_AUTOSIZE_MEASURING_BASE}
height: 0 !important
}
}`;
export const STYLES = (theme: ThemeVariables & LyFieldVariables, ref: ThemeRef) => {
const classes = ref.selectorsOf(STYLES);
const {before, after } = theme;
const shake = keyframesUniqueId.next();
return {
$priority: STYLE_PRIORITY,
$global: lyl `{
@keyframes ${shake} {
0% {
margin-${before}: 0
}
40% {
margin-${before}: 2px
}
50% {
margin-${before}: -2px
}
70% {
margin-${before}: 2px
}
100% {
margin-${before}: 0
}
}
...${STYLE_AUTOSIZE}
}`,
root: ( ) => lyl `{
display: inline-block
position: relative
line-height: 1.125
${classes.hint}, ${classes.error} {
display: block
}
${classes.label}, ${classes.placeholder} {
ly-icon {
font-size: inherit
}
}
${classes.prefix}, ${classes.suffix} {
position: relative
white-space: nowrap
flex: none
}
{
...${
(theme.field
&& theme.field.root
&& (theme.field.root instanceof StyleCollection
? theme.field.root.setTransformer(fn => fn(classes))
: theme.field.root(classes))
)
}
}
}`,
animations: ( ) => lyl `{
& ${classes.labelSpan} {
transition: ${theme.animations.curves.deceleration} .${theme.animations.durations.complex}s
}
& ${classes.label} {
transition: ${theme.animations.curves.deceleration} .${theme.animations.durations.complex}s
}
}`,
container: lyl `{
height: 100%
display: flex
align-items: baseline
position: relative
-webkit-tap-highlight-color: transparent
box-sizing: border-box
&:after {
...${LY_COMMON_STYLES.fill}
content: ''
pointer-events: none
}
}`,
fieldset: lyl `{
...${LY_COMMON_STYLES.fill}
margin: 0
border-style: solid
border-width: 0
}`,
fieldsetSpan: lyl `{
padding: 0
height: 2px
}`,
prefix: lyl `{
max-height: 2em
}`,
infix: lyl `{
display: inline-flex
position: relative
min-width: 0
width: 180px
flex: auto
}`,
suffix: lyl `{
max-height: 2em
}`,
labelContainer: lyl `{
...${LY_COMMON_STYLES.fill}
pointer-events: none
display: flex
width: 100%
}`,
labelSpacingStart: null,
labelCenter: lyl `{
display: flex
max-width: 100%
}`,
labelSpacingEnd: lyl `{
flex: 1
}`,
label: lyl `{
...${LY_COMMON_STYLES.fill}
margin: 0
border: none
pointer-events: none
overflow: hidden
width: 100%
height: 100%
}`,
labelSpan: lyl `{
white-space: nowrap
text-overflow: ellipsis
overflow: hidden
display: block
width: 100%
height: 100%
transform-origin: ${before} 0
}`,
isFloatingLabel: null,
floatingLabel: null,
placeholder: lyl `{
...${LY_COMMON_STYLES.fill}
pointer-events: none
white-space: nowrap
text-overflow: ellipsis
overflow: hidden
}`,
focused: () => lyl `{
&:not(${classes.errorState}) ${classes.fieldRequiredMarker} {
color: ${theme.accent.default}
}
}`,
inputNative: lyl `{
padding: 0
outline: none
border: none
background-color: transparent
color: inherit
font: inherit
width: 100%
textarea& {
padding: 2px 0
margin: -2px 0
resize: vertical
overflow: auto
}
select& {
-moz-appearance: none
-webkit-appearance: none
position: relative
background-color: transparent
display: inline-flex
box-sizing: border-box
padding-${after}: 1em
option:not([disabled]) {
color: initial
}
optgroup:not([disabled]) {
color: initial
}
}
select&::-ms-expand {
display: none
}
select&::-moz-focus-inner {
border: 0
}
select&:not(:disabled) {
cursor: pointer
}
select&::-ms-value {
color: inherit
background: 0 0
}
}`,
/** Is used to hide the input when `displayWith` is shown */
_hiddenInput: lyl `{
color: transparent
}`,
displayWith: lyl `{
...${LY_COMMON_STYLES.fill}
white-space: nowrap
text-overflow: ellipsis
overflow: hidden
width: 100%
pointer-events: none
}`,
hintContainer: lyl `{
min-height: 1.25em
font-size: 0.75em
margin-top: .25em
> div {
display: flex
max-width: 100%
overflow: hidden
justify-content: space-between
align-items: center
}
}`,
disabled: ( ) => lyl `{
&, & ${classes.label}, & ${classes.container}:after {
color: ${theme.disabled.contrast}
cursor: default
}
}`,
hint: null,
fieldRequiredMarker: null,
error: null,
errorState: ( ) => lyl `{
& ${classes.label}, & ${classes.hintContainer}, &${classes.selectArrow} ${classes.infix}:after {
color: ${theme.warn.default}!important
}
& ${classes.fieldset}, & ${classes.container}:after {
border-color: ${theme.warn.default}!important
}
& ${classes.inputNative} {
caret-color: ${theme.warn.default}!important
}
& ${classes.hintContainer} ly-hint:not(${classes.hintAfter}) {
display: none
}
& ${classes.labelSpan} {
animation: ${shake} ${theme.animations.durations.complex}ms ${theme.animations.curves.deceleration}
}
& ${classes.inputNative}::selection, & ${classes.inputNative}::-moz-selection {
background-color: ${theme.warn.default} !important
color: ${theme.warn.contrast} !important
}
}`,
hintAfter: lyl `{
margin-${before}: auto
}`,
hintBefore: lyl `{
margin-${after}: auto
}`,
selectArrow: ( ) => lyl `{
${classes.infix} {
&::after {
position: absolute
content: ''
width: 0
height: 0
border-left: 0.3125em solid transparent
border-right: 0.3125em solid transparent
border-top: 0.3125em solid
top: 0
${after}: 0
pointer-events: none
}
}
}`
};
};
/**
* @dynamic
*/
@Component({
selector: 'ly-field',
exportAs: 'lyFormField',
templateUrl: 'field.html',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
providers: [
StyleRenderer,
]
})
export class LyField implements WithStyles, OnInit, AfterContentInit, AfterViewInit, OnDestroy {
/**
* styles
* @docs-private
*/
readonly classes = this._theme.renderStyleSheet(STYLES);
protected _appearance: string;
protected _appearanceClass: string;
protected _color: string;
protected _colorClass: string;
protected _isFloating: boolean;
protected _floatingLabel: boolean;
private _destroyed = new Subject<void>();
private _fielsetSpanClass: string;
private _fullWidth: boolean;
private _fullWidthClass?: string;
private _updateFielsetSpanOnStable: boolean;
@ViewChild('_container', { static: true }) _container: ElementRef<HTMLDivElement>;
@ViewChild('_labelContainer') _labelContainer: ElementRef<HTMLDivElement>;
@ViewChild('_labelContainer2') _labelContainer2: ElementRef<HTMLDivElement>;
@ViewChild('_labelSpan') _labelSpan: ElementRef<HTMLDivElement>;
@ViewChild('_prefixContainer') _prefixContainer: ElementRef<HTMLDivElement>;
@ViewChild('_suffixContainer') _suffixContainer: ElementRef<HTMLDivElement>;
@ContentChild(LyFieldControlBase) _controlNonStatic?: LyFieldControlBase;
@ContentChild(LyFieldControlBase, { static: true }) _controlStatic: LyFieldControlBase<any>;
get _control() {
// Support both Ivy and ViewEngine.
return this._controlNonStatic || this._controlStatic;
}
@ContentChild(LyPlaceholder) _placeholderChild: LyPlaceholder;
@ContentChild(LyLabel) _labelChild: LyLabel;
@ContentChild(LyDisplayWith) readonly _displayWithChild: QueryList<LyDisplayWith>;
@ContentChildren(LyHint) _hintChildren: QueryList<LyHint>;
@ContentChildren(LyPrefix) _prefixChildren: QueryList<LyPrefix>;
@ContentChildren(LySuffix) _suffixChildren: QueryList<LySuffix>;
@ContentChildren(LyError) _errorChildren: QueryList<LyError>;
get errorState() {
return this._control ? this._control.errorState : false;
}
get displayWithStatus() {
return !!(this._displayWithChild
&& this._control
&& !this._control.empty
&& !this._control.focused
&& !this._control.errorState);
}
/** Whether the required marker should be hidden. */
@Input()
get hideRequiredMarker(): boolean {
return this._hideRequiredMarker;
}
set hideRequiredMarker(value: boolean) {
this._hideRequiredMarker = coerceBooleanProperty(value);
}
private _hideRequiredMarker: boolean;
@Input() persistentHint: boolean;
/**
* Floating label size
* Default: 0.75
*/
@Input()
@Style(
(val, media) => ({ breakpoints }: ThemeVariables, ref) => {
const classes = ref.selectorsOf(STYLES);
return lyl `{
@media ${(media && breakpoints[media]) || 'all'} {
${classes.floatingLabel} ${classes.labelSpan} {
transform: scale(${val})
width: ${Math.round(100 / 0.75)}%
}
}
}`;
}
)
floatingLabelSize: number | null;
@Input()
set fullWidth(val: boolean) {
const newVal = toBoolean(val);
if (newVal) {
this._fullWidthClass = this._theme.addStyle(
`fullWidth`,
{
display: 'block',
width: '100%'
},
this._getHostElement(),
this._fullWidthClass,
STYLE_PRIORITY
);
} else if (this._fullWidthClass) {
this._renderer.removeClass(this._getHostElement(), this._fullWidthClass);
this._fullWidthClass = undefined;
}
this._fullWidth = newVal;
}
get fullWidth() {
return this._fullWidth;
}
/** Whether the label is floating. */
@Input()
set floatingLabel(val: boolean) {
this._floatingLabel = toBoolean(val);
this._updateFloatingLabel();
}
get floatingLabel() {
return this._floatingLabel;
}
/** Theme color for the component. */
@Input()
@Style<string>(
val => (theme: ThemeVariables, ref) => {
const classes = ref.selectorsOf(STYLES);
const color = theme.colorOf(val);
const contrast = theme.colorOf(`${val}:contrast`);
return lyl `{
&${classes.focused} ${classes.container}:after,
&${classes.focused}${classes.selectArrow} ${classes.infix}:after {
color: ${color}
}
&${classes.focused} ${classes.fieldset} {
border-color: ${color}
}
&${classes.focused} ${classes.label} {
color: ${color}
}
& ${classes.inputNative} {
caret-color: ${color}
}
& ${classes.inputNative}::selection {
background-color: ${color}
color: ${contrast}
}
& ${classes.inputNative}::-moz-selection {
background-color: ${color}
color: ${contrast}
}
}`;
}
) color: string;
/** The field appearance style. */
@Input()
@Style<string | null>(
val => (theme: LyFieldVariables, ref) => {
const classes = ref.selectorsOf(STYLES);
if (theme.field?.appearance) {
const appearance = theme.field.appearance[val];
if (appearance) {
return appearance instanceof StyleCollection
? appearance.setTransformer((_) => _(classes)).css
: appearance(classes);
}
}
throw new Error(`[${val}] not found in theme.field.appearance`);
},
STYLE_PRIORITY
)
set appearance(val: string | null) {
if (val === 'outlined') {
this._updateFielsetSpanOnStable = true;
}
}
@HostListener('focus') onFocus() {
this._el.nativeElement.focus();
}
constructor(
private _renderer: Renderer2,
private _el: ElementRef,
private _theme: LyTheme2,
private _cd: ChangeDetectorRef,
private _ngZone: NgZone,
readonly sRenderer: StyleRenderer,
private _platform: Platform,
@Optional() @Inject(LY_FIELD_DEFAULT_OPTIONS)
private _defaults: LyFieldDefaultOptions
) {
_renderer.addClass(_el.nativeElement, this.classes.root);
this._hideRequiredMarker =
_defaults?.hideRequiredMarker != null ? _defaults.hideRequiredMarker : false;
}
ngOnInit() {
if (!this.color) {
this.color = DEFAULT_WITH_COLOR;
}
if (this.floatingLabelSize == null) {
this.floatingLabelSize = (this._defaults?.floatingLabelSize != null)
? this._defaults?.floatingLabelSize
: DEFAULT_FLOATING_LABEL_SIZE;
}
if (!this.appearance) {
this.appearance = this._defaults?.appearance ? this._defaults?.appearance : DEFAULT_APPEARANCE;
}
if (this.persistentHint == null) {
this.persistentHint = (this._defaults?.persistentHint != null) ? this._defaults.persistentHint : false;
}
if (this.floatingLabel == null) {
this.floatingLabel = (this._defaults?.floatingLabel != null) ? this._defaults.floatingLabel : false;
}
}
ngAfterContentInit() {
this._control!.stateChanges.subscribe(() => {
this._updateFloatingLabel();
this._updateDisplayWith();
this._markForCheck();
});
const ngControl = this._control!.ngControl;
// Run change detection if the value changes.
if (ngControl && ngControl.valueChanges) {
ngControl.valueChanges.pipe(takeUntil(this._destroyed)).subscribe(() => {
this._updateFloatingLabel();
this._updateDisplayWith();
this._markForCheck();
});
}
this._ngZone.runOutsideAngular(() => {
this._ngZone.onStable.pipe(takeUntil(this._destroyed)).subscribe(() => {
if (this._updateFielsetSpanOnStable) {
this._updateFielsetSpan();
}
});
this._ngZone.onStable.pipe(take(1), takeUntil(this._destroyed)).subscribe(() => {
this._updateDisplayWith();
this._renderer.addClass(this._el.nativeElement, this.classes.animations);
});
});
merge(this._prefixChildren.changes, this._suffixChildren.changes).subscribe(() => {
this._updateFielsetSpanOnStable = true;
this._markForCheck();
});
}
ngAfterViewInit() {
this._updateFielsetSpan();
this._updateFloatingLabel();
}
ngOnDestroy() {
this._destroyed.next();
this._destroyed.complete();
}
_updateFielsetSpan() {
if (!this._platform.isBrowser) {
return;
}
if (this.floatingLabelSize == null) {
return;
}
if (this.appearance !== 'outlined') {
return;
}
const label = this._isLabel() ? this._labelSpan.nativeElement : null;
const labelChildren = this._isLabel()
? this._labelSpan.nativeElement.children
: null;
if (!label) {
return;
}
const before = this._theme.variables.before;
const fieldsetLegend = this._getHostElement().querySelector('legend');
if (!fieldsetLegend) {
this._updateFielsetSpanOnStable = true;
return;
}
const labelRect = label.getBoundingClientRect();
const container = this._container.nativeElement;
const containerRect = this._container.nativeElement.getBoundingClientRect();
let width = 0;
for (let index = 0; index < labelChildren!.length; index++) {
width += labelChildren![index].getBoundingClientRect().width;
}
const percent = containerRect.width / container.offsetWidth;
const labelPercent = labelRect.width / label.offsetWidth;
let beforeMargin = Math.abs(
(containerRect[before] - labelRect[before]) / percent) - 12;
width /= labelPercent;
width *= this.floatingLabelSize;
// add 6px of space
width += 6;
width = width > (label.parentElement!.offsetWidth)
? (label.parentElement!.offsetWidth)
: width;
width = Math.round(width);
beforeMargin = Math.round(beforeMargin);
fieldsetLegend.style[`margin-right`] = ``;
fieldsetLegend.style[`margin-left`] = ``;
fieldsetLegend.style[`margin-${before}`] = `${beforeMargin}px`;
this._updateFielsetSpanOnStable = false;
this._fielsetSpanClass = this._theme.addStyle(`style.fieldsetSpanFocused:${width}`, {
[`&.${this.classes.isFloatingLabel} .${this.classes.fieldsetSpan}`]: {width: `${width}px`}
}, this._el.nativeElement, this._fielsetSpanClass, STYLE_PRIORITY);
}
/** @ignore */
_isLabel() {
if (this._control && this._control.placeholder && !this._labelChild) {
return true;
} else if (this._labelChild || this._placeholderChild) {
return true;
}
return false;
}
/** @ignore */
_isPlaceholder() {
if ((this._labelChild && this._control && this._control.placeholder) || (this._labelChild && this._placeholderChild)) {
return true;
}
return false;
}
/** @ignore */
_isEmpty() {
const val = this._control ? this._control.value : null;
return val === '' || val === null || val === undefined;
}
private _updateFloatingLabel() {
if (this._labelContainer2) {
const isFloating = this._control!.floatingLabel || this.floatingLabel;
if (this._isFloating !== isFloating) {
this._isFloating = isFloating;
if (isFloating) {
this._renderer.addClass(this._labelContainer2.nativeElement, this.classes.floatingLabel);
this._renderer.addClass(this._el.nativeElement, this.classes.isFloatingLabel);
} else {
this._renderer.removeClass(this._labelContainer2.nativeElement, this.classes.floatingLabel);
this._renderer.removeClass(this._el.nativeElement, this.classes.isFloatingLabel);
}
}
}
if (this._control) {
if (this._control.focused) {
this._renderer.addClass(this._el.nativeElement, this.classes.focused);
} else {
this._renderer.removeClass(this._el.nativeElement, this.classes.focused);
}
}
}
private _updateDisplayWith() {
if (this._control) {
this._control.sRenderer.toggleClass(this.classes._hiddenInput, this.displayWithStatus);
}
}
private _markForCheck() {
this._cd.markForCheck();
}
_getHostElement() {
return this._el.nativeElement;
}
static ngAcceptInputType_hideRequiredMarker: BooleanInput;
}
@Directive({
selector:
'input[lyInput], textarea[lyInput], input[lyNativeControl], textarea[lyNativeControl], select[lyNativeControl]',
exportAs: 'LyNativeControl',
providers: [
StyleRenderer,
{ provide: LyFieldControlBase, useExisting: LyNativeControl }
]
})
export class LyNativeControl implements LyFieldControlBase, OnInit, DoCheck, OnDestroy {
protected _disabled = false;
protected _required = false;
protected _placeholder: string;
readonly stateChanges: Subject<void> = new Subject<void>();
private _hasDisabledClass?: boolean;
private _errorClass?: string;
private _cursorClass: string | null;
private _isSelectInput: boolean;
private _form: NgForm | FormGroupDirective | null = this._parentForm || this._parentFormGroup;
_focused: boolean = false;
errorState: boolean = false;
@HostListener('input') _onInput() {
this.stateChanges.next();
}
@HostListener('blur') _onBlur() {
if (this._focused !== false) {
this._focused = false;
this.stateChanges.next();
}
}
@HostListener('focus') _onFocus() {
if (this._focused !== true) {
this._focused = true;
this.stateChanges.next();
}
}
/** @ignore */
@Input()
set value(val) {
if (val !== this.value) {
this._getHostElement().value = val;
this.stateChanges.next();
}
}
get value() {
return this._getHostElement().value;
}
/** Whether the input is disabled. */
@HostBinding()
@Input()
set disabled(val: boolean) {
if (val !== this._disabled) {
this._disabled = toBoolean(val);
if (this._field) {
if (!val && this._hasDisabledClass) {
this._renderer.removeClass(this._field._getHostElement(), this._field.classes.disabled);
if (this._cursorClass) {
this._renderer.addClass(this._field._getHostElement(), this._cursorClass);
}
this._hasDisabledClass = undefined;
} else if (val) {
this._renderer.addClass(this._field._getHostElement(), this._field.classes.disabled);
if (this._cursorClass) {
this._renderer.removeClass(this._field._getHostElement(), this._cursorClass);
}
this._hasDisabledClass = true;
}
}
}
}
get disabled(): boolean {
if (this.ngControl && this.ngControl.disabled !== null) {
return this.ngControl.disabled;
}
return this._disabled;
}
@HostBinding()
@Input()
set required(value: boolean) {
this._required = coerceBooleanProperty(value);
}
get required(): boolean { return this._required; }
@Input()
set placeholder(val: string) {
this._placeholder = val;
}
get placeholder(): string { return this._placeholder; }
get focused() {
return this._focused;
}
get empty() {
const val = this.value;
return val === '' || val == null;
}
get floatingLabel() {
return this.focused || !this.empty || (this._isSelectInput ? this._hasLabelSelectionOption() : false);
}
constructor(
private _theme: LyTheme2,
readonly sRenderer: StyleRenderer,
private _el: ElementRef<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>,
private _renderer: Renderer2,
@Optional() private _field: LyField,
/** @docs-private */
@Optional() @Self() public ngControl: NgControl,
@Optional() private _parentForm: NgForm,
@Optional() private _parentFormGroup: FormGroupDirective
) { }
ngOnInit() {
this._renderer.setAttribute(this._getHostElement(), 'placeholder', '');
const { nativeElement } = this._el;
if (nativeElement.nodeName.toLowerCase() === 'select') {
this._isSelectInput = true;
}
// apply class {selectArrow} to `<select> not multiple`
if (this._field && nativeElement.type === 'select-one') {
this._renderer.addClass(this._field._getHostElement(), this._field.classes.selectArrow);
}
// apply style cursor only for input of type text
if (nativeElement instanceof HTMLTextAreaElement ||
inputText.some(type => type === nativeElement.type)) {
this._cursorClass = this._theme.addSimpleStyle('lyField.text', {
'& {infix}': {
cursor: 'text'
}
}, STYLE_PRIORITY, STYLES);
}
if (this._isSelectInput) {
this._cursorClass = this._theme.addSimpleStyle('lyField.select', {
'& {infix}': {
cursor: 'pointer'
}
}, STYLE_PRIORITY, STYLES);
}
if (this._cursorClass) {
this._renderer.addClass(this._field._getHostElement(), this._cursorClass);
}
// apply default styles
this._renderer.addClass(nativeElement, this._field.classes.inputNative);
const ngControl = this.ngControl;
// update styles on disabled
if (ngControl && ngControl.statusChanges) {
ngControl.statusChanges.subscribe(() => {
this.disabled = !!ngControl.disabled;
});
}
}
ngDoCheck() {
if (this._field._control) {
const oldVal = this.errorState;
const newVal = !!(this.ngControl && this.ngControl.invalid && (this.ngControl.touched || (this._form && this._form.submitted)));
if (newVal !== oldVal) {
this.errorState = newVal;
if (this._field) {
const errorClass = this._field.classes.errorState;
if (newVal) {
this._renderer.addClass(this._field._getHostElement(), errorClass);
this._errorClass = errorClass;
} else if (this._errorClass) {
this._renderer.removeClass(this._field._getHostElement(), errorClass);
this._errorClass = undefined;
}
this.stateChanges.next();
}
}
}
}
ngOnDestroy() {
this.stateChanges.complete();
}
/** @docs-private */
onContainerClick(_e: MouseEvent) {
this._getHostElement().focus();
}
/** Focuses the input. */
focus(): void { this._getHostElement().focus(); }
_getHostElement() {
return this._el.nativeElement;
}
private _hasLabelSelectionOption() {
const el = this._getHostElement() as HTMLSelectElement;
const option = el.selectedOptions ? el.selectedOptions.item(0) : null;
return option ? !!option.label : false;
}
} | the_stack |
import * as vscode from '@vscode/debugadapter'
import { DebugProtocol as VSCodeDebugProtocol } from '@vscode/debugprotocol'
import * as net from 'net'
import * as xdebug from './xdebugConnection'
import moment = require('moment')
import * as url from 'url'
import * as childProcess from 'child_process'
import * as path from 'path'
import * as util from 'util'
import * as fs from 'fs'
import { Terminal } from './terminal'
import { convertClientPathToDebugger, convertDebuggerPathToClient } from './paths'
import minimatch = require('minimatch')
import { BreakpointManager, BreakpointAdapter } from './breakpoints'
import * as semver from 'semver'
import { LogPointManager } from './logpoint'
import { ProxyConnect } from './proxyConnect'
import { randomUUID } from 'crypto'
if (process.env['VSCODE_NLS_CONFIG']) {
try {
moment.locale(JSON.parse(process.env['VSCODE_NLS_CONFIG']).locale)
} catch (e) {
// ignore
}
}
/** formats a xdebug property value for VS Code */
function formatPropertyValue(property: xdebug.BaseProperty): string {
let displayValue: string
if (property.hasChildren || property.type === 'array' || property.type === 'object') {
if (property.type === 'array') {
// for arrays, show the length, like a var_dump would do
displayValue = 'array(' + (property.hasChildren ? property.numberOfChildren : 0) + ')'
} else if (property.type === 'object' && property.class) {
// for objects, show the class name as type (if specified)
displayValue = property.class
} else {
// edge case: show the type of the property as the value
displayValue = property.type
}
} else {
// for null, uninitialized, resource, etc. show the type
displayValue = property.value || property.type === 'string' ? property.value : property.type
if (property.type === 'string') {
displayValue = '"' + displayValue + '"'
} else if (property.type === 'bool') {
displayValue = !!parseInt(displayValue) + ''
}
}
return displayValue
}
/**
* This interface should always match the schema found in the mock-debug extension manifest.
*/
export interface LaunchRequestArguments extends VSCodeDebugProtocol.LaunchRequestArguments {
/** Name of the configuration */
name?: string
/** The address to bind to for listening for Xdebug connections (default: all IPv6 connections if available, else all IPv4 connections) or unix socket */
hostname?: string
/** The port where the adapter should listen for Xdebug connections (default: 9003) */
port?: number
/** Automatically stop target after launch. If not specified, target does not stop. */
stopOnEntry?: boolean
/** The source root on the server when doing remote debugging on a different host */
serverSourceRoot?: string
/** The path to the source root on this machine that is the equivalent to the serverSourceRoot on the server. */
localSourceRoot?: string
/** The path to the source root on this machine that is the equivalent to the serverSourceRoot on the server. */
pathMappings?: { [index: string]: string }
/** If true, will log all communication between VS Code and the adapter to the console */
log?: boolean
/** Array of glob patterns that errors should be ignored from */
ignore?: string[]
/** Xdebug configuration */
xdebugSettings?: { [featureName: string]: string | number }
/** proxy connection configuration */
proxy?: {
allowMultipleSessions: boolean
enable: boolean
host: string
key: string
port: number
timeout: number
}
// CLI options
/** If set, launches the specified PHP script in CLI mode */
program?: string
/** Optional arguments passed to the debuggee. */
args?: string[]
/** Launch the debuggee in this working directory (specified as an absolute path). If omitted the debuggee is launched in its own directory. */
cwd?: string
/** Absolute path to the runtime executable to be used. Default is the runtime executable on the PATH. */
runtimeExecutable?: string
/** Optional arguments passed to the runtime executable. */
runtimeArgs?: string[]
/** Optional environment variables to pass to the debuggee. The string valued properties of the 'environmentVariables' are used as key/value pairs. */
env?: { [key: string]: string }
/** If true launch the target in an external console. */
externalConsole?: boolean
/** Maximum allowed parallel debugging sessions */
maxConnections?: number
}
class PhpDebugSession extends vscode.DebugSession {
/** The arguments that were given to launchRequest */
private _args: LaunchRequestArguments
/** The TCP server that listens for Xdebug connections */
private _server: net.Server
/** The child process of the launched PHP script, if launched by the debug adapter */
private _phpProcess?: childProcess.ChildProcess
/**
* A map from VS Code thread IDs to Xdebug Connections.
* Xdebug makes a new connection for each request to the webserver, we present these as threads to VS Code.
* The threadId key is equal to the id attribute of the connection.
*/
private _connections = new Map<number, xdebug.Connection>()
/** A counter for unique source IDs */
private _sourceIdCounter = 1
/** A map of VS Code source IDs to Xdebug file URLs for virtual files (dpgp://whatever) and the corresponding connection */
private _sources = new Map<number, { connection: xdebug.Connection; url: string }>()
/** A counter for unique stackframe IDs */
private _stackFrameIdCounter = 1
/** A map from unique stackframe IDs (even across connections) to Xdebug stackframes */
private _stackFrames = new Map<number, xdebug.StackFrame>()
/** A map from Xdebug connections to their current status */
private _statuses = new Map<xdebug.Connection, xdebug.StatusResponse>()
/** A counter for unique context, property and eval result properties (as these are all requested by a VariableRequest from VS Code) */
private _variableIdCounter = 1
/** A map from unique VS Code variable IDs to Xdebug statuses for virtual error stack frames */
private _errorStackFrames = new Map<number, xdebug.StatusResponse>()
/** A map from unique VS Code variable IDs to Xdebug statuses for virtual error scopes */
private _errorScopes = new Map<number, xdebug.StatusResponse>()
/** A map from unique VS Code variable IDs to an Xdebug contexts */
private _contexts = new Map<number, xdebug.Context>()
/** A map from unique VS Code variable IDs to a Xdebug properties */
private _properties = new Map<number, xdebug.Property>()
/** A map from unique VS Code variable IDs to Xdebug eval result properties, because property children returned from eval commands are always inlined */
private _evalResultProperties = new Map<number, xdebug.EvalResultProperty>()
/** A flag to indicate that the adapter has already processed the stopOnEntry step request */
private _hasStoppedOnEntry = false
/** Breakpoint Manager to map VS Code to Xdebug breakpoints */
private _breakpointManager = new BreakpointManager()
/** Breakpoint Adapters */
private _breakpointAdapters = new Map<xdebug.Connection, BreakpointAdapter>()
/**
* The manager for logpoints. Since xdebug does not support anything like logpoints,
* it has to be managed by the extension/debug server. It does that by a Map referencing
* the log messages per file. Xdebug sees it as a regular breakpoint.
*/
private _logPointManager = new LogPointManager()
/** The proxy initialization and termination connection. */
private _proxyConnect: ProxyConnect
/** the promise that gets resolved once we receive the done request */
private _donePromise: Promise<void>
/** resolves the done promise */
private _donePromiseResolveFn: () => any
public constructor() {
super()
this.setDebuggerColumnsStartAt1(true)
this.setDebuggerLinesStartAt1(true)
this.setDebuggerPathFormat('uri')
}
protected initializeRequest(
response: VSCodeDebugProtocol.InitializeResponse,
args: VSCodeDebugProtocol.InitializeRequestArguments
): void {
response.body = {
supportsConfigurationDoneRequest: true,
supportsEvaluateForHovers: true,
supportsConditionalBreakpoints: true,
supportsFunctionBreakpoints: true,
supportsLogPoints: true,
supportsHitConditionalBreakpoints: true,
supportsSetVariable: true,
exceptionBreakpointFilters: [
{
filter: 'Notice',
label: 'Notices',
},
{
filter: 'Warning',
label: 'Warnings',
},
{
filter: 'Error',
label: 'Errors',
},
{
filter: 'Exception',
label: 'Exceptions',
},
{
filter: '*',
label: 'Everything',
},
],
supportTerminateDebuggee: true,
supportsDelayedStackTraceLoading: false,
}
this.sendResponse(response)
}
protected attachRequest(
response: VSCodeDebugProtocol.AttachResponse,
args: VSCodeDebugProtocol.AttachRequestArguments
) {
this.sendErrorResponse(response, new Error('Attach requests are not supported'))
this.shutdown()
}
protected async launchRequest(response: VSCodeDebugProtocol.LaunchResponse, args: LaunchRequestArguments) {
if (args.localSourceRoot && args.serverSourceRoot) {
let pathMappings: { [index: string]: string } = {}
if (args.pathMappings) {
pathMappings = args.pathMappings
}
pathMappings[args.serverSourceRoot] = args.localSourceRoot
args.pathMappings = pathMappings
}
this._args = args
this._donePromise = new Promise<void>((resolve, reject) => {
this._donePromiseResolveFn = resolve
})
/** launches the script as CLI */
const launchScript = async (port: number | string) => {
// check if program exists
if (args.program) {
await new Promise<void>((resolve, reject) =>
fs.access(args.program!, fs.constants.F_OK, err => (err ? reject(err) : resolve()))
)
}
const runtimeArgs = (args.runtimeArgs || []).map(v => v.replace('${port}', port.toString()))
const runtimeExecutable = args.runtimeExecutable || 'php'
const programArgs = args.args || []
const program = args.program ? [args.program] : []
const cwd = args.cwd || process.cwd()
const env = Object.fromEntries(
Object.entries({ ...process.env, ...args.env }).map(v => [
v[0],
v[1]?.replace('${port}', port.toString()),
])
)
// launch in CLI mode
if (args.externalConsole) {
const script = await Terminal.launchInTerminal(
cwd,
[runtimeExecutable, ...runtimeArgs, ...program, ...programArgs],
env
)
if (script) {
// we only do this for CLI mode. In normal listen mode, only a thread exited event is send.
script.on('exit', (code: number | null) => {
this.sendEvent(new vscode.ExitedEvent(code ?? 0))
this.sendEvent(new vscode.TerminatedEvent())
})
}
} else {
const script = childProcess.spawn(runtimeExecutable, [...runtimeArgs, ...program, ...programArgs], {
cwd,
env,
})
// redirect output to debug console
script.stdout.on('data', (data: Buffer) => {
this.sendEvent(new vscode.OutputEvent(data + '', 'stdout'))
})
script.stderr.on('data', (data: Buffer) => {
this.sendEvent(new vscode.OutputEvent(data + '', 'stderr'))
})
// we only do this for CLI mode. In normal listen mode, only a thread exited event is send.
script.on('exit', (code: number | null) => {
this.sendEvent(new vscode.ExitedEvent(code ?? 0))
this.sendEvent(new vscode.TerminatedEvent())
})
script.on('error', (error: Error) => {
this.sendEvent(new vscode.OutputEvent(util.inspect(error) + '\n'))
})
this._phpProcess = script
}
}
/** sets up a TCP server to listen for Xdebug connections */
const createServer = () =>
new Promise<number | string>((resolve, reject) => {
const server = (this._server = net.createServer())
server.on('connection', async (socket: net.Socket) => {
try {
// new Xdebug connection
// first check if we have a limit on connections
if (args.maxConnections ?? 0 > 0) {
if (this._connections.size >= args.maxConnections!) {
if (args.log) {
this.sendEvent(
new vscode.OutputEvent(
`new connection from ${socket.remoteAddress} - dropping due to max connection limit\n`
),
true
)
}
socket.end()
return
}
}
const connection = new xdebug.Connection(socket)
if (args.log) {
this.sendEvent(
new vscode.OutputEvent(
`new connection ${connection.id} from ${socket.remoteAddress}\n`
),
true
)
}
this._connections.set(connection.id, connection)
const disposeConnection = (error?: Error) => {
if (this._connections.has(connection.id)) {
if (args.log) {
this.sendEvent(new vscode.OutputEvent(`connection ${connection.id} closed\n`))
}
if (error) {
this.sendEvent(
new vscode.OutputEvent(`connection ${connection.id}: ${error.message}\n`)
)
}
this.sendEvent(new vscode.ContinuedEvent(connection.id, false))
this.sendEvent(new vscode.ThreadEvent('exited', connection.id))
connection.close()
this._connections.delete(connection.id)
this._statuses.delete(connection)
this._breakpointAdapters.delete(connection)
}
}
connection.on('warning', (warning: string) => {
this.sendEvent(new vscode.OutputEvent(warning + '\n'))
})
connection.on('error', disposeConnection)
connection.on('close', disposeConnection)
connection.on('log', (text: string) => {
if (this._args && this._args.log) {
const log = `xd(${connection.id}) ${text}\n`
this.sendEvent(new vscode.OutputEvent(log), true)
}
})
try {
const initPacket = await connection.waitForInitPacket()
// support for breakpoints
let feat: xdebug.FeatureGetResponse
const supportedEngine =
initPacket.engineName === 'Xdebug' &&
semver.valid(initPacket.engineVersion, { loose: true }) &&
semver.gte(initPacket.engineVersion, '3.0.0', { loose: true })
const supportedEngine32 =
initPacket.engineName === 'Xdebug' &&
semver.valid(initPacket.engineVersion, { loose: true }) &&
semver.gte(initPacket.engineVersion, '3.2.0', { loose: true })
if (
supportedEngine ||
((feat = await connection.sendFeatureGetCommand('resolved_breakpoints')) &&
feat.supported === '1')
) {
await connection.sendFeatureSetCommand('resolved_breakpoints', '1')
}
if (
supportedEngine ||
((feat = await connection.sendFeatureGetCommand('notify_ok')) && feat.supported === '1')
) {
await connection.sendFeatureSetCommand('notify_ok', '1')
connection.on('notify_user', notify => this.handleUserNotify(notify, connection))
}
if (
supportedEngine ||
((feat = await connection.sendFeatureGetCommand('extended_properties')) &&
feat.supported === '1')
) {
await connection.sendFeatureSetCommand('extended_properties', '1')
}
if (
supportedEngine32 ||
((feat = await connection.sendFeatureGetCommand('breakpoint_include_return_value')) &&
feat.supported === '1')
) {
await connection.sendFeatureSetCommand('breakpoint_include_return_value', '1')
}
// override features from launch.json
try {
const xdebugSettings = args.xdebugSettings || {}
// Required defaults for indexedVariables
xdebugSettings.max_children = xdebugSettings.max_children || 100
await Promise.all(
Object.keys(xdebugSettings).map(setting =>
connection.sendFeatureSetCommand(setting, xdebugSettings[setting])
)
)
args.xdebugSettings = xdebugSettings
} catch (error) {
throw new Error(
'Error applying xdebugSettings: ' + (error instanceof Error ? error.message : error)
)
}
this.sendEvent(new vscode.ThreadEvent('started', connection.id))
// wait for all breakpoints
await this._donePromise
let bpa = new BreakpointAdapter(connection, this._breakpointManager)
bpa.on('dapEvent', event => this.sendEvent(event))
this._breakpointAdapters.set(connection, bpa)
// sync breakpoints to connection
await bpa.process()
let xdebugResponse: xdebug.StatusResponse
// either tell VS Code we stopped on entry or run the script
if (this._args.stopOnEntry) {
// do one step to the first statement
this._hasStoppedOnEntry = false
xdebugResponse = await connection.sendStepIntoCommand()
} else {
xdebugResponse = await connection.sendRunCommand()
}
this._checkStatus(xdebugResponse)
} catch (error) {
this.sendEvent(
new vscode.OutputEvent(
`Failed initializing connection ${connection.id}: ` +
(error instanceof Error ? error.message : error) +
'\n',
'stderr'
)
)
disposeConnection()
socket.destroy()
}
} catch (error) {
this.sendEvent(
new vscode.OutputEvent(
'Error in socket server: ' + (error instanceof Error ? error.message : error) + '\n',
'stderr'
)
)
this.shutdown()
}
})
server.on('error', (error: Error) => {
this.sendEvent(new vscode.OutputEvent(util.inspect(error) + '\n'))
reject(error)
})
server.on('listening', () => {
if (args.log) {
this.sendEvent(new vscode.OutputEvent(`Listening on ${util.inspect(server.address())}\n`), true)
}
if (typeof server.address() === 'string') {
resolve(<string>server.address())
} else {
const port = (server.address() as net.AddressInfo).port
resolve(port)
}
})
if (
args.port !== undefined &&
(args.hostname?.toLowerCase()?.startsWith('unix://') === true ||
args.hostname?.startsWith('\\\\') === true)
) {
throw new Error('Cannot have port and socketPath set at the same time')
}
if (args.hostname?.toLowerCase()?.startsWith('unix://') === true) {
server.listen(args.hostname.substring(7))
} else if (args.hostname?.startsWith('\\\\') === true) {
server.listen(args.hostname)
} else {
const listenPort = args.port === undefined ? 9003 : args.port
server.listen(listenPort, args.hostname)
}
})
try {
// Some checks
if (args.env !== undefined && args.program === undefined && args.runtimeArgs === undefined) {
throw new Error(
`Cannot set env without running a program.\nPlease remove env from [${args.name}] configuration.`
)
}
if (
(args.hostname?.toLowerCase()?.startsWith('unix://') === true ||
args.hostname?.startsWith('\\\\') === true) &&
args.proxy?.enable === true
) {
throw new Error('Proxy does not support socket path listen, only port.')
}
let port = <number | string>0
if (!args.noDebug) {
port = await createServer()
if (typeof port === 'number' && args.proxy?.enable === true) {
await this.setupProxy(port)
}
}
if (args.program || args.runtimeArgs) {
await launchScript(port)
}
} catch (error) {
this.sendErrorResponse(response, <Error>error)
return
}
this.sendResponse(response)
// request breakpoints
this.sendEvent(new vscode.InitializedEvent())
}
private async setupProxy(idePort: number): Promise<void> {
this._proxyConnect = new ProxyConnect(
this._args.proxy!.host,
this._args.proxy!.port,
idePort,
this._args.proxy!.allowMultipleSessions,
this._args.proxy!.key,
this._args.proxy!.timeout
)
const proxyConsole = (str: string) => this.sendEvent(new vscode.OutputEvent(str + '\n'), true)
this._proxyConnect.on('log_request', proxyConsole)
this._proxyConnect.on('log_response', proxyConsole)
this._proxyConnect.on('log_error', (error: Error) => {
this.sendEvent(new vscode.OutputEvent('PROXY ERROR: ' + error.message + '\n', 'stderr'))
})
return this._proxyConnect.sendProxyInitCommand()
}
/**
* Checks the status of a StatusResponse and notifies VS Code accordingly
* @param {xdebug.StatusResponse} response
*/
private async _checkStatus(response: xdebug.StatusResponse): Promise<void> {
const connection = response.connection
this._statuses.set(connection, response)
if (response.status === 'stopping') {
const response = await connection.sendStopCommand()
this._checkStatus(response)
} else if (response.status === 'stopped') {
this._connections.delete(connection.id)
this._statuses.delete(connection)
this._breakpointAdapters.delete(connection)
this.sendEvent(new vscode.ThreadEvent('exited', connection.id))
connection.close()
} else if (response.status === 'break') {
// First sync breakpoints
let bpa = this._breakpointAdapters.get(connection)
if (bpa) {
await bpa.process()
}
// StoppedEvent reason can be 'step', 'breakpoint', 'exception' or 'pause'
let stoppedEventReason: 'step' | 'breakpoint' | 'exception' | 'pause' | 'entry'
let exceptionText: string | undefined
if (response.exception) {
// If one of the ignore patterns matches, ignore this exception
if (
this._args.ignore &&
this._args.ignore.some(glob =>
minimatch(convertDebuggerPathToClient(response.fileUri).replace(/\\/g, '/'), glob)
)
) {
const response = await connection.sendRunCommand()
await this._checkStatus(response)
return
}
stoppedEventReason = 'exception'
exceptionText = response.exception.name + ': ' + response.exception.message // this seems to be ignored currently by VS Code
} else if (this._args.stopOnEntry && !this._hasStoppedOnEntry) {
stoppedEventReason = 'entry'
this._hasStoppedOnEntry = true
} else if (response.command.indexOf('step') === 0) {
stoppedEventReason = 'step'
} else {
stoppedEventReason = 'breakpoint'
}
// Check for log points
if (this._logPointManager.hasLogPoint(response.fileUri, response.line)) {
const logMessage = await this._logPointManager.resolveExpressions(
response.fileUri,
response.line,
async (expr: string): Promise<string> => {
const evaluated = await connection.sendEvalCommand(expr)
return formatPropertyValue(evaluated.result)
}
)
this.sendEvent(new vscode.OutputEvent(logMessage + '\n', 'console'))
if (stoppedEventReason === 'breakpoint') {
const responseCommand = await connection.sendRunCommand()
await this._checkStatus(responseCommand)
return
}
}
const event: VSCodeDebugProtocol.StoppedEvent = new vscode.StoppedEvent(
stoppedEventReason,
connection.id,
exceptionText
)
event.body.allThreadsStopped = false
this.sendEvent(event)
}
}
/** Logs all requests before dispatching */
protected dispatchRequest(request: VSCodeDebugProtocol.Request): void {
if (this._args && this._args.log) {
const log = `-> ${request.command}Request\n${util.inspect(request, { depth: Infinity })}\n\n`
super.sendEvent(new vscode.OutputEvent(log))
}
super.dispatchRequest(request)
}
public sendEvent(event: VSCodeDebugProtocol.Event, bypassLog: boolean = false): void {
if (this._args && this._args.log && !bypassLog) {
const log = `<- ${event.event}Event\n${util.inspect(event, { depth: Infinity })}\n\n`
super.sendEvent(new vscode.OutputEvent(log))
}
super.sendEvent(event)
}
public sendResponse(response: VSCodeDebugProtocol.Response): void {
if (this._args && this._args.log) {
const log = `<- ${response.command}Response\n${util.inspect(response, { depth: Infinity })}\n\n`
super.sendEvent(new vscode.OutputEvent(log))
}
super.sendResponse(response)
}
protected sendErrorResponse(
response: VSCodeDebugProtocol.Response,
error: Error,
dest?: vscode.ErrorDestination
): void
protected sendErrorResponse(
response: VSCodeDebugProtocol.Response,
codeOrMessage: number | VSCodeDebugProtocol.Message,
format?: string,
variables?: any,
dest?: vscode.ErrorDestination
): void
protected sendErrorResponse(response: VSCodeDebugProtocol.Response) {
if (arguments[1] instanceof Error) {
const error = arguments[1] as Error & { code?: number | string; errno?: number }
const dest = arguments[2] as vscode.ErrorDestination
let code: number
if (typeof error.code === 'number') {
code = error.code as number
} else if (typeof error.errno === 'number') {
code = error.errno
} else {
code = 0
}
super.sendErrorResponse(response, code, error.message, dest)
} else {
super.sendErrorResponse(response, arguments[1], arguments[2], arguments[3], arguments[4])
}
}
protected handleUserNotify(notify: xdebug.UserNotify, connection: xdebug.Connection) {
if (notify.property !== undefined) {
const event: VSCodeDebugProtocol.OutputEvent = new vscode.OutputEvent('', 'stdout')
const property = new xdebug.SyntheticProperty('', 'object', formatPropertyValue(notify.property), [
notify.property,
])
let variablesReference = this._variableIdCounter++
this._evalResultProperties.set(variablesReference, property)
event.body.variablesReference = variablesReference
if (notify.fileUri.startsWith('file://')) {
const filePath = convertDebuggerPathToClient(notify.fileUri, this._args.pathMappings)
event.body.source = { name: path.basename(filePath), path: filePath }
event.body.line = notify.line
}
this.sendEvent(event)
}
}
/** This is called for each source file that has breakpoints with all the breakpoints in that file and whenever these change. */
protected async setBreakPointsRequest(
response: VSCodeDebugProtocol.SetBreakpointsResponse,
args: VSCodeDebugProtocol.SetBreakpointsArguments
) {
try {
const fileUri = convertClientPathToDebugger(args.source.path!, this._args.pathMappings)
const vscodeBreakpoints = this._breakpointManager.setBreakPoints(args.source, fileUri, args.breakpoints!)
response.body = { breakpoints: vscodeBreakpoints }
// Process logpoints
this._logPointManager.clearFromFile(fileUri)
args.breakpoints!.filter(breakpoint => breakpoint.logMessage).forEach(breakpoint => {
this._logPointManager.addLogPoint(fileUri, breakpoint.line, breakpoint.logMessage!)
})
} catch (error) {
this.sendErrorResponse(response, error)
return
}
this.sendResponse(response)
this._breakpointManager.process()
}
/** This is called once after all line breakpoints have been set and whenever the breakpoints settings change */
protected async setExceptionBreakPointsRequest(
response: VSCodeDebugProtocol.SetExceptionBreakpointsResponse,
args: VSCodeDebugProtocol.SetExceptionBreakpointsArguments
) {
try {
const vscodeBreakpoints = this._breakpointManager.setExceptionBreakPoints(args.filters)
response.body = { breakpoints: vscodeBreakpoints }
} catch (error) {
this.sendErrorResponse(response, error)
return
}
this.sendResponse(response)
this._breakpointManager.process()
}
protected async setFunctionBreakPointsRequest(
response: VSCodeDebugProtocol.SetFunctionBreakpointsResponse,
args: VSCodeDebugProtocol.SetFunctionBreakpointsArguments
) {
try {
const vscodeBreakpoints = this._breakpointManager.setFunctionBreakPointsRequest(args.breakpoints)
response.body = { breakpoints: vscodeBreakpoints }
} catch (error) {
this.sendErrorResponse(response, error)
return
}
this.sendResponse(response)
this._breakpointManager.process()
}
/** Executed after all breakpoints have been set by VS Code */
protected async configurationDoneRequest(
response: VSCodeDebugProtocol.ConfigurationDoneResponse,
args: VSCodeDebugProtocol.ConfigurationDoneArguments
) {
this.sendResponse(response)
this._donePromiseResolveFn()
}
/** Executed after a successful launch or attach request and after a ThreadEvent */
protected threadsRequest(response: VSCodeDebugProtocol.ThreadsResponse): void {
// PHP doesn't have threads, but it may have multiple requests in parallel.
// Think about a website that makes multiple, parallel AJAX requests to your PHP backend.
// Xdebug opens a new socket connection for each of them, we tell VS Code that these are our threads.
const connections = Array.from(this._connections.values())
response.body = {
threads: connections.map(
connection =>
new vscode.Thread(
connection.id,
`Request ${connection.id} (${moment(connection.timeEstablished).format('LTS')})`
)
),
}
this.sendResponse(response)
}
/** Called by VS Code after a StoppedEvent */
protected async stackTraceRequest(
response: VSCodeDebugProtocol.StackTraceResponse,
args: VSCodeDebugProtocol.StackTraceArguments
) {
try {
const connection = this._connections.get(args.threadId)
if (!connection) {
throw new Error('Unknown thread ID')
}
let { stack } = await connection.sendStackGetCommand()
// First delete the old stack trace info ???
// this._stackFrames.clear();
// this._properties.clear();
// this._contexts.clear();
const status = this._statuses.get(connection)
if (stack.length === 0 && status && status.exception) {
// special case: if a fatal error occurs (for example after an uncaught exception), the stack trace is EMPTY.
// in that case, VS Code would normally not show any information to the user at all
// to avoid this, we create a virtual stack frame with the info from the last status response we got
const status = this._statuses.get(connection)!
const id = this._stackFrameIdCounter++
const name = status.exception.name
let line = status.line
let source: VSCodeDebugProtocol.Source
const urlObject = url.parse(status.fileUri)
if (urlObject.protocol === 'dbgp:') {
let sourceReference
const src = Array.from(this._sources).find(
([, v]) => v.url === status.fileUri && v.connection === connection
)
if (src) {
sourceReference = src[0]
} else {
sourceReference = this._sourceIdCounter++
this._sources.set(sourceReference, { connection, url: status.fileUri })
}
// for eval code, we need to include .php extension to get syntax highlighting
source = { name: status.exception.name + '.php', sourceReference, origin: status.exception.name }
// for eval code, we add a "<?php" line at the beginning to get syntax highlighting (see sourceRequest)
line++
} else {
// Xdebug paths are URIs, VS Code file paths
const filePath = convertDebuggerPathToClient(urlObject, this._args.pathMappings)
// "Name" of the source and the actual file path
source = { name: path.basename(filePath), path: filePath }
}
this._errorStackFrames.set(id, status)
response.body = { stackFrames: [{ id, name, source, line, column: 1 }] }
} else {
const totalFrames = stack.length
stack = stack.slice(args.startFrame, args.levels ? (args.startFrame ?? 0) + args.levels : undefined)
response.body = {
totalFrames,
stackFrames: stack.map((stackFrame): VSCodeDebugProtocol.StackFrame => {
let source: VSCodeDebugProtocol.Source
let line = stackFrame.line
const urlObject = url.parse(stackFrame.fileUri)
if (urlObject.protocol === 'dbgp:') {
let sourceReference
const src = Array.from(this._sources).find(
([, v]) => v.url === stackFrame.fileUri && v.connection === connection
)
if (src) {
sourceReference = src[0]
} else {
sourceReference = this._sourceIdCounter++
this._sources.set(sourceReference, { connection, url: stackFrame.fileUri })
}
// for eval code, we need to include .php extension to get syntax highlighting
source = {
name:
stackFrame.type === 'eval'
? `eval ${stackFrame.fileUri.substr(7)}.php`
: stackFrame.name,
sourceReference,
origin: stackFrame.type,
}
// for eval code, we add a "<?php" line at the beginning to get syntax highlighting (see sourceRequest)
line++
} else {
// Xdebug paths are URIs, VS Code file paths
const filePath = convertDebuggerPathToClient(urlObject, this._args.pathMappings)
// "Name" of the source and the actual file path
source = { name: path.basename(filePath), path: filePath }
}
// a new, unique ID for scopeRequests
const stackFrameId = this._stackFrameIdCounter++
// save the connection this stackframe belongs to and the level of the stackframe under the stacktrace id
this._stackFrames.set(stackFrameId, stackFrame)
// prepare response for VS Code (column is always 1 since Xdebug doesn't tell us the column)
return { id: stackFrameId, name: stackFrame.name, source, line, column: 1 }
}),
}
}
} catch (error) {
this.sendErrorResponse(response, error)
return
}
this.sendResponse(response)
}
protected async sourceRequest(
response: VSCodeDebugProtocol.SourceResponse,
args: VSCodeDebugProtocol.SourceArguments
) {
try {
if (!this._sources.has(args.sourceReference)) {
throw new Error(`Unknown sourceReference ${args.sourceReference}`)
}
const { connection, url } = this._sources.get(args.sourceReference)!
let { source } = await connection.sendSourceCommand(url)
if (!/^\s*<\?(php|=)/.test(source)) {
// we do this because otherwise VS Code would not show syntax highlighting for eval() code
source = '<?php\n' + source
}
response.body = { content: source, mimeType: 'application/x-php' }
} catch (error) {
this.sendErrorResponse(response, error)
return
}
this.sendResponse(response)
}
protected async scopesRequest(
response: VSCodeDebugProtocol.ScopesResponse,
args: VSCodeDebugProtocol.ScopesArguments
) {
try {
let scopes: vscode.Scope[] = []
if (this._errorStackFrames.has(args.frameId)) {
// VS Code is requesting the scopes for a virtual error stack frame
const status = this._errorStackFrames.get(args.frameId)!
if (status.exception) {
const variableId = this._variableIdCounter++
this._errorScopes.set(variableId, status)
scopes = [new vscode.Scope(status.exception.name.replace(/^(.*\\)+/g, ''), variableId)]
}
} else {
const stackFrame = this._stackFrames.get(args.frameId)
if (!stackFrame) {
throw new Error(`Unknown frameId ${args.frameId}`)
}
const contexts = await stackFrame.getContexts()
scopes = contexts.map(context => {
const variableId = this._variableIdCounter++
// remember that this new variable ID is assigned to a SCOPE (in Xdebug "context"), not a variable (in Xdebug "property"),
// so when VS Code does a variablesRequest with that ID we do a context_get and not a property_get
this._contexts.set(variableId, context)
// send VS Code the variable ID as identifier
return new vscode.Scope(context.name, variableId)
})
const status = this._statuses.get(stackFrame.connection)
if (status && status.exception) {
const variableId = this._variableIdCounter++
this._errorScopes.set(variableId, status)
scopes.unshift(new vscode.Scope(status.exception.name.replace(/^(.*\\)+/g, ''), variableId))
}
}
response.body = { scopes }
} catch (error) {
this.sendErrorResponse(response, error)
return
}
this.sendResponse(response)
}
protected async setVariableRequest(
response: VSCodeDebugProtocol.SetVariableResponse,
args: VSCodeDebugProtocol.SetVariableArguments
) {
try {
let properties: xdebug.Property[]
if (this._properties.has(args.variablesReference)) {
// variablesReference is a property
const container = this._properties.get(args.variablesReference)!
if (!container.hasChildren) {
throw new Error('Cannot edit property without children')
}
if (container.children.length === container.numberOfChildren) {
properties = container.children
} else {
properties = await container.getChildren()
}
} else if (this._contexts.has(args.variablesReference)) {
const context = this._contexts.get(args.variablesReference)!
properties = await context.getProperties()
} else {
throw new Error('Unknown variable reference')
}
const property = properties.find(child => child.name === args.name)
if (!property) {
throw new Error('Property not found')
}
await property.set(args.value)
response.body = { value: args.value }
} catch (error) {
this.sendErrorResponse(response, error)
return
}
this.sendResponse(response)
}
protected async variablesRequest(
response: VSCodeDebugProtocol.VariablesResponse,
args: VSCodeDebugProtocol.VariablesArguments
) {
try {
const variablesReference = args.variablesReference
let variables: VSCodeDebugProtocol.Variable[]
if (this._errorScopes.has(variablesReference)) {
// this is a virtual error scope
const status = this._errorScopes.get(variablesReference)!
variables = [
new vscode.Variable('type', status.exception.name),
new vscode.Variable('message', '"' + status.exception.message + '"'),
]
if (status.exception.code !== undefined) {
variables.push(new vscode.Variable('code', status.exception.code + ''))
}
} else {
// it is a real scope
let properties: xdebug.BaseProperty[]
if (this._contexts.has(variablesReference)) {
// VS Code is requesting the variables for a SCOPE, so we have to do a context_get
const context = this._contexts.get(variablesReference)!
properties = await context.getProperties()
} else if (this._properties.has(variablesReference)) {
// VS Code is requesting the subelements for a variable, so we have to do a property_get
const property = this._properties.get(variablesReference)!
if (property.hasChildren) {
if (property.children.length === property.numberOfChildren) {
properties = property.children
} else {
properties = await property.getChildren((args.start ?? 0) / 100)
}
} else {
properties = []
}
// SHOULD WE CACHE?
property.children = <xdebug.Property[]>properties
} else if (this._evalResultProperties.has(variablesReference)) {
// the children of properties returned from an eval command are always inlined, so we simply resolve them
const property = this._evalResultProperties.get(variablesReference)!
properties = property.hasChildren ? property.children : []
} else {
throw new Error('Unknown variable reference')
}
variables = properties.map(property => {
const displayValue = formatPropertyValue(property)
let variablesReference: number
let evaluateName: string
if (property.hasChildren || property.type === 'array' || property.type === 'object') {
// if the property has children, we have to send a variableReference back to VS Code
// so it can receive the child elements in another request.
// for arrays and objects we do it even when it does not have children so the user can still expand/collapse the entry
variablesReference = this._variableIdCounter++
if (property instanceof xdebug.Property) {
this._properties.set(variablesReference, property)
} else if (property instanceof xdebug.EvalResultProperty) {
this._evalResultProperties.set(variablesReference, property)
}
} else {
variablesReference = 0
}
if (property instanceof xdebug.Property) {
evaluateName = property.fullName
} else {
evaluateName = property.name
}
let presentationHint: VSCodeDebugProtocol.VariablePresentationHint = {}
if (property.facets?.length) {
if (property.facets.includes('public')) {
presentationHint.visibility = 'public'
} else if (property.facets.includes('private')) {
presentationHint.visibility = 'private'
} else if (property.facets.includes('protected')) {
presentationHint.visibility = 'protected'
}
if (property.facets.includes('readonly')) {
presentationHint.attributes = presentationHint.attributes || []
presentationHint.attributes.push('readOnly')
}
if (property.facets.includes('static')) {
presentationHint.attributes = presentationHint.attributes || []
presentationHint.attributes.push('static')
}
if (property.facets.includes('virtual')) {
presentationHint.kind = 'virtual'
}
}
const variable: VSCodeDebugProtocol.Variable = {
name: property.name,
value: displayValue,
type: property.type,
variablesReference,
presentationHint,
evaluateName,
}
if (this._args.xdebugSettings?.max_children === 100) {
variable.indexedVariables = property.numberOfChildren
}
return variable
})
}
response.body = { variables }
} catch (error) {
this.sendErrorResponse(response, error)
return
}
this.sendResponse(response)
}
protected async continueRequest(
response: VSCodeDebugProtocol.ContinueResponse,
args: VSCodeDebugProtocol.ContinueArguments
) {
let connection: xdebug.Connection | undefined
try {
connection = this._connections.get(args.threadId)
if (!connection) {
return this.sendErrorResponse(response, new Error('Unknown thread ID ' + args.threadId))
}
response.body = {
allThreadsContinued: false,
}
this.sendResponse(response)
} catch (error) {
this.sendErrorResponse(response, error)
return
}
try {
const xdebugResponse = await connection.sendRunCommand()
this._checkStatus(xdebugResponse)
} catch (error) {
this.sendEvent(
new vscode.OutputEvent(
'continueRequest thread ID ' + args.threadId + ' error: ' + error.message + '\n'
),
true
)
}
}
protected async nextRequest(response: VSCodeDebugProtocol.NextResponse, args: VSCodeDebugProtocol.NextArguments) {
let connection: xdebug.Connection | undefined
try {
connection = this._connections.get(args.threadId)
if (!connection) {
return this.sendErrorResponse(response, new Error('Unknown thread ID ' + args.threadId))
}
this.sendResponse(response)
} catch (error) {
this.sendErrorResponse(response, error)
return
}
try {
const xdebugResponse = await connection.sendStepOverCommand()
this._checkStatus(xdebugResponse)
} catch (error) {
this.sendEvent(
new vscode.OutputEvent('nextRequest thread ID ' + args.threadId + ' error: ' + error.message + '\n'),
true
)
}
}
protected async stepInRequest(
response: VSCodeDebugProtocol.StepInResponse,
args: VSCodeDebugProtocol.StepInArguments
) {
let connection: xdebug.Connection | undefined
try {
connection = this._connections.get(args.threadId)
if (!connection) {
return this.sendErrorResponse(response, new Error('Unknown thread ID ' + args.threadId))
}
this.sendResponse(response)
} catch (error) {
this.sendErrorResponse(response, error)
return
}
try {
const xdebugResponse = await connection.sendStepIntoCommand()
this._checkStatus(xdebugResponse)
} catch (error) {
this.sendEvent(
new vscode.OutputEvent('stepInRequest thread ID ' + args.threadId + ' error: ' + error.message + '\n'),
true
)
}
}
protected async stepOutRequest(
response: VSCodeDebugProtocol.StepOutResponse,
args: VSCodeDebugProtocol.StepOutArguments
) {
let connection: xdebug.Connection | undefined
try {
connection = this._connections.get(args.threadId)
if (!connection) {
return this.sendErrorResponse(response, new Error('Unknown thread ID ' + args.threadId))
}
this.sendResponse(response)
} catch (error) {
this.sendErrorResponse(response, error)
return
}
try {
const xdebugResponse = await connection.sendStepOutCommand()
this._checkStatus(xdebugResponse)
} catch (error) {
this.sendEvent(
new vscode.OutputEvent('stepOutRequest thread ID ' + args.threadId + ' error: ' + error.message + '\n'),
true
)
}
}
protected pauseRequest(response: VSCodeDebugProtocol.PauseResponse, args: VSCodeDebugProtocol.PauseArguments) {
this.sendErrorResponse(response, new Error('Pausing the execution is not supported by Xdebug'))
}
protected async disconnectRequest(
response: VSCodeDebugProtocol.DisconnectResponse,
args: VSCodeDebugProtocol.DisconnectArguments
) {
try {
await Promise.all(
Array.from(this._connections).map(async ([id, connection]) => {
if (args?.terminateDebuggee !== false) {
// Try to send stop command for 500ms
// If the script is running, just close the connection
await Promise.race([
connection.sendStopCommand(),
new Promise(resolve => setTimeout(resolve, 500)),
])
}
await connection.close()
this._connections.delete(id)
this._statuses.delete(connection)
this._breakpointAdapters.delete(connection)
})
)
// If listening for connections, close server
if (this._server) {
await new Promise(resolve => this._server.close(resolve))
}
// If launched as CLI, kill process
if (this._phpProcess) {
this._phpProcess.kill()
}
// Unregister proxy
if (this._proxyConnect) {
await this._proxyConnect.sendProxyStopCommand()
}
} catch (error) {
this.sendErrorResponse(response, error)
return
}
this.sendResponse(response)
this.shutdown()
}
protected async evaluateRequest(
response: VSCodeDebugProtocol.EvaluateResponse,
args: VSCodeDebugProtocol.EvaluateArguments
) {
try {
if (!args.frameId) {
throw new Error('Cannot evaluate code without a connection')
}
if (!this._stackFrames.has(args.frameId)) {
throw new Error(`Unknown frameId ${args.frameId}`)
}
const stackFrame = this._stackFrames.get(args.frameId)!
const connection = stackFrame.connection
let result: xdebug.BaseProperty | null = null
if (args.context === 'hover') {
// try to get variable from property_get
const ctx = await stackFrame.getContexts() // TODO CACHE THIS
const response = await connection.sendPropertyGetNameCommand(args.expression, ctx[0])
if (response.property) {
result = response.property
}
} else if (args.context === 'repl') {
const uuid = randomUUID()
await connection.sendEvalCommand(`$GLOBALS['eval_cache']['${uuid}']=${args.expression}`)
const ctx = await stackFrame.getContexts() // TODO CACHE THIS
const response = await connection.sendPropertyGetNameCommand(`$eval_cache['${uuid}']`, ctx[1])
if (response.property) {
result = response.property
}
} else {
const response = await connection.sendEvalCommand(args.expression)
if (response.result) {
result = response.result
}
}
if (result) {
const displayValue = formatPropertyValue(result)
let variablesReference: number
// if the property has children, generate a variable ID and save the property (including children) so VS Code can request them
if (result.hasChildren || result.type === 'array' || result.type === 'object') {
variablesReference = this._variableIdCounter++
if (result instanceof xdebug.Property) {
this._properties.set(variablesReference, result)
} else {
this._evalResultProperties.set(variablesReference, result)
}
} else {
variablesReference = 0
}
response.body = { result: displayValue, variablesReference }
} else {
response.body = { result: 'no result', variablesReference: 0 }
}
this.sendResponse(response)
} catch (error) {
response.message = error.message
response.success = false
this.sendResponse(response)
}
}
}
vscode.DebugSession.run(PhpDebugSession) | the_stack |
import { testTokenization } from '../test/testRunner';
testTokenization('postiats', [
// Keywords
[
{
line: 'implement main(argc, argv) =',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'identifier.pats' },
{ startIndex: 14, type: 'delimiter.parenthesis.pats' },
{ startIndex: 15, type: 'identifier.pats' },
{ startIndex: 19, type: 'delimiter.comma.pats' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'identifier.pats' },
{ startIndex: 25, type: 'delimiter.parenthesis.pats' },
{ startIndex: 26, type: '' },
{ startIndex: 27, type: 'keyword.pats' }
]
}
],
// Comments - single line
[
{
line: '//',
tokens: [{ startIndex: 0, type: 'comment.pats' }]
}
],
[
{
line: ' // a comment',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 4, type: 'comment.pats' }
]
}
],
[
{
line: '// a comment',
tokens: [{ startIndex: 0, type: 'comment.pats' }]
}
],
[
{
line: '//sticky comment',
tokens: [{ startIndex: 0, type: 'comment.pats' }]
}
],
[
{
line: '/almost a comment',
tokens: [
{ startIndex: 0, type: 'operator.pats' },
{ startIndex: 1, type: 'identifier.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'identifier.pats' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'identifier.pats' }
]
}
],
[
{
line: '/* //*/ a',
tokens: [
{ startIndex: 0, type: 'comment.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'identifier.pats' }
]
}
],
[
{
line: '1 / 2; /* comment',
tokens: [
{ startIndex: 0, type: 'number.decimal.pats' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'operator.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'number.decimal.pats' },
{ startIndex: 5, type: 'delimiter.semicolon.pats' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'comment.pats' }
]
}
],
[
{
line: 'val x:int = 1; // my comment // is a nice one',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 5, type: 'keyword.pats' },
{ startIndex: 6, type: 'type.pats' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'keyword.pats' },
{ startIndex: 11, type: '' },
{ startIndex: 12, type: 'number.decimal.pats' },
{ startIndex: 13, type: 'delimiter.semicolon.pats' },
{ startIndex: 14, type: '' },
{ startIndex: 15, type: 'comment.pats' }
]
}
],
// Comments - range comment, single line
[
{
line: '/* a simple comment */',
tokens: [{ startIndex: 0, type: 'comment.pats' }]
}
],
[
{
line: 'var x : int = /* a simple comment */ 1;',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'keyword.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'type.pats' },
{ startIndex: 11, type: '' },
{ startIndex: 12, type: 'keyword.pats' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'comment.pats' },
{ startIndex: 36, type: '' },
{ startIndex: 37, type: 'number.decimal.pats' },
{ startIndex: 38, type: 'delimiter.semicolon.pats' }
]
}
],
[
{
line: 'val x = /* comment */ 1; */',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'keyword.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'comment.pats' },
{ startIndex: 21, type: '' },
{ startIndex: 22, type: 'number.decimal.pats' },
{ startIndex: 23, type: 'delimiter.semicolon.pats' },
{ startIndex: 24, type: '' },
{ startIndex: 25, type: 'operator.pats' }
]
}
],
[
{
line: 'x = /**/;',
tokens: [
{ startIndex: 0, type: 'identifier.pats' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'comment.pats' },
{ startIndex: 8, type: 'delimiter.semicolon.pats' }
]
}
],
[
{
line: 'x = /*/;',
tokens: [
{ startIndex: 0, type: 'identifier.pats' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'comment.pats' }
]
}
],
// block comments, single line
[
{
line: '(* a simple comment *)',
tokens: [{ startIndex: 0, type: 'comment.pats' }]
}
],
[
{
line: '(* a simple (* nested *) comment *)',
tokens: [{ startIndex: 0, type: 'comment.pats' }]
}
],
[
{
line: '(* ****** ****** *)',
tokens: [{ startIndex: 0, type: 'comment.pats' }]
}
],
[
{
line: 'var x : int = (* a simple comment *) 1;',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'keyword.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'type.pats' },
{ startIndex: 11, type: '' },
{ startIndex: 12, type: 'keyword.pats' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'comment.pats' },
{ startIndex: 36, type: '' },
{ startIndex: 37, type: 'number.decimal.pats' },
{ startIndex: 38, type: 'delimiter.semicolon.pats' }
]
}
],
[
{
line: 'val x = (* comment *) 1; *)',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'keyword.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'comment.pats' },
{ startIndex: 21, type: '' },
{ startIndex: 22, type: 'number.decimal.pats' },
{ startIndex: 23, type: 'delimiter.semicolon.pats' },
{ startIndex: 24, type: '' },
{ startIndex: 25, type: 'operator.pats' },
{ startIndex: 26, type: 'delimiter.parenthesis.pats' }
]
}
],
[
{
line: 'x = (**);',
tokens: [
{ startIndex: 0, type: 'identifier.pats' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'comment.pats' },
{ startIndex: 8, type: 'delimiter.semicolon.pats' }
]
}
],
[
{
line: '(*)',
tokens: [
{ startIndex: 0, type: 'invalid.pats' } // not a comment!
]
}
],
// Numbers
[
{
line: '0',
tokens: [{ startIndex: 0, type: 'number.decimal.pats' }]
}
],
[
{
line: '12l',
tokens: [{ startIndex: 0, type: 'number.decimal.pats' }]
}
],
[
{
line: '34U',
tokens: [{ startIndex: 0, type: 'number.decimal.pats' }]
}
],
[
{
line: '55LL',
tokens: [{ startIndex: 0, type: 'number.decimal.pats' }]
}
],
[
{
line: '34ul',
tokens: [{ startIndex: 0, type: 'number.decimal.pats' }]
}
],
[
{
line: '55llU',
tokens: [{ startIndex: 0, type: 'number.decimal.pats' }]
}
],
/*
[{
line: '5\'5llU',
tokens: [
{ startIndex: 0, type: 'number.pats' }
]}],
[{
line: '100\'000\'000',
tokens: [
{ startIndex: 0, type: 'number.pats' }
]}],
*/
[
{
line: '0x100aafllU',
tokens: [{ startIndex: 0, type: 'number.hex.pats' }]
}
],
[
{
line: '0342325',
tokens: [{ startIndex: 0, type: 'number.octal.pats' }]
}
],
[
{
line: '0x123',
tokens: [{ startIndex: 0, type: 'number.hex.pats' }]
}
],
[
{
line: '23.5',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '23.5e3',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '23.5E3',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '23.5F',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '23.5f',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '1.72E3F',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '1.72E3f',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '1.72e3F',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '1.72e3f',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '23.5L',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '23.5l',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '1.72E3L',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '1.72E3l',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '1.72e3L',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '1.72e3l',
tokens: [{ startIndex: 0, type: 'number.float.pats' }]
}
],
[
{
line: '0+0',
tokens: [
{ startIndex: 0, type: 'number.decimal.pats' },
{ startIndex: 1, type: 'operator.pats' },
{ startIndex: 2, type: 'number.decimal.pats' }
]
}
],
[
{
line: '100+10',
tokens: [
{ startIndex: 0, type: 'number.decimal.pats' },
{ startIndex: 3, type: 'operator.pats' },
{ startIndex: 4, type: 'number.decimal.pats' }
]
}
],
[
{
line: '0 + 0',
tokens: [
{ startIndex: 0, type: 'number.decimal.pats' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'operator.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'number.decimal.pats' }
]
}
],
// hi-lighting of variables in staload/dynload
[
{
line: '"{$LIBATSCC2JS}/staloadall.hats"',
tokens: [
{ startIndex: 0, type: 'string.quote.pats' },
{ startIndex: 1, type: 'string.escape.pats' },
{ startIndex: 3, type: 'identifier.pats' },
{ startIndex: 14, type: 'string.escape.pats' },
{ startIndex: 15, type: 'string.pats' },
{ startIndex: 31, type: 'string.quote.pats' }
]
}
],
// Monarch Generated
[
{
line: '#include "/path/to/my/file.h"',
tokens: [
{ startIndex: 0, type: 'keyword.srp.pats' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'string.quote.pats' },
{ startIndex: 10, type: 'string.pats' },
{ startIndex: 28, type: 'string.quote.pats' }
]
},
{
line: '',
tokens: []
},
{
line: '#ifdef VAR #then',
tokens: [
{ startIndex: 0, type: 'keyword.srp.pats' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'identifier.pats' },
{ startIndex: 10, type: '' },
{ startIndex: 11, type: 'keyword.srp.pats' }
]
},
{
line: '#define SUM(A,B) (A) + (B)',
tokens: [
{ startIndex: 0, type: 'keyword.srp.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'identifier.pats' },
{ startIndex: 11, type: 'delimiter.parenthesis.pats' },
{ startIndex: 12, type: 'identifier.pats' },
{ startIndex: 13, type: 'delimiter.comma.pats' },
{ startIndex: 14, type: 'identifier.pats' },
{ startIndex: 15, type: 'delimiter.parenthesis.pats' },
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'delimiter.parenthesis.pats' },
{ startIndex: 18, type: 'identifier.pats' },
{ startIndex: 19, type: 'delimiter.parenthesis.pats' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'operator.pats' },
{ startIndex: 22, type: '' },
{ startIndex: 23, type: 'delimiter.parenthesis.pats' },
{ startIndex: 24, type: 'identifier.pats' },
{ startIndex: 25, type: 'delimiter.parenthesis.pats' }
]
},
{
line: 'staload Asdf_CDE = "./myfile.sats"',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'identifier.pats' },
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'keyword.pats' },
{ startIndex: 18, type: '' },
{ startIndex: 19, type: 'string.quote.pats' },
{ startIndex: 20, type: 'string.pats' },
{ startIndex: 33, type: 'string.quote.pats' }
]
},
{
line: '',
tokens: []
},
{
line: 'implement main(argc, argv)',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'identifier.pats' },
{ startIndex: 14, type: 'delimiter.parenthesis.pats' },
{ startIndex: 15, type: 'identifier.pats' },
{ startIndex: 19, type: 'delimiter.comma.pats' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'identifier.pats' },
{ startIndex: 25, type: 'delimiter.parenthesis.pats' }
]
},
{
line: ' = begin',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 1, type: 'keyword.pats' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'keyword.pats' }
]
},
{
line: '0',
tokens: [{ startIndex: 0, type: 'number.decimal.pats' }]
},
{
line: 'end',
tokens: [{ startIndex: 0, type: 'keyword.pats' }]
},
{
line: '',
tokens: []
},
{
line: '',
tokens: []
},
{
line: 'dataprop FACT (int, int) =',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'identifier.pats' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'delimiter.parenthesis.pats' },
{ startIndex: 15, type: 'type.pats' },
{ startIndex: 18, type: 'delimiter.comma.pats' },
{ startIndex: 19, type: '' },
{ startIndex: 20, type: 'type.pats' },
{ startIndex: 23, type: 'delimiter.parenthesis.pats' },
{ startIndex: 24, type: '' },
{ startIndex: 25, type: 'keyword.pats' }
]
},
{
line: ' | FACTbas (0, 1) of ()',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 1, type: 'keyword.pats' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'identifier.pats' },
{ startIndex: 10, type: '' },
{ startIndex: 11, type: 'delimiter.parenthesis.pats' },
{ startIndex: 12, type: 'number.decimal.pats' },
{ startIndex: 13, type: 'delimiter.comma.pats' },
{ startIndex: 14, type: '' },
{ startIndex: 15, type: 'number.decimal.pats' },
{ startIndex: 16, type: 'delimiter.parenthesis.pats' },
{ startIndex: 17, type: '' },
{ startIndex: 18, type: 'keyword.pats' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'delimiter.parenthesis.pats' }
]
},
{
line: ' | {n:pos}{r:int} FACTind (n, n*r) of FACT (n-1, r)',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 1, type: 'keyword.pats' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'delimiter.curly.pats' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 5, type: 'keyword.pats' },
{ startIndex: 6, type: 'identifier.pats' },
{ startIndex: 9, type: 'delimiter.parenthesis.pats' },
{ startIndex: 10, type: 'delimiter.curly.pats' },
{ startIndex: 11, type: 'identifier.pats' },
{ startIndex: 12, type: 'keyword.pats' },
{ startIndex: 13, type: 'type.pats' },
{ startIndex: 16, type: 'delimiter.parenthesis.pats' },
{ startIndex: 17, type: '' },
{ startIndex: 18, type: 'identifier.pats' },
{ startIndex: 25, type: '' },
{ startIndex: 26, type: 'delimiter.parenthesis.pats' },
{ startIndex: 27, type: 'identifier.pats' },
{ startIndex: 28, type: 'delimiter.comma.pats' },
{ startIndex: 29, type: '' },
{ startIndex: 30, type: 'identifier.pats' },
{ startIndex: 31, type: 'operator.pats' },
{ startIndex: 32, type: 'identifier.pats' },
{ startIndex: 33, type: 'delimiter.parenthesis.pats' },
{ startIndex: 34, type: '' },
{ startIndex: 35, type: 'keyword.pats' },
{ startIndex: 37, type: '' },
{ startIndex: 38, type: 'identifier.pats' },
{ startIndex: 42, type: '' },
{ startIndex: 43, type: 'delimiter.parenthesis.pats' },
{ startIndex: 44, type: 'identifier.pats' },
{ startIndex: 45, type: 'operator.pats' },
{ startIndex: 46, type: 'number.decimal.pats' },
{ startIndex: 47, type: 'delimiter.comma.pats' },
{ startIndex: 48, type: '' },
{ startIndex: 49, type: 'identifier.pats' },
{ startIndex: 50, type: 'delimiter.parenthesis.pats' }
]
},
{
line: '',
tokens: []
},
{
line: 'fun fact {n:nat} .<n>. (x: int n) : [r:int] (FACT(n, r) | int(r)) = (',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'delimiter.curly.pats' },
{ startIndex: 10, type: 'identifier.pats' },
{ startIndex: 11, type: 'keyword.pats' },
{ startIndex: 12, type: 'identifier.pats' },
{ startIndex: 15, type: 'delimiter.parenthesis.pats' },
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'identifier.sym.pats' },
{ startIndex: 19, type: 'identifier.pats' },
{ startIndex: 20, type: 'keyword.pats' },
{ startIndex: 22, type: '' },
{ startIndex: 23, type: 'delimiter.parenthesis.pats' },
{ startIndex: 24, type: 'identifier.pats' },
{ startIndex: 25, type: 'keyword.pats' },
{ startIndex: 26, type: '' },
{ startIndex: 27, type: 'type.pats' },
{ startIndex: 30, type: '' },
{ startIndex: 31, type: 'identifier.pats' },
{ startIndex: 32, type: 'delimiter.parenthesis.pats' },
{ startIndex: 33, type: '' },
{ startIndex: 34, type: 'keyword.pats' },
{ startIndex: 35, type: '' },
{ startIndex: 36, type: 'delimiter.square.pats' },
{ startIndex: 37, type: 'identifier.pats' },
{ startIndex: 38, type: 'keyword.pats' },
{ startIndex: 39, type: 'type.pats' },
{ startIndex: 42, type: 'delimiter.square.pats' },
{ startIndex: 43, type: '' },
{ startIndex: 44, type: 'delimiter.parenthesis.pats' },
{ startIndex: 45, type: 'identifier.pats' },
{ startIndex: 49, type: 'delimiter.parenthesis.pats' },
{ startIndex: 50, type: 'identifier.pats' },
{ startIndex: 51, type: 'delimiter.comma.pats' },
{ startIndex: 52, type: '' },
{ startIndex: 53, type: 'identifier.pats' },
{ startIndex: 54, type: 'delimiter.parenthesis.pats' },
{ startIndex: 55, type: '' },
{ startIndex: 56, type: 'keyword.pats' },
{ startIndex: 57, type: '' },
{ startIndex: 58, type: 'type.pats' },
{ startIndex: 61, type: 'delimiter.parenthesis.pats' },
{ startIndex: 62, type: 'identifier.pats' },
{ startIndex: 63, type: 'delimiter.parenthesis.pats' },
{ startIndex: 65, type: '' },
{ startIndex: 66, type: 'keyword.pats' },
{ startIndex: 67, type: '' },
{ startIndex: 68, type: 'delimiter.parenthesis.pats' }
]
},
{
line: 'if x > 0 then let',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'identifier.pats' },
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'keyword.pats' },
{ startIndex: 6, type: '' },
{ startIndex: 7, type: 'number.decimal.pats' },
{ startIndex: 8, type: '' },
{ startIndex: 9, type: 'keyword.pats' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'keyword.pats' }
]
},
{
line: ' val [r1:int] (pf1 | r1) = fact (x-1)',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 2, type: 'keyword.pats' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'delimiter.square.pats' },
{ startIndex: 7, type: 'identifier.pats' },
{ startIndex: 9, type: 'keyword.pats' },
{ startIndex: 10, type: 'type.pats' },
{ startIndex: 13, type: 'delimiter.square.pats' },
{ startIndex: 14, type: '' },
{ startIndex: 15, type: 'delimiter.parenthesis.pats' },
{ startIndex: 16, type: 'identifier.pats' },
{ startIndex: 19, type: '' },
{ startIndex: 20, type: 'keyword.pats' },
{ startIndex: 21, type: '' },
{ startIndex: 22, type: 'identifier.pats' },
{ startIndex: 24, type: 'delimiter.parenthesis.pats' },
{ startIndex: 25, type: '' },
{ startIndex: 26, type: 'keyword.pats' },
{ startIndex: 27, type: '' },
{ startIndex: 28, type: 'identifier.pats' },
{ startIndex: 32, type: '' },
{ startIndex: 33, type: 'delimiter.parenthesis.pats' },
{ startIndex: 34, type: 'identifier.pats' },
{ startIndex: 35, type: 'operator.pats' },
{ startIndex: 36, type: 'number.decimal.pats' },
{ startIndex: 37, type: 'delimiter.parenthesis.pats' }
]
},
{
line: ' prval pf = FACTind {n}{r1} (pf1)',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 2, type: 'keyword.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'identifier.pats' },
{ startIndex: 10, type: '' },
{ startIndex: 11, type: 'keyword.pats' },
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'identifier.pats' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'delimiter.curly.pats' },
{ startIndex: 22, type: 'identifier.pats' },
{ startIndex: 23, type: 'delimiter.parenthesis.pats' },
{ startIndex: 24, type: 'delimiter.curly.pats' },
{ startIndex: 25, type: 'identifier.pats' },
{ startIndex: 27, type: 'delimiter.parenthesis.pats' },
{ startIndex: 28, type: '' },
{ startIndex: 29, type: 'delimiter.parenthesis.pats' },
{ startIndex: 30, type: 'identifier.pats' },
{ startIndex: 33, type: 'delimiter.parenthesis.pats' }
]
},
{
line: ' val r = x * r1',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 2, type: 'keyword.pats' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'identifier.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'keyword.pats' },
{ startIndex: 9, type: '' },
{ startIndex: 10, type: 'identifier.pats' },
{ startIndex: 11, type: '' },
{ startIndex: 12, type: 'operator.pats' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'identifier.pats' }
]
},
{
line: 'in',
tokens: [{ startIndex: 0, type: 'keyword.pats' }]
},
{
line: ' (pf | r)',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 2, type: 'delimiter.parenthesis.pats' },
{ startIndex: 3, type: 'identifier.pats' },
{ startIndex: 5, type: '' },
{ startIndex: 6, type: 'keyword.pats' },
{ startIndex: 7, type: '' },
{ startIndex: 8, type: 'identifier.pats' },
{ startIndex: 9, type: 'delimiter.parenthesis.pats' }
]
},
{
line: 'end // end of [then]',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'comment.pats' }
]
},
{
line: 'else (FACTbas () | 1)',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 4, type: '' },
{ startIndex: 5, type: 'delimiter.parenthesis.pats' },
{ startIndex: 6, type: 'identifier.pats' },
{ startIndex: 13, type: '' },
{ startIndex: 14, type: 'delimiter.parenthesis.pats' },
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'keyword.pats' },
{ startIndex: 18, type: '' },
{ startIndex: 19, type: 'number.decimal.pats' },
{ startIndex: 20, type: 'delimiter.parenthesis.pats' }
]
},
{
line: ') (* end of [fact] *)',
tokens: [
{ startIndex: 0, type: 'delimiter.parenthesis.pats' },
{ startIndex: 1, type: '' },
{ startIndex: 2, type: 'comment.pats' }
]
},
{
line: '',
tokens: []
},
{
line: 'local',
tokens: [{ startIndex: 0, type: 'keyword.pats' }]
},
{
line: 'var __count: int = 0 // it is statically allocated',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 11, type: 'keyword.pats' },
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'type.pats' },
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'keyword.pats' },
{ startIndex: 18, type: '' },
{ startIndex: 19, type: 'number.decimal.pats' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'comment.pats' }
]
},
{
line: '',
tokens: []
},
{
line: 'val theCount =',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 12, type: '' },
{ startIndex: 13, type: 'keyword.pats' }
]
},
{
line: ' ref_make_viewptr{int}(view@(__count) | addr@(__count))',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 2, type: 'identifier.pats' },
{ startIndex: 18, type: 'delimiter.curly.pats' },
{ startIndex: 19, type: 'type.pats' },
{ startIndex: 22, type: 'delimiter.parenthesis.pats' },
{ startIndex: 24, type: 'keyword.pats' },
{ startIndex: 29, type: 'delimiter.parenthesis.pats' },
{ startIndex: 30, type: 'identifier.pats' },
{ startIndex: 37, type: 'delimiter.parenthesis.pats' },
{ startIndex: 38, type: '' },
{ startIndex: 39, type: 'keyword.pats' },
{ startIndex: 40, type: '' },
{ startIndex: 41, type: 'keyword.pats' },
{ startIndex: 46, type: 'delimiter.parenthesis.pats' },
{ startIndex: 47, type: 'identifier.pats' },
{ startIndex: 54, type: 'delimiter.parenthesis.pats' }
]
},
{
line: '// end of [val]',
tokens: [{ startIndex: 0, type: 'comment.pats' }]
},
{
line: '',
tokens: []
},
{
line: 'in (* in of [local] *)',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 2, type: '' },
{ startIndex: 3, type: 'comment.pats' }
]
},
{
line: '',
tokens: []
},
{
line: 'fun theCount_get (): int = !theCount',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'delimiter.parenthesis.pats' },
{ startIndex: 19, type: 'keyword.pats' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'type.pats' },
{ startIndex: 24, type: '' },
{ startIndex: 25, type: 'keyword.pats' },
{ startIndex: 26, type: '' },
{ startIndex: 27, type: 'keyword.pats' },
{ startIndex: 28, type: 'identifier.pats' }
]
},
{
line: '',
tokens: []
},
{
line: 'fun theCount_inc (): void = !theCount := !theCount + 1',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'identifier.pats' },
{ startIndex: 16, type: '' },
{ startIndex: 17, type: 'delimiter.parenthesis.pats' },
{ startIndex: 19, type: 'keyword.pats' },
{ startIndex: 20, type: '' },
{ startIndex: 21, type: 'type.pats' },
{ startIndex: 25, type: '' },
{ startIndex: 26, type: 'keyword.pats' },
{ startIndex: 27, type: '' },
{ startIndex: 28, type: 'keyword.pats' },
{ startIndex: 29, type: 'identifier.pats' },
{ startIndex: 37, type: '' },
{ startIndex: 38, type: 'operator.pats' },
{ startIndex: 40, type: '' },
{ startIndex: 41, type: 'keyword.pats' },
{ startIndex: 42, type: 'identifier.pats' },
{ startIndex: 50, type: '' },
{ startIndex: 51, type: 'operator.pats' },
{ startIndex: 52, type: '' },
{ startIndex: 53, type: 'number.decimal.pats' }
]
},
{
line: '',
tokens: []
},
{
line: 'end // end of [local]',
tokens: [
{ startIndex: 0, type: 'keyword.pats' },
{ startIndex: 3, type: '' },
{ startIndex: 4, type: 'comment.pats' }
]
},
{
line: '',
tokens: []
},
{
line: '#endif',
tokens: [{ startIndex: 0, type: 'keyword.srp.pats' }]
}
]
]); | the_stack |
import { useReducer, useState } from "react";
import type { Dispatch } from "react";
import type { NewLeagueTeam } from "./types";
import type { Conf, Div, View } from "../../../common/types";
import classNames from "classnames";
import { arrayMoveImmutable } from "array-move";
import orderBy from "lodash-es/orderBy";
import UpsertTeamModal from "./UpsertTeamModal";
import countBy from "lodash-es/countBy";
import { HelpPopover, StickyBottomButtons } from "../../components";
import { logEvent, toWorker } from "../../util";
import getUnusedAbbrevs from "../../../common/getUnusedAbbrevs";
import getTeamInfos from "../../../common/getTeamInfos";
import confirmDeleteWithChlidren from "./confirmDeleteWithChlidren";
import { Dropdown } from "react-bootstrap";
import { processingSpinner } from "../../components/ActionButton";
const makeTIDsSequential = <T extends { tid: number }>(teams: T[]): T[] => {
return teams.map((t, i) => ({
...t,
tid: i,
}));
};
type ConfsDivsTeams = {
confs: Conf[];
divs: Div[];
teams: NewLeagueTeam[];
};
type State = ConfsDivsTeams;
type Action =
| ({
type: "setState";
} & ConfsDivsTeams)
| {
type: "addConf";
}
| {
type: "addDiv";
cid: number;
}
| {
type: "addTeam";
t: NewLeagueTeam;
}
| {
type: "renameConf";
cid: number;
name: string;
}
| {
type: "renameDiv";
did: number;
name: string;
}
| {
type: "editTeam";
t: NewLeagueTeam;
}
| {
type: "moveConf";
cid: number;
direction: 1 | -1;
}
| {
type: "moveDiv";
did: number;
direction: 1 | -1;
}
| {
type: "deleteConf";
cid: number;
moveToCID?: number;
}
| {
type: "deleteDiv";
did: number;
moveToDID?: number;
}
| {
type: "deleteTeam";
tid: number;
};
const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "setState":
return {
...state,
confs: action.confs,
divs: action.divs,
teams: makeTIDsSequential(action.teams),
};
case "addConf": {
const maxCID =
state.confs.length > 0
? Math.max(...state.confs.map(conf => conf.cid))
: -1;
return {
...state,
confs: [
...state.confs,
{
cid: maxCID + 1,
name: "New Conference",
},
],
};
}
case "addDiv": {
const maxDID =
state.divs.length > 0
? Math.max(...state.divs.map(div => div.did))
: -1;
return {
...state,
divs: [
...state.divs,
{
did: maxDID + 1,
cid: action.cid,
name: "New Division",
},
],
};
}
case "addTeam": {
return {
...state,
teams: makeTIDsSequential([...state.teams, action.t]),
};
}
case "renameConf":
return {
...state,
confs: state.confs.map(conf => {
if (action.cid !== conf.cid) {
return conf;
}
return {
...conf,
name: action.name,
};
}),
};
case "renameDiv":
return {
...state,
divs: state.divs.map(div => {
if (action.did !== div.did) {
return div;
}
return {
...div,
name: action.name,
};
}),
};
case "editTeam": {
const newTeams = state.teams.map(t => {
if (t.tid !== action.t.tid) {
return t;
}
return action.t;
});
return {
...state,
teams: makeTIDsSequential(newTeams),
};
}
case "moveConf": {
const oldIndex = state.confs.findIndex(conf => conf.cid === action.cid);
const newIndex = oldIndex + action.direction;
if (newIndex < 0 || newIndex > state.confs.length - 1) {
return state;
}
const newConfs = arrayMoveImmutable(state.confs, oldIndex, newIndex);
return {
...state,
confs: newConfs,
};
}
case "moveDiv": {
// Make sure we're sorted by cid, to make moving between conferences easy
const newDivs = orderBy(state.divs, "cid", "asc");
const div = newDivs.find(div => div.did === action.did);
if (!div) {
return state;
}
// See if we're moving at the boundary of the conference, in which case we need to switch to a new conference
const divsLocal = newDivs.filter(div2 => div2.cid === div.cid);
const indexLocal = divsLocal.findIndex(div => div.did === action.did);
let newCID = -1;
if (
(indexLocal === 0 && action.direction === -1) ||
(indexLocal === divsLocal.length - 1 && action.direction === 1)
) {
const confIndex = state.confs.findIndex(conf => conf.cid === div.cid);
if (confIndex > 0 && action.direction === -1) {
newCID = state.confs[confIndex - 1].cid;
} else if (
confIndex < state.confs.length - 1 &&
action.direction === 1
) {
newCID = state.confs[confIndex + 1].cid;
}
}
if (newCID >= 0) {
return {
...state,
divs: newDivs.map(div => {
if (action.did !== div.did) {
return div;
}
return {
...div,
cid: newCID,
};
}),
};
}
// Normal move
const oldIndex = newDivs.findIndex(div => div.did === action.did);
const newIndex = oldIndex + action.direction;
if (newIndex < 0 || newIndex > newDivs.length - 1) {
return state;
}
const newDivs2 = arrayMoveImmutable(newDivs, oldIndex, newIndex);
return {
...state,
divs: newDivs2,
};
}
case "deleteConf": {
const { moveToCID } = action;
let newDivs;
let newTeams;
if (moveToCID === undefined) {
// Delete children
newDivs = state.divs.filter(div => div.cid !== action.cid);
newTeams = state.teams.filter(t => t.cid !== action.cid);
} else {
// Move children
newDivs = state.divs.map(div => {
if (div.cid !== action.cid) {
return div;
}
return {
...div,
cid: moveToCID,
};
});
newTeams = state.teams.map(t => {
if (t.cid !== action.cid) {
return t;
}
return {
...t,
cid: moveToCID,
};
});
}
return {
confs: state.confs.filter(conf => conf.cid !== action.cid),
divs: newDivs,
teams: makeTIDsSequential(newTeams),
};
}
case "deleteDiv": {
let newTeams;
if (action.moveToDID === undefined) {
// Delete children
newTeams = state.teams.filter(t => t.did !== action.did);
} else {
// Move children
const div = state.divs.find(div => div.did === action.moveToDID);
if (!div) {
throw new Error("div not found");
}
newTeams = state.teams.map(t => {
if (t.did !== action.did) {
return t;
}
return {
...t,
did: div.did,
cid: div.cid,
};
});
}
return {
...state,
divs: state.divs.filter(div => div.did !== action.did),
teams: makeTIDsSequential(newTeams),
};
}
case "deleteTeam":
return {
...state,
teams: makeTIDsSequential(
state.teams.filter(t => t.tid !== action.tid),
),
};
default:
throw new Error();
}
};
const EditButton = ({ onClick }: { onClick: () => void }) => {
return (
<button
className="ml-2 btn btn-link p-0 border-0 text-reset"
onClick={onClick}
title="Edit"
type="button"
>
<span className="glyphicon glyphicon-edit" />
</button>
);
};
const DeleteButton = ({ onClick }: { onClick: () => void }) => {
return (
<button
className="ml-2 btn btn-link text-danger p-0 border-0"
onClick={onClick}
title="Delete"
type="button"
>
<span className="glyphicon glyphicon-remove" />
</button>
);
};
const CardHeader = ({
alignButtonsRight,
name,
onDelete,
onMoveDown,
onMoveUp,
onRename,
disableMoveUp,
disableMoveDown,
}: {
alignButtonsRight?: boolean;
name: string;
onDelete: () => void;
onMoveDown: () => void;
onMoveUp: () => void;
onRename: (name: string) => void;
disableMoveUp: boolean;
disableMoveDown: boolean;
}) => {
const [renaming, setRenaming] = useState(false);
const [controlledName, setControlledName] = useState(name);
return (
<div
className={classNames("card-header", renaming ? "p-1" : undefined)}
style={{ height: 44 }}
>
{renaming ? (
<form
className="d-flex"
onSubmit={event => {
event.preventDefault();
onRename(controlledName);
setRenaming(false);
}}
style={{ maxWidth: 300 }}
>
<input
type="text"
className="form-control mr-2"
value={controlledName}
onChange={event => {
setControlledName(event.target.value);
}}
/>
<button type="submit" className="btn btn-primary">
Save
</button>
</form>
) : (
<div className="d-flex">
<div className={alignButtonsRight ? "mr-auto" : "mr-2"}>{name}</div>
<button
className="ml-2 btn btn-link p-0 border-0 text-reset"
title="Move Up"
type="button"
onClick={onMoveUp}
disabled={disableMoveUp}
>
<span className="glyphicon glyphicon-menu-left" />
</button>
<button
className="ml-2 btn btn-link p-0 border-0 text-reset"
title="Move Down"
type="button"
onClick={onMoveDown}
disabled={disableMoveDown}
>
<span className="glyphicon glyphicon-menu-right" />
</button>
<EditButton
onClick={() => {
setRenaming(true);
}}
/>
<DeleteButton onClick={onDelete} />
</div>
)}
</div>
);
};
const AddTeam = ({
addTeam,
did,
availableBuiltInTeams,
}: {
addTeam: (did: number, t?: NewLeagueTeam) => void;
did: number;
availableBuiltInTeams: NewLeagueTeam[];
}) => {
const [abbrev, setAbbrev] = useState("custom");
return (
<div className="card-body p-0 m-3">
<div className="input-group">
<select
className="form-control"
value={abbrev}
onChange={event => {
setAbbrev(event.target.value);
}}
>
<option value="custom">Custom Team</option>
{availableBuiltInTeams.map(t => (
<option key={t.abbrev} value={t.abbrev}>
{t.region} {t.name} ({t.abbrev})
</option>
))}
</select>
<div className="input-group-append">
<button
className="btn btn-secondary"
onClick={() => {
const t = availableBuiltInTeams.find(t => t.abbrev === abbrev);
addTeam(did, t);
}}
>
Add Team
</button>
</div>
</div>
</div>
);
};
const Division = ({
div,
divs,
confs,
teams,
dispatch,
addTeam,
editTeam,
disableMoveUp,
disableMoveDown,
abbrevsUsedMultipleTimes,
availableBuiltInTeams,
}: {
div: Div;
divs: Div[];
confs: Conf[];
teams: NewLeagueTeam[];
dispatch: Dispatch<Action>;
addTeam: (did: number, t?: NewLeagueTeam) => void;
editTeam: (tid: number) => void;
disableMoveUp: boolean;
disableMoveDown: boolean;
abbrevsUsedMultipleTimes: string[];
availableBuiltInTeams: NewLeagueTeam[];
}) => {
return (
<div className="card mt-3">
<CardHeader
alignButtonsRight
name={div.name}
onDelete={async () => {
if (teams.length === 0) {
dispatch({ type: "deleteDiv", did: div.did });
} else {
const siblings = divs
.filter(div2 => div2.did !== div.did)
.map(div2 => {
const conf = confs.find(conf => conf.cid === div2.cid);
return {
key: div2.did,
text: `Move teams to "${div2.name}" division (${
conf ? conf.name : "unknown conference"
})`,
};
});
const { proceed, key } = await confirmDeleteWithChlidren({
text: `When the "${div.name}" division is deleted, what should happen to its teams?`,
deleteButtonText: "Delete Division",
deleteChildrenText: `Delete all teams in the "${div.name}" division`,
siblings,
});
if (proceed) {
dispatch({ type: "deleteDiv", did: div.did, moveToDID: key });
}
}
}}
onMoveDown={() => {
dispatch({ type: "moveDiv", did: div.did, direction: 1 });
}}
onMoveUp={() => {
dispatch({ type: "moveDiv", did: div.did, direction: -1 });
}}
onRename={(name: string) => {
dispatch({ type: "renameDiv", did: div.did, name });
}}
disableMoveUp={disableMoveUp}
disableMoveDown={disableMoveDown}
/>
<ul className="list-group list-group-flush">
{teams.map(t => (
<li key={t.tid} className="list-group-item d-flex">
<div className="mr-auto">
{t.region} {t.name}{" "}
<span
className={
abbrevsUsedMultipleTimes.includes(t.abbrev)
? "text-danger"
: undefined
}
>
({t.abbrev})
</span>
</div>
<EditButton
onClick={() => {
editTeam(t.tid);
}}
/>
<DeleteButton
onClick={() => {
dispatch({ type: "deleteTeam", tid: t.tid });
}}
/>
</li>
))}
</ul>
<AddTeam
addTeam={addTeam}
did={div.did}
availableBuiltInTeams={availableBuiltInTeams}
/>
</div>
);
};
const Conference = ({
conf,
confs,
divs,
teams,
dispatch,
addTeam,
editTeam,
disableMoveUp,
disableMoveDown,
abbrevsUsedMultipleTimes,
availableBuiltInTeams,
}: {
conf: Conf;
confs: Conf[];
divs: Div[];
teams: NewLeagueTeam[];
dispatch: Dispatch<Action>;
addTeam: (did: number, t?: NewLeagueTeam) => void;
editTeam: (tid: number) => void;
disableMoveUp: boolean;
disableMoveDown: boolean;
abbrevsUsedMultipleTimes: string[];
availableBuiltInTeams: NewLeagueTeam[];
}) => {
const children = divs.filter(div => div.cid === conf.cid);
return (
<div className="card mb-3">
<CardHeader
name={conf.name}
onDelete={async () => {
if (children.length === 0) {
dispatch({ type: "deleteConf", cid: conf.cid });
} else {
const siblings = confs
.filter(conf2 => conf2.cid !== conf.cid)
.map(conf2 => ({
key: conf2.cid,
text: `Move divisions to "${conf2.name}" conference`,
}));
const { proceed, key } = await confirmDeleteWithChlidren({
text: `When the "${conf.name}" conference is deleted, what should happen to its divisions?`,
deleteButtonText: "Delete Conference",
deleteChildrenText: `Delete all divisions in the "${conf.name}" conference`,
siblings,
});
if (proceed) {
dispatch({ type: "deleteConf", cid: conf.cid, moveToCID: key });
}
}
}}
onMoveDown={() => {
dispatch({ type: "moveConf", cid: conf.cid, direction: 1 });
}}
onMoveUp={() => {
dispatch({ type: "moveConf", cid: conf.cid, direction: -1 });
}}
disableMoveUp={disableMoveUp}
disableMoveDown={disableMoveDown}
onRename={(name: string) => {
dispatch({ type: "renameConf", cid: conf.cid, name });
}}
/>
<div className="row mx-0">
{children.map((div, i) => (
<div className="col-sm-6 col-md-4" key={div.did}>
<Division
div={div}
divs={divs}
confs={confs}
dispatch={dispatch}
addTeam={addTeam}
editTeam={editTeam}
teams={teams.filter(t => t.did === div.did)}
disableMoveUp={i === 0 && disableMoveUp}
disableMoveDown={i === divs.length - 1 && disableMoveDown}
abbrevsUsedMultipleTimes={abbrevsUsedMultipleTimes}
availableBuiltInTeams={availableBuiltInTeams}
/>
</div>
))}
</div>
<div className="card-body p-0 m-3 d-flex">
<button
className="btn btn-secondary ml-auto"
onClick={() => {
dispatch({ type: "addDiv", cid: conf.cid });
}}
>
Add Division
</button>
</div>
</div>
);
};
const CustomizeTeams = ({
onCancel,
onSave,
initialConfs,
initialDivs,
initialTeams,
getDefaultConfsDivsTeams,
godModeLimits,
}: {
onCancel: () => void;
onSave: (obj: ConfsDivsTeams) => void;
initialConfs: Conf[];
initialDivs: Div[];
initialTeams: NewLeagueTeam[];
getDefaultConfsDivsTeams: () => ConfsDivsTeams;
godModeLimits: View<"newLeague">["godModeLimits"];
}) => {
const [{ confs, divs, teams }, dispatch] = useReducer(reducer, {
confs: [...initialConfs],
divs: [...initialDivs],
teams: [...initialTeams],
});
const [editingInfo, setEditingInfo] = useState<
| {
type: "none";
}
| {
type: "add";
did: number;
}
| {
type: "edit";
tid: number;
}
>({
type: "none",
});
const [randomizing, setRandomizing] = useState(false);
const editTeam = (tid: number) => {
setEditingInfo({
type: "edit",
tid,
});
};
const addTeam = (did: number, t?: NewLeagueTeam) => {
if (t) {
const div = divs.find(div => div.did === did);
if (div) {
dispatch({
type: "addTeam",
t: {
...t,
cid: div.cid,
did: div.did,
},
});
}
} else {
setEditingInfo({
type: "add",
did,
});
}
};
let editingTeam: NewLeagueTeam | undefined;
if (editingInfo.type === "add") {
const div = divs.find(div => div.did === editingInfo.did);
if (div) {
editingTeam = {
tid: -1,
region: "",
name: "",
abbrev: "NEW",
pop: 1,
popRank: -1,
cid: div.cid,
did: div.did,
};
}
} else if (editingInfo.type === "edit") {
editingTeam = teams.find(t => t.tid === editingInfo.tid);
}
const abbrevCounts = countBy(teams, "abbrev");
const abbrevsUsedMultipleTimes: string[] = [];
for (const [abbrev, count] of Object.entries(abbrevCounts)) {
if (count > 1) {
abbrevsUsedMultipleTimes.push(abbrev);
}
}
const availableAbbrevs = getUnusedAbbrevs(teams);
const param = availableAbbrevs.map(abbrev => ({
tid: -1,
cid: -1,
did: -1,
abbrev,
}));
const availableBuiltInTeams: NewLeagueTeam[] = orderBy(
getTeamInfos(param).map(t => ({
...t,
popRank: -1,
})),
["region", "name"],
);
const resetDefault = () => {
const info = getDefaultConfsDivsTeams();
dispatch({
type: "setState",
...info,
});
};
const randomize = (weightByPopulation: boolean) => async () => {
setRandomizing(true);
try {
// If there are no teams, auto reset to default first
let myDivs = divs;
let myTeams = teams;
let myConfs = confs;
if (myTeams.length === 0) {
const info = getDefaultConfsDivsTeams();
myDivs = info.divs;
myTeams = info.teams;
myConfs = info.confs;
}
const numTeamsPerDiv = myDivs.map(
div => myTeams.filter(t => t.did === div.did).length,
);
const response = await toWorker(
"main",
"getRandomTeams",
myDivs,
numTeamsPerDiv,
weightByPopulation,
);
if (typeof response === "string") {
logEvent({
type: "error",
text: response,
saveToDb: false,
});
} else {
dispatch({
type: "setState",
teams: response,
divs: myDivs,
confs: myConfs,
});
}
setRandomizing(false);
} catch (error) {
setRandomizing(false);
throw error;
}
};
return (
<>
{confs.map((conf, i) => (
<Conference
key={conf.cid}
conf={conf}
confs={confs}
divs={divs}
teams={teams}
dispatch={dispatch}
addTeam={addTeam}
editTeam={editTeam}
disableMoveUp={i === 0}
disableMoveDown={i === confs.length - 1}
abbrevsUsedMultipleTimes={abbrevsUsedMultipleTimes}
availableBuiltInTeams={availableBuiltInTeams}
/>
))}
<div className="mb-3 d-flex">
<button
className="btn btn-secondary ml-auto"
onClick={() => {
dispatch({ type: "addConf" });
}}
style={{
marginRight: 15,
}}
>
Add Conference
</button>
</div>
<StickyBottomButtons>
<Dropdown>
<Dropdown.Toggle
variant="danger"
id="customize-teams-reset"
disabled={randomizing}
>
{randomizing ? processingSpinner : "Reset"}
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item onClick={resetDefault}>Default</Dropdown.Item>
<Dropdown.Item onClick={randomize(false)}>
Random built-in teams
</Dropdown.Item>
<Dropdown.Item onClick={randomize(true)}>
Random built-in teams (population weighted)
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<div className="ml-2 pt-2">
<HelpPopover title="Reset">
<p>
<b>Default</b>: Resets conferences, divisions, and teams to their
default values.
</p>
<p>
<b>Random built-in teams</b>: This replaces any teams you
currently have with random built-in teams. Those teams are grouped
into divisions based on their geographic location. Then, if your
division names are the same as the default division names and each
division has the same number of teams, it tries to assign each
group to a division name that makes sense.
</p>
<p>
<b>Random built-in teams (population weighted)</b>: Same as above,
except larger cities are more likely to be selected, so the set of
teams may feel a bit more realistic.
</p>
</HelpPopover>
</div>
<form
className="btn-group ml-auto"
onSubmit={event => {
event.preventDefault();
if (abbrevsUsedMultipleTimes.length > 0) {
logEvent({
type: "error",
text: `You cannot use the same abbrev for multiple teams: ${abbrevsUsedMultipleTimes.join(
", ",
)}`,
saveToDb: false,
});
return;
}
if (teams.length < 2) {
logEvent({
type: "error",
text: "Your league must have at least 2 teams in it.",
saveToDb: false,
});
return;
}
onSave({ confs, divs, teams });
}}
>
<button
className="btn btn-secondary"
type="button"
onClick={onCancel}
disabled={randomizing}
>
Cancel
</button>
<button
className="btn btn-primary mr-2"
type="submit"
disabled={randomizing}
>
Save Teams
</button>
</form>
</StickyBottomButtons>
<UpsertTeamModal
key={editingInfo.type === "edit" ? editingInfo.tid : editingInfo.type}
t={editingTeam}
confs={confs}
divs={divs}
onSave={(t: NewLeagueTeam) => {
if (t.tid === -1) {
dispatch({ type: "addTeam", t });
} else {
dispatch({ type: "editTeam", t });
}
setEditingInfo({ type: "none" });
}}
onCancel={() => {
setEditingInfo({ type: "none" });
}}
godModeLimits={godModeLimits}
/>
</>
);
};
export default CustomizeTeams; | the_stack |
import { expect } from 'chai';
import fetch from 'node-fetch';
import { Application, middlewareCall, MemoryRequest, Context } from '../src';
import * as fs from 'fs';
import { Writable } from 'stream';
describe('Application', () => {
it('should instantiate', () => {
const application = new Application();
expect(application).to.be.an.instanceof(Application);
});
it('should respond to HTTP requests', async () => {
const application = new Application();
application.use((ctx, next) => {
ctx.response.body = 'hi';
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.equal('hi');
expect(response.headers.get('server')).to.equal(
// eslint-disable-next-line @typescript-eslint/no-var-requires
'curveball/' + require('../package.json').version
);
expect(response.status).to.equal(200);
server.close();
});
it('should accept hostname', async () => {
const application = new Application();
application.use((ctx, next) => {
ctx.response.body = 'hi';
});
const server = application.listen(5555, '0.0.0.0');
const response = await fetch('http://0.0.0.0:5555');
const body = await response.text();
expect(body).to.equal('hi');
expect(response.headers.get('server')).to.equal(
// eslint-disable-next-line @typescript-eslint/no-var-requires
'curveball/' + require('../package.json').version
);
expect(response.status).to.equal(200);
server.close();
});
it('should work with Buffer responses', async () => {
const application = new Application();
application.use((ctx, next) => {
ctx.response.body = Buffer.from('hi');
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.equal('hi');
expect(response.headers.get('server')).to.equal(
// eslint-disable-next-line @typescript-eslint/no-var-requires
'curveball/' + require('../package.json').version
);
expect(response.status).to.equal(200);
server.close();
});
it('should work with Readable stream responses', async () => {
const application = new Application();
application.use((ctx, next) => {
ctx.response.body = fs.createReadStream(__filename);
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body.substring(0, 6)).to.equal('import');
expect(response.headers.get('server')).to.equal(
// eslint-disable-next-line @typescript-eslint/no-var-requires
'curveball/' + require('../package.json').version
);
expect(response.status).to.equal(200);
server.close();
});
it('should work with a callback resonse body', async () => {
const application = new Application();
application.use((ctx, next) => {
ctx.response.body = (stream: Writable) => {
stream.write('hi');
stream.end();
};
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.equal('hi');
expect(response.headers.get('server')).to.equal(
// eslint-disable-next-line @typescript-eslint/no-var-requires
'curveball/' + require('../package.json').version
);
expect(response.status).to.equal(200);
server.close();
});
it('should automatically JSON-encode objects', async () => {
const application = new Application();
application.use((ctx, next) => {
ctx.response.body = { foo: 'bar' };
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.equal('{"foo":"bar"}');
expect(response.headers.get('server')).to.equal(
// eslint-disable-next-line @typescript-eslint/no-var-requires
'curveball/' + require('../package.json').version
);
expect(response.status).to.equal(200);
server.close();
});
it('should handle "null" bodies', async () => {
const application = new Application();
application.use((ctx, next) => {
ctx.response.body = null;
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.equal('');
expect(response.headers.get('server')).to.equal(
// eslint-disable-next-line @typescript-eslint/no-var-requires
'curveball/' + require('../package.json').version
);
expect(response.status).to.equal(200);
server.close();
});
it('should throw an exception for unsupported bodies', async () => {
const application = new Application();
application.use((ctx, next) => {
ctx.response.body = 5;
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.include(': 500');
expect(response.headers.get('server')).to.equal(
// eslint-disable-next-line @typescript-eslint/no-var-requires
'curveball/' + require('../package.json').version
);
expect(response.status).to.equal(500);
server.close();
});
it('should work with multiple calls to middlewares', async () => {
const application = new Application();
application.use(async (ctx, next) => {
ctx.response.body = 'hi';
await next();
});
application.use((ctx, next) => {
ctx.response.headers.set('X-Foo', 'bar');
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.equal('hi');
expect(response.headers.get('X-Foo')).to.equal('bar');
expect(response.status).to.equal(200);
server.close();
});
it('should work with multiple middlewares as arguments', async () => {
const application = new Application();
application.use(async (ctx, next) => {
ctx.response.body = 'hi';
await next();
}),
application.use((ctx, next) => {
ctx.response.headers.set('X-Foo', 'bar');
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.equal('hi');
expect(response.headers.get('X-Foo')).to.equal('bar');
expect(response.status).to.equal(200);
server.close();
});
it('should work with object-middlewares', async () => {
const application = new Application();
const myMw = {
// eslint-disable-next-line @typescript-eslint/ban-types
[middlewareCall]: async (ctx: Context, next: Function) => {
ctx.response.body = 'hi';
}
};
application.use(myMw);
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.equal('hi');
expect(response.status).to.equal(200);
server.close();
});
it('should not call sequential middlewares if next is not called', async () => {
const application = new Application();
application.use((ctx, next) => {
ctx.response.body = 'hi';
});
application.use((ctx, next) => {
ctx.response.headers.set('X-Foo', 'bar');
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.equal('hi');
expect(response.headers.get('X-Foo')).to.equal(null);
expect(response.status).to.equal(200);
server.close();
});
describe('When an uncaught exception happens', () => {
it('should trigger an "error" event', async () => {
const application = new Application();
application.use((ctx, next) => {
throw new Error('hi');
});
let error;
application.on('error', err => {
error = err;
});
const server = application.listen(5555);
await fetch('http://localhost:5555');
expect(error).to.be.an.instanceof(Error);
// @ts-expect-error: TS complains about error possibly being undefined.
expect(error.message).to.equal('hi');
server.close();
});
it('should return an error message in the response body.', async () => {
const application = new Application();
application.use((ctx, next) => {
throw new Error('hi');
});
const server = application.listen(5555);
const response = await fetch('http://localhost:5555');
const body = await response.text();
expect(body).to.include(': 500');
server.close();
});
});
describe('When no middlewares are defined', () => {
it('should do nothing', async () => {
const application = new Application();
const server = application.listen(5555);
await fetch('http://localhost:5555');
server.close();
});
});
describe('Subrequests', () => {
it('should work with a Request object', async () => {
let innerRequest;
const application = new Application();
application.use(ctx => {
innerRequest = ctx.request;
ctx.response.status = 201;
ctx.response.headers.set('X-Foo', 'bar');
ctx.response.body = 'hello world';
});
const request = new MemoryRequest(
'POST',
'/',
{ foo: 'bar' },
'request-body'
);
const response = await application.subRequest(request);
expect(response.status).to.equal(201);
expect(response.headers.get('X-Foo')).to.equal('bar');
expect(response.body).to.equal('hello world');
expect(innerRequest).to.equal(request);
});
it('should work without a Request object', async () => {
const application = new Application();
application.use(ctx => {
ctx.response.status = 201;
ctx.response.headers.set('X-Foo', 'bar');
ctx.response.body = 'hello world';
});
const response = await application.subRequest(
'POST',
'/',
{ foo: 'bar' },
'request-body'
);
expect(response.status).to.equal(201);
expect(response.headers.get('X-Foo')).to.equal('bar');
expect(response.body).to.equal('hello world');
});
});
describe('When middlewares did not set an explicit status', () => {
it('should return 200 when a body was set', async () => {
const app = new Application();
app.use(ctx => {
ctx.response.body = 'hi';
});
const server = app.listen(5555);
const response = await fetch('http://localhost:5555');
expect(response.status).to.equal(200);
server.close();
});
it('should return 404 when no body was set', async () => {
const app = new Application();
const server = app.listen(5555);
const response = await fetch('http://localhost:5555');
expect(response.status).to.equal(404);
server.close();
});
});
}); | the_stack |
import { LiskValidationError } from '@liskhq/lisk-validator';
import { EventEmitter2, ListenerFn } from 'eventemitter2';
import { Dealer, Router, Subscriber } from 'zeromq';
import { Logger } from '../logger';
import { ActionInfoForBus, ChannelType } from '../types';
import { Action } from './action';
import { BaseChannel } from './channels/base_channel';
import { IPC_EVENTS } from './constants';
import { Event, EventsDefinition } from './event';
import { IPCServer } from './ipc/ipc_server';
import * as JSONRPC from './jsonrpc';
import { WSServer } from './ws/ws_server';
import { HTTPServer } from './http/http_server';
import { JSONRPCError } from './jsonrpc';
interface BusConfiguration {
readonly httpServer?: HTTPServer;
readonly internalIPCServer: IPCServer;
readonly externalIPCServer?: IPCServer;
readonly wsServer?: WSServer;
}
interface RegisterChannelOptions {
readonly type: string;
readonly channel: BaseChannel;
readonly socketPath?: string;
}
interface ChannelInfo {
readonly channel?: BaseChannel;
readonly rpcClient?: Dealer;
readonly actions: {
[key: string]: ActionInfoForBus;
};
readonly events: EventsDefinition;
readonly type: ChannelType;
}
interface RegisterToBusRequestObject {
readonly moduleName: string;
readonly eventsList: ReadonlyArray<string>;
readonly actionsInfo: {
[key: string]: Action;
};
readonly options: RegisterChannelOptions;
}
const parseError = (id: JSONRPC.ID, err: Error | JSONRPC.JSONRPCError): JSONRPC.JSONRPCError => {
if (err instanceof JSONRPC.JSONRPCError) {
return err;
}
return new JSONRPC.JSONRPCError(
err.message,
JSONRPC.errorResponse(id, JSONRPC.internalError(err.message)),
);
};
export class Bus {
public logger: Logger;
private readonly actions: {
[key: string]: ActionInfoForBus;
};
private readonly events: { [key: string]: boolean };
private readonly channels: {
[key: string]: ChannelInfo;
};
private readonly rpcClients: { [key: string]: Dealer };
private readonly _internalIPCServer?: IPCServer;
private readonly _externalIPCServer?: IPCServer;
private readonly _rpcRequestIds: Set<string>;
private readonly _emitter: EventEmitter2;
private readonly _wsServer?: WSServer;
private readonly _httpServer?: HTTPServer;
private readonly _handleRPCResponse: (rpcClient: Dealer) => Promise<void>;
private readonly _handleRPC: (rpcServer: Router) => Promise<void>;
private readonly _handleExternalRPC: (rpcServer: Router) => Promise<void>;
private readonly _handleEvents: (subSocket: Subscriber) => Promise<void>;
public constructor(logger: Logger, config: BusConfiguration) {
this.logger = logger;
this._emitter = new EventEmitter2({
wildcard: true,
delimiter: ':',
maxListeners: 1000,
});
// Hash map used instead of arrays for performance.
this.actions = {};
this.events = {};
this.channels = {};
this.rpcClients = {};
this._rpcRequestIds = new Set();
this._internalIPCServer = config.internalIPCServer;
this._externalIPCServer = config.externalIPCServer;
this._httpServer = config.httpServer;
this._wsServer = config.wsServer;
// Handle RPC requests responses coming back from different ipcServers on rpcClient
this._handleRPCResponse = async (rpcClient: Dealer): Promise<void> => {
for await (const [requestId, result] of rpcClient) {
if (this._rpcRequestIds.has(requestId.toString())) {
this._emitter.emit(requestId.toString(), JSON.parse(result.toString()));
continue;
}
}
};
this._handleRPC = async (rpcServer: Router): Promise<void> => {
for await (const [sender, request, params] of rpcServer) {
switch (request.toString()) {
case IPC_EVENTS.REGISTER_CHANNEL: {
const { moduleName, eventsList, actionsInfo, options } = JSON.parse(
params.toString(),
) as RegisterToBusRequestObject;
this.registerChannel(moduleName, eventsList, actionsInfo, options).catch(err => {
this.logger.debug(
err,
`Error occurred while Registering channel for module ${moduleName}.`,
);
});
break;
}
case IPC_EVENTS.RPC_EVENT: {
const requestData = JSON.parse(params.toString()) as JSONRPC.RequestObject;
this.invoke(requestData)
.then(result => {
// Send back result RPC request for a given requestId
rpcServer
.send([sender, requestData.id as string, JSON.stringify(result)])
.catch(error => {
this.logger.debug(
{ err: error as Error },
`Failed to send request response: ${requestData.id as string} to ipc client.`,
);
});
})
.catch(err => {
this.logger.debug(err, 'Error occurred while sending RPC results.');
});
break;
}
default:
break;
}
}
};
this._handleExternalRPC = async (rpcServer: Router): Promise<void> => {
for await (const [sender, request, params] of rpcServer) {
switch (request.toString()) {
case IPC_EVENTS.RPC_EVENT: {
const requestData = JSON.parse(params.toString()) as JSONRPC.RequestObject;
this.invoke(requestData)
.then(result => {
// Send back result RPC request for a given requestId
rpcServer
.send([sender, requestData.id as string, JSON.stringify(result)])
.catch(error => {
this.logger.debug(
{ err: error as Error },
`Failed to send request response: ${requestData.id as string} to ipc client.`,
);
});
})
.catch((err: JSONRPCError) => {
rpcServer
.send([sender, requestData.id as string, JSON.stringify(err.response)])
.catch(error => {
this.logger.debug(
{ err: error as Error },
`Failed to send error response: ${requestData.id as string} to ipc client.`,
);
});
});
break;
}
default:
break;
}
}
};
this._handleEvents = async (subSocket: Subscriber) => {
for await (const [_event, eventData] of subSocket) {
this.publish(eventData.toString());
}
};
}
public async init(): Promise<boolean> {
if (this._internalIPCServer) {
await this._setupIPCInternalServer();
}
if (this._externalIPCServer) {
await this._setupIPCExternalServer();
}
if (this._wsServer) {
await this._setupWSServer();
}
if (this._httpServer) {
await this._setupHTTPServer();
}
return true;
}
// eslint-disable-next-line @typescript-eslint/require-await
public async registerChannel(
moduleName: string,
// Events should also include the module name
events: EventsDefinition,
actions: { [key: string]: Action },
options: RegisterChannelOptions,
): Promise<void> {
if (Object.keys(this.channels).includes(moduleName)) {
throw new Error(`Channel for module ${moduleName} is already registered.`);
}
events.forEach(eventName => {
if (this.events[`${moduleName}:${eventName}`] !== undefined) {
throw new Error(`Event "${eventName}" already registered with bus.`);
}
this.events[`${moduleName}:${eventName}`] = true;
});
this._wsServer?.registerAllowedEvent([...this.getEvents()]);
Object.keys(actions).forEach(actionName => {
if (this.actions[`${moduleName}:${actionName}`] !== undefined) {
throw new Error(`Action "${actionName}" already registered with bus.`);
}
this.actions[`${moduleName}:${actionName}`] = actions[actionName];
});
if (options.type === ChannelType.ChildProcess && options.socketPath) {
const rpcClient = new Dealer();
rpcClient.connect(options.socketPath);
this.rpcClients[moduleName] = rpcClient;
this._handleRPCResponse(rpcClient).catch(err => {
this.logger.debug(err, 'Error occured while listening to RPC results on RPC Dealer.');
});
this.channels[moduleName] = {
rpcClient,
events,
actions,
type: ChannelType.ChildProcess,
};
} else {
this.channels[moduleName] = {
channel: options.channel,
events,
actions,
type: ChannelType.InMemory,
};
}
}
public async invoke<T>(
rawRequest: string | JSONRPC.RequestObject,
): Promise<JSONRPC.ResponseObjectWithResult<T>> {
let request!: JSONRPC.RequestObject;
// As the request can be invoked from external source, so we should validate if it exists and valid JSON object
if (!rawRequest) {
this.logger.error('Empty invoke request.');
throw new JSONRPC.JSONRPCError(
'Invalid invoke request.',
JSONRPC.errorResponse(null, JSONRPC.invalidRequest()),
);
}
try {
request =
typeof rawRequest === 'string'
? (JSON.parse(rawRequest) as JSONRPC.RequestObject)
: rawRequest;
} catch (error) {
throw new JSONRPC.JSONRPCError(
'Invalid invoke request.',
JSONRPC.errorResponse(null, JSONRPC.invalidRequest()),
);
}
try {
JSONRPC.validateJSONRPCRequest(request as never);
} catch (error) {
this.logger.error({ err: error as LiskValidationError }, 'Invalid invoke request.');
throw new JSONRPC.JSONRPCError(
'Invalid invoke request.',
JSONRPC.errorResponse(request.id, JSONRPC.invalidRequest()),
);
}
const action = Action.fromJSONRPCRequest(request);
const actionFullName = action.key();
if (this.actions[actionFullName] === undefined) {
throw new JSONRPC.JSONRPCError(
`Action '${actionFullName}' is not registered to bus.`,
JSONRPC.errorResponse(
action.id,
JSONRPC.internalError(`Action '${actionFullName}' is not registered to bus.`),
),
);
}
const actionParams = action.params;
const channelInfo = this.channels[action.module];
if (channelInfo.type === ChannelType.InMemory) {
try {
const result = await (channelInfo.channel as BaseChannel).invoke<T>(
actionFullName,
actionParams,
);
return action.buildJSONRPCResponse({
result,
}) as JSONRPC.ResponseObjectWithResult<T>;
} catch (error) {
throw parseError(action.id, error);
}
}
return new Promise((resolve, reject) => {
this._rpcRequestIds.add(action.id as string);
(channelInfo.rpcClient as Dealer)
.send([IPC_EVENTS.RPC_EVENT, JSON.stringify(action.toJSONRPCRequest())])
.then(_ => {
const requestTimeout = setTimeout(() => {
reject(new Error('Request timed out on invoke.'));
}, IPC_EVENTS.RPC_REQUEST_TIMEOUT);
// Listen to this event once for serving the request
this._emitter.once(
action.id as string,
(response: JSONRPC.ResponseObjectWithResult<T>) => {
clearTimeout(requestTimeout);
this._rpcRequestIds.delete(action.id as string);
return resolve(response);
},
);
})
.catch(err => {
this.logger.debug(err, 'Error occurred while sending RPC request.');
});
});
}
public publish(rawRequest: string | JSONRPC.NotificationRequest): void {
let request!: JSONRPC.NotificationRequest;
// As the request can be invoked from external source, so we should validate if it exists and valid JSON object
if (!rawRequest) {
this.logger.error('Empty publish request.');
throw new JSONRPC.JSONRPCError(
'Invalid publish request.',
JSONRPC.errorResponse(null, JSONRPC.invalidRequest()),
);
}
try {
request =
typeof rawRequest === 'string'
? (JSON.parse(rawRequest) as JSONRPC.RequestObject)
: rawRequest;
} catch (error) {
throw new JSONRPC.JSONRPCError(
'Invalid publish request.',
JSONRPC.errorResponse(null, JSONRPC.invalidRequest()),
);
}
try {
JSONRPC.validateJSONRPCNotification(request as never);
} catch (error) {
this.logger.error({ err: error as LiskValidationError }, 'Invalid publish request.');
throw new JSONRPC.JSONRPCError(
'Invalid publish request.',
JSONRPC.errorResponse(null, JSONRPC.invalidRequest()),
);
}
const event = Event.fromJSONRPCNotification(rawRequest);
const eventName = event.key();
const notification = event.toJSONRPCNotification();
if (!this.getEvents().includes(eventName)) {
throw new JSONRPC.JSONRPCError(
`Event ${eventName} is not registered to bus.`,
JSONRPC.errorResponse(
null,
JSONRPC.internalError(`Event ${eventName} is not registered to bus.`),
),
);
}
// Communicate through event emitter
this._emitter.emit(eventName, notification);
// Communicate through unix socket
if (this._internalIPCServer) {
this._internalIPCServer.pubSocket
.send([eventName, JSON.stringify(notification)])
.catch(error => {
this.logger.debug(
{ err: error as Error },
`Failed to publish event: ${eventName} to ipc server.`,
);
});
}
if (this._externalIPCServer) {
this._externalIPCServer.pubSocket
.send([eventName, JSON.stringify(notification)])
.catch(error => {
this.logger.debug(
{ err: error as Error },
`Failed to publish event: ${eventName} to ipc server.`,
);
});
}
if (this._wsServer) {
try {
this._wsServer.broadcast(notification);
} catch (error) {
this.logger.debug(
{ err: error as Error },
`Failed to publish event: ${eventName} to ws server.`,
);
}
}
}
public subscribe(eventName: string, cb: ListenerFn): void {
if (!this.getEvents().includes(eventName)) {
this.logger.info(`Event ${eventName} was subscribed but not registered to the bus yet.`);
}
// Communicate through event emitter
this._emitter.on(eventName, cb);
}
public unsubscribe(eventName: string, cb: ListenerFn): void {
if (!this.getEvents().includes(eventName)) {
this.logger.info(
`Can't unsubscribe to event ${eventName} that was not registered to the bus yet.`,
);
}
this._emitter.off(eventName, cb);
}
public once(eventName: string, cb: ListenerFn): this {
if (!this.getEvents().includes(eventName)) {
this.logger.info(`Event ${eventName} was subscribed but not registered to the bus yet.`);
}
// Communicate through event emitter
this._emitter.once(eventName, cb);
return this;
}
public getActions(): ReadonlyArray<string> {
return Object.keys(this.actions);
}
public getEvents(): ReadonlyArray<string> {
return Object.keys(this.events);
}
// eslint-disable-next-line @typescript-eslint/require-await
public async cleanup(): Promise<void> {
this._emitter.removeAllListeners();
this._internalIPCServer?.stop();
this._externalIPCServer?.stop();
this._wsServer?.stop();
this._httpServer?.stop();
// Close all the RPC Clients
for (const key of Object.keys(this.rpcClients)) {
this.rpcClients[key].close();
}
}
private async _setupIPCInternalServer(): Promise<void> {
await this._internalIPCServer?.start();
this._handleEvents((this._internalIPCServer as IPCServer).subSocket).catch(err => {
this.logger.debug(err, 'Error occured while listening to events on subscriber.');
});
this._handleRPC((this._internalIPCServer as IPCServer).rpcServer).catch(err => {
this.logger.debug(err, 'Error occured while listening to RPCs on RPC router.');
});
}
private async _setupIPCExternalServer(): Promise<void> {
await this._externalIPCServer?.start();
this._handleEvents((this._externalIPCServer as IPCServer).subSocket).catch(err => {
this.logger.debug(err, 'Error occured while listening to events on subscriber.');
});
this._handleExternalRPC((this._externalIPCServer as IPCServer).rpcServer).catch(err => {
this.logger.debug(err, 'Error occured while listening to RPCs on RPC router.');
});
}
// eslint-disable-next-line @typescript-eslint/require-await
private async _setupWSServer(): Promise<void> {
this._wsServer?.start((socket, message) => {
this.invoke(message)
.then(data => {
socket.send(JSON.stringify(data as JSONRPC.ResponseObjectWithResult));
})
.catch((error: JSONRPC.JSONRPCError) => {
socket.send(JSON.stringify(error.response));
});
});
}
// eslint-disable-next-line @typescript-eslint/require-await
private async _setupHTTPServer(): Promise<void> {
this._httpServer?.start((_req, res, message) => {
this.invoke(message)
.then(data => {
res.end(JSON.stringify(data as JSONRPC.ResponseObjectWithResult));
})
.catch((error: JSONRPC.JSONRPCError) => {
res.end(JSON.stringify(error.response));
});
});
}
} | the_stack |
import settings from 'carbon-components/es/globals/js/settings';
import { classMap } from 'lit-html/directives/class-map';
import { TemplateResult } from 'lit-html';
import { ifDefined } from 'lit-html/directives/if-defined';
import { html, property, query, customElement, LitElement } from 'lit-element';
import ChevronDown16 from '@carbon/icons/lib/chevron--down/16';
import WarningFilled16 from '@carbon/icons/lib/warning--filled/16';
import FocusMixin from '../../globals/mixins/focus';
import FormMixin from '../../globals/mixins/form';
import HostListenerMixin from '../../globals/mixins/host-listener';
import ValidityMixin from '../../globals/mixins/validity';
import HostListener from '../../globals/decorators/host-listener';
import { find, forEach, indexOf } from '../../globals/internal/collection-helpers';
import { DROPDOWN_COLOR_SCHEME, DROPDOWN_KEYBOARD_ACTION, DROPDOWN_SIZE, DROPDOWN_TYPE, NAVIGATION_DIRECTION } from './defs';
import BXDropdownItem from './dropdown-item';
import styles from './dropdown.scss';
export { DROPDOWN_COLOR_SCHEME, DROPDOWN_KEYBOARD_ACTION, DROPDOWN_SIZE, DROPDOWN_TYPE, NAVIGATION_DIRECTION };
const { prefix } = settings;
/**
* Dropdown.
* @element bx-dropdown
* @csspart label-text The label text.
* @csspart helper-text The helper text.
* @csspart trigger-button The trigger button.
* @csspart menu-body The menu body.
* @csspart validity-message The validity message.
* @fires bx-dropdown-beingselected
* The custom event fired before a dropdown item is selected upon a user gesture.
* Cancellation of this event stops changing the user-initiated selection.
* @fires bx-dropdown-beingtoggled
* The custom event fired before the open state of this dropdown is toggled upon a user gesture.
* Cancellation of this event stops the user-initiated toggling.
* @fires bx-dropdown-selected - The custom event fired after a dropdown item is selected upon a user gesture.
* @fires bx-dropdown-toggled - The custom event fired after the open state of this dropdown is toggled upon a user gesture.
*/
@customElement(`${prefix}-dropdown`)
class BXDropdown extends ValidityMixin(HostListenerMixin(FormMixin(FocusMixin(LitElement)))) {
/**
* The latest status of this dropdown, for screen reader to accounce.
*/
protected _assistiveStatusText?: string;
/**
* The content of the selected item.
*/
protected _selectedItemContent: DocumentFragment | null = null;
/**
* `true` if the trigger button should be focusable.
* Derived class can set `false` to this if the trigger button contains another primary focusable element (e.g. `<input>`).
*/
protected _shouldTriggerBeFocusable = true;
/**
* The list box `<div>` node.
*/
@query(`.${prefix}--list-box`)
protected _listBoxNode!: HTMLDivElement;
/**
* The `<slot>` element for the helper text in the shadow DOM.
*/
@query('slot[name="helper-text"]')
protected _slotHelperTextNode!: HTMLSlotElement;
/**
* The `<slot>` element for the label text in the shadow DOM.
*/
@query('slot[name="label-text"]')
protected _slotLabelTextNode!: HTMLSlotElement;
/**
* @param itemToSelect A dropdown item. Absense of this argument means clearing selection.
* @returns `true` if the selection of this dropdown should change if the given item is selected upon user interaction.
*/
protected _selectionShouldChange(itemToSelect?: BXDropdownItem) {
return !itemToSelect || itemToSelect.value !== this.value;
}
/**
* A callback that runs after change in dropdown selection upon user interaction is confirmed.
* @param itemToSelect
* A dropdown item.
* Absense of this argument means clearing selection, which may be handled by a derived class.
*/
protected _selectionDidChange(itemToSelect?: BXDropdownItem) {
if (itemToSelect) {
this.value = itemToSelect.value;
forEach(this.querySelectorAll((this.constructor as typeof BXDropdown).selectorItemSelected), item => {
(item as BXDropdownItem).selected = false;
});
itemToSelect.selected = true;
this._assistiveStatusText = this.selectedItemAssistiveText;
this._handleUserInitiatedToggle(false);
}
}
/**
* Handles `click` event on the top-level element in the shadow DOM.
* @param event The event.
*/
protected _handleClickInner(event: MouseEvent) {
if (this.shadowRoot!.contains(event.target as Node)) {
this._handleUserInitiatedToggle();
} else {
const item = (event.target as Element).closest((this.constructor as typeof BXDropdown).selectorItem) as BXDropdownItem;
if (this.contains(item)) {
this._handleUserInitiatedSelectItem(item);
}
}
}
/**
* Handler for the `keydown` event on the top-level element in the shadow DOM.
*/
protected _handleKeydownInner(event: KeyboardEvent) {
const { key } = event;
const action = (this.constructor as typeof BXDropdown).getAction(key);
if (!this.open) {
switch (action) {
case DROPDOWN_KEYBOARD_ACTION.NAVIGATING:
this._handleUserInitiatedToggle(true);
// If this menu gets open with an arrow key, reset the highlight
this._clearHighlight();
break;
default:
break;
}
} else {
switch (action) {
case DROPDOWN_KEYBOARD_ACTION.CLOSING:
this._handleUserInitiatedToggle(false);
break;
case DROPDOWN_KEYBOARD_ACTION.NAVIGATING:
this._navigate(NAVIGATION_DIRECTION[key]);
break;
default:
break;
}
}
}
/**
* Handler for the `keypress` event on the top-level element in the shadow DOM.
*/
protected _handleKeypressInner(event: KeyboardEvent) {
const { key } = event;
const action = (this.constructor as typeof BXDropdown).getAction(key);
if (!this.open) {
switch (action) {
case DROPDOWN_KEYBOARD_ACTION.TRIGGERING:
this._handleUserInitiatedToggle(true);
break;
default:
break;
}
} else {
switch (action) {
case DROPDOWN_KEYBOARD_ACTION.TRIGGERING:
{
const constructor = this.constructor as typeof BXDropdown;
const highlightedItem = this.querySelector(constructor.selectorItemHighlighted) as BXDropdownItem;
if (highlightedItem) {
this._handleUserInitiatedSelectItem(highlightedItem);
} else {
this._handleUserInitiatedToggle(false);
}
}
break;
default:
break;
}
}
}
/**
* Handles `blur` event handler on the document this element is in.
* @param event The event.
*/
@HostListener('focusout')
// @ts-ignore: The decorator refers to this method but TS thinks this method is not referred to
protected _handleFocusOut(event: FocusEvent) {
if (!this.contains(event.relatedTarget as Node)) {
this._handleUserInitiatedToggle(false);
}
}
/**
* Handles `slotchange` event for the `<slot>` for helper text.
*/
protected _handleSlotchangeHelperText() {
this.requestUpdate();
}
/**
* Handles `slotchange` event for the `<slot>` for label text.
*/
protected _handleSlotchangeLabelText() {
this.requestUpdate();
}
/**
* Handles user-initiated selection of a dropdown item.
* @param [item] The dropdown item user wants to select. Absense of this argument means clearing selection.
*/
protected _handleUserInitiatedSelectItem(item?: BXDropdownItem) {
if (this._selectionShouldChange(item)) {
const init = {
bubbles: true,
composed: true,
detail: {
item,
},
};
const constructor = this.constructor as typeof BXDropdown;
const beforeSelectEvent = new CustomEvent(constructor.eventBeforeSelect, {
...init,
cancelable: true,
});
if (this.dispatchEvent(beforeSelectEvent)) {
this._selectionDidChange(item);
const afterSelectEvent = new CustomEvent(constructor.eventSelect, init);
this.dispatchEvent(afterSelectEvent);
}
}
}
/**
* Handles user-initiated toggling the open state.
* @param [force] If specified, forces the open state to the given one.
*/
protected _handleUserInitiatedToggle(force: boolean = !this.open) {
const { eventBeforeToggle, eventToggle } = this.constructor as typeof BXDropdown;
const init = {
bubbles: true,
cancelable: true,
composed: true,
detail: {
open: force,
},
};
if (this.dispatchEvent(new CustomEvent(eventBeforeToggle, init))) {
this.open = force;
if (this.open) {
this._assistiveStatusText = this.selectingItemsAssistiveText;
} else {
const {
selectedItemAssistiveText,
triggerContent,
_assistiveStatusText: assistiveStatusText,
_selectedItemContent: selectedItemContent,
} = this;
const selectedItemText = (selectedItemContent && selectedItemContent.textContent) || triggerContent;
if (selectedItemText && assistiveStatusText !== selectedItemAssistiveText) {
this._assistiveStatusText = selectedItemText;
}
forEach(this.querySelectorAll((this.constructor as typeof BXDropdown).selectorItemHighlighted), item => {
(item as BXDropdownItem).highlighted = false;
});
}
this.requestUpdate();
this.dispatchEvent(new CustomEvent(eventToggle, init));
}
}
/**
* Clears the selection of dropdown items.
*/
protected _clearHighlight() {
forEach(this.querySelectorAll((this.constructor as typeof BXDropdown).selectorItem), item => {
(item as BXDropdownItem).highlighted = false;
});
}
/**
* Navigate through dropdown items.
* @param direction `-1` to navigate backward, `1` to navigate forward.
*/
protected _navigate(direction: number) {
const constructor = this.constructor as typeof BXDropdown;
const items = this.querySelectorAll(constructor.selectorItem);
const highlightedItem = this.querySelector(constructor.selectorItemHighlighted);
const highlightedIndex = indexOf(items, highlightedItem!);
let nextIndex = highlightedIndex + direction;
if (nextIndex < 0) {
nextIndex = items.length - 1;
}
if (nextIndex >= items.length) {
nextIndex = 0;
}
forEach(items, (item, i) => {
(item as BXDropdownItem).highlighted = i === nextIndex;
});
const nextItem = items[nextIndex];
// Using `{ block: 'nearest' }` to prevent scrolling unless scrolling is absolutely necessary.
// `scrollIntoViewOptions` seems to work in latest Safari despite of MDN/caniuse table.
// IE falls back to the old behavior.
nextItem.scrollIntoView({ block: 'nearest' });
const nextItemText = nextItem.textContent;
if (nextItemText) {
this._assistiveStatusText = nextItemText;
}
this.requestUpdate();
}
/* eslint-disable class-methods-use-this */
/**
* @returns The content preceding the trigger button.
*/
protected _renderPrecedingTriggerContent(): TemplateResult | void {
return undefined;
}
/* eslint-enable class-methods-use-this */
/**
* @returns The main content of the trigger button.
*/
protected _renderTriggerContent(): TemplateResult {
const { triggerContent, _selectedItemContent: selectedItemContent } = this;
return html` <span id="trigger-label" class="${prefix}--list-box__label">${selectedItemContent || triggerContent}</span> `;
}
/* eslint-disable class-methods-use-this */
/**
* @returns The content following the trigger button.
*/
protected _renderFollowingTriggerContent(): TemplateResult | void {
return undefined;
}
/* eslint-enable class-methods-use-this */
/**
* Handles event to include selected value on the parent form.
* @param event The event.
*/
_handleFormdata(event: Event) {
const { formData } = event as any; // TODO: Wait for `FormDataEvent` being available in `lib.dom.d.ts`
const { disabled, name, value } = this;
if (!disabled) {
formData.append(name, value);
}
}
/**
* The color scheme.
*/
@property({ attribute: 'color-scheme', reflect: true })
colorScheme = DROPDOWN_COLOR_SCHEME.REGULAR;
/**
* `true` if this dropdown should be disabled.
*/
@property({ type: Boolean, reflect: true })
disabled = false;
/**
* The helper text.
*/
@property({ attribute: 'helper-text' })
helperText = '';
/**
* `true` to show the UI of the invalid state.
*/
@property({ type: Boolean, reflect: true })
invalid = false;
/**
* The label text.
*/
@property({ attribute: 'label-text' })
labelText = '';
/**
* Name for the dropdown in the `FormData`
*/
@property()
name = '';
/**
* `true` if this dropdown should be open.
*/
@property({ type: Boolean, reflect: true })
open = false;
/**
* `true` if the value is required.
*/
@property({ type: Boolean, reflect: true })
required = false;
/**
* The special validity message for `required`.
*/
@property({ attribute: 'required-validity-message' })
requiredValidityMessage = 'Please fill out this field.';
/**
* An assistive text for screen reader to announce, telling the open state.
*/
@property({ attribute: 'selecting-items-assistive-text' })
selectingItemsAssistiveText = 'Selecting items. Use up and down arrow keys to navigate.';
/**
* An assistive text for screen reader to announce, telling that an item is selected.
*/
@property({ attribute: 'selected-item-assistive-text' })
selectedItemAssistiveText = 'Selected an item.';
/**
* Dropdown size.
*/
@property({ reflect: true })
size = DROPDOWN_SIZE.REGULAR;
/**
* The `aria-label` attribute for the UI indicating the closed state.
*/
@property({ attribute: 'toggle-label-closed' })
toggleLabelClosed = '';
/**
* The `aria-label` attribute for the UI indicating the open state.
*/
@property({ attribute: 'toggle-label-open' })
toggleLabelOpen = '';
/**
* The content of the trigger button.
*/
@property({ attribute: 'trigger-content' })
triggerContent = '';
/**
* `true` if this dropdown should use the inline UI variant.
*/
@property({ reflect: true })
type = DROPDOWN_TYPE.REGULAR;
/**
* The validity message.
*/
@property({ attribute: 'validity-message' })
validityMessage = '';
/**
* The value of the selected item.
*/
@property({ reflect: true })
value = '';
createRenderRoot() {
return this.attachShadow({
mode: 'open',
delegatesFocus: Number((/Safari\/(\d+)/.exec(navigator.userAgent) ?? ['', 0])[1]) <= 537,
});
}
shouldUpdate(changedProperties) {
const { selectorItem } = this.constructor as typeof BXDropdown;
if (changedProperties.has('size')) {
forEach(this.querySelectorAll(selectorItem), elem => {
(elem as BXDropdownItem).size = this.size;
});
}
if (changedProperties.has('value')) {
// `<bx-multi-select>` updates selection beforehand
// because our rendering logic for `<bx-multi-select>` looks for selected items via `qSA()`
forEach(this.querySelectorAll(selectorItem), elem => {
(elem as BXDropdownItem).selected = (elem as BXDropdownItem).value === this.value;
});
const item = find(this.querySelectorAll(selectorItem), elem => (elem as BXDropdownItem).value === this.value);
if (item) {
const range = this.ownerDocument!.createRange();
range.selectNodeContents(item);
this._selectedItemContent = range.cloneContents();
} else {
this._selectedItemContent = null;
}
}
return true;
}
updated(changedProperties) {
const { helperText, type } = this;
const inline = type === DROPDOWN_TYPE.INLINE;
const { selectorItem } = this.constructor as typeof BXDropdown;
if (changedProperties.has('disabled')) {
const { disabled } = this;
// Propagate `disabled` attribute to descendants until `:host-context()` gets supported in all major browsers
forEach(this.querySelectorAll(selectorItem), elem => {
(elem as BXDropdownItem).disabled = disabled;
});
}
if ((changedProperties.has('helperText') || changedProperties.has('type')) && helperText && inline) {
// eslint-disable-next-line no-console
console.warn('Found `helperText` property/attribute usage in inline mode, that is not supported, at:', this);
}
}
render() {
const {
colorScheme,
disabled,
helperText,
invalid,
labelText,
open,
toggleLabelClosed,
toggleLabelOpen,
size,
type,
validityMessage,
_assistiveStatusText: assistiveStatusText,
_shouldTriggerBeFocusable: shouldTriggerBeFocusable,
_handleClickInner: handleClickInner,
_handleKeydownInner: handleKeydownInner,
_handleKeypressInner: handleKeypressInner,
_handleSlotchangeHelperText: handleSlotchangeHelperText,
_handleSlotchangeLabelText: handleSlotchangeLabelText,
_slotHelperTextNode: slotHelperTextNode,
_slotLabelTextNode: slotLabelTextNode,
} = this;
const inline = type === DROPDOWN_TYPE.INLINE;
const selectedItemsCount = this.querySelectorAll((this.constructor as typeof BXDropdown).selectorItemSelected).length;
const classes = classMap({
[`${prefix}--dropdown`]: true,
[`${prefix}--list-box`]: true,
[`${prefix}--list-box--${colorScheme}`]: colorScheme,
[`${prefix}--list-box--disabled`]: disabled,
[`${prefix}--list-box--inline`]: inline,
[`${prefix}--list-box--expanded`]: open,
[`${prefix}--list-box--${size}`]: size,
[`${prefix}--dropdown--invalid`]: invalid,
[`${prefix}--dropdown--inline`]: inline,
[`${prefix}--dropdown--selected`]: selectedItemsCount > 0,
});
const labelClasses = classMap({
[`${prefix}--label`]: true,
[`${prefix}--label--disabled`]: disabled,
});
const helperClasses = classMap({
[`${prefix}--form__helper-text`]: true,
[`${prefix}--form__helper-text--disabled`]: disabled,
});
const iconContainerClasses = classMap({
[`${prefix}--list-box__menu-icon`]: true,
[`${prefix}--list-box__menu-icon--open`]: open,
});
const toggleLabel = (open ? toggleLabelOpen : toggleLabelClosed) || undefined;
const hasHelperText = helperText || (slotHelperTextNode && slotHelperTextNode.assignedNodes().length > 0);
const hasLabelText = labelText || (slotLabelTextNode && slotLabelTextNode.assignedNodes().length > 0);
const helper = !invalid
? html`
<div part="helper-text" class="${helperClasses}" ?hidden="${inline || !hasHelperText}">
<slot name="helper-text" @slotchange="${handleSlotchangeHelperText}">${helperText}</slot>
</div>
`
: html`
<div part="validity-message" class=${`${prefix}--form-requirement`}>
<slot name="validity-message">${validityMessage}</slot>
</div>
`;
const validityIcon = !invalid
? undefined
: WarningFilled16({ class: `${prefix}--list-box__invalid-icon`, 'aria-label': toggleLabel });
const menuBody = !open
? undefined
: html`
<div id="menu-body" part="menu-body" class="${prefix}--list-box__menu" role="listbox" tabindex="-1">
<slot></slot>
</div>
`;
return html`
<label part="label-text" class="${labelClasses}" ?hidden="${!hasLabelText}">
<slot name="label-text" @slotchange="${handleSlotchangeLabelText}">${labelText}</slot>
</label>
<div
role="listbox"
class="${classes}"
?data-invalid=${invalid}
@click=${handleClickInner}
@keydown=${handleKeydownInner}
@keypress=${handleKeypressInner}>
${validityIcon}
<div
part="trigger-button"
role="${ifDefined(!shouldTriggerBeFocusable ? undefined : 'button')}"
class="${prefix}--list-box__field"
tabindex="${ifDefined(!shouldTriggerBeFocusable ? undefined : '0')}"
aria-labelledby="trigger-label"
aria-expanded="${String(open)}"
aria-haspopup="listbox"
aria-owns="menu-body"
aria-controls="menu-body">
${this._renderPrecedingTriggerContent()}${this._renderTriggerContent()}${this._renderFollowingTriggerContent()}
<div class="${iconContainerClasses}">${ChevronDown16({ 'aria-label': toggleLabel })}</div>
</div>
${menuBody}
</div>
${helper}
<div class="${prefix}--assistive-text" role="status" aria-live="assertive" aria-relevant="additions text">
${assistiveStatusText}
</div>
`;
}
/**
* Symbols of keys that triggers opening/closing menu and selecting/deselecting menu item.
*/
static TRIGGER_KEYS = new Set([' ', 'Enter']);
/**
* A selector that will return highlighted items.
*/
static get selectorItemHighlighted() {
return `${prefix}-dropdown-item[highlighted]`;
}
/**
* A selector that will return dropdown items.
*/
static get selectorItem() {
return `${prefix}-dropdown-item`;
}
/**
* A selector that will return selected items.
*/
static get selectorItemSelected() {
return `${prefix}-dropdown-item[selected]`;
}
/**
* The name of the custom event fired before a dropdown item is selected upon a user gesture.
* Cancellation of this event stops changing the user-initiated selection.
*/
static get eventBeforeSelect() {
return `${prefix}-dropdown-beingselected`;
}
/**
* The name of the custom event fired after a a dropdown item is selected upon a user gesture.
*/
static get eventSelect() {
return `${prefix}-dropdown-selected`;
}
/**
* The name of the custom event fired before this dropdown item is being toggled upon a user gesture.
* Cancellation of this event stops the user-initiated action of toggling this dropdown item.
*/
static get eventBeforeToggle() {
return `${prefix}-dropdown-beingtoggled`;
}
/**
* The name of the custom event fired after this dropdown item is toggled upon a user gesture.
*/
static get eventToggle() {
return `${prefix}-dropdown-toggled`;
}
static styles = styles;
/**
* @returns A action for dropdown for the given key symbol.
*/
static getAction(key: string) {
if (key === 'Escape') {
return DROPDOWN_KEYBOARD_ACTION.CLOSING;
}
if (key in NAVIGATION_DIRECTION) {
return DROPDOWN_KEYBOARD_ACTION.NAVIGATING;
}
if (this.TRIGGER_KEYS.has(key)) {
return DROPDOWN_KEYBOARD_ACTION.TRIGGERING;
}
return DROPDOWN_KEYBOARD_ACTION.NONE;
}
}
export default BXDropdown; | the_stack |
const DEFAULT_DENO_VERSION = 'v1.14.3';
import fs from 'fs';
import yn from 'yn';
import { dirname, join, relative, resolve } from 'path';
import { tmpdir } from 'os';
import { spawn } from 'child_process';
import { Readable } from 'stream';
import once from '@tootallnate/once';
import {
BuildOptions,
Config,
Files,
FileBlob,
FileFsRef,
StartDevServerOptions,
StartDevServerResult,
createLambda,
download,
glob,
shouldServe,
} from '@vercel/build-utils';
import * as shebang from './shebang';
import { isURL } from './util';
import { bashShellQuote } from 'shell-args';
import { AbortController, AbortSignal } from 'abort-controller';
const { stat, readdir, readFile, writeFile, unlink } = fs.promises;
type Env = typeof process.env;
interface Graph {
deps: string[];
version_hash: string;
}
interface FileInfo {
version: string;
signature: string;
affectsGlobalScope: boolean;
}
interface Program {
fileNames?: string[];
fileInfos: { [name: string]: FileInfo };
referencedMap: { [name: string]: string[] };
exportedModulesMap: { [name: string]: string[] };
semanticDiagnosticsPerFile?: string[];
}
interface BuildInfo {
program: Program;
version: string;
}
const TMP = tmpdir();
// `chmod()` is required for usage with `vercel-dev-runtime` since
// file mode is not preserved in Vercel deployments from the CLI.
fs.chmodSync(join(__dirname, 'build.sh'), 0o755);
fs.chmodSync(join(__dirname, 'bootstrap'), 0o755);
function configBool(
config: Config,
configName: string,
env: Env,
envName: string
): boolean | undefined {
const configVal = config[configName];
if (typeof configVal === 'boolean') {
return configVal;
}
if (typeof configVal === 'string' || typeof configVal === 'number') {
const d = yn(configVal);
if (typeof d === 'boolean') {
return d;
}
}
const envVal = env[envName];
if (typeof envVal === 'string') {
const d = yn(envVal);
if (typeof d === 'boolean') {
return d;
}
}
}
function configString(
config: Config,
configName: string,
env: Env,
envName: string
): string | undefined {
const configVal = config[configName];
if (typeof configVal === 'string') {
return configVal;
}
const envVal = env[envName];
if (typeof envVal === 'string') {
return envVal;
}
}
export const version = 3;
export { shouldServe };
export async function build({
workPath,
files,
entrypoint,
meta = {},
config = {},
}: BuildOptions) {
//const { devCacheDir = join(workPath, '.vercel', 'cache') } = meta;
//const distPath = join(devCacheDir, 'deno', entrypoint);
await download(files, workPath, meta);
const absEntrypoint = join(workPath, entrypoint);
const absEntrypointDir = dirname(absEntrypoint);
const args = shebang.parse(
await fs.promises.readFile(absEntrypoint, 'utf8')
);
const debug = configBool(config, 'debug', process.env, 'DEBUG') || false;
// @deprecated
const unstable =
configBool(config, 'denoUnstable', process.env, 'DENO_UNSTABLE') ||
false;
// @deprecated
const denoTsConfig = configString(
config,
'tsconfig',
process.env,
'DENO_TSCONFIG'
);
let denoVersion = args['--version'];
delete args['--version'];
// @deprecated
if (!denoVersion) {
denoVersion = configString(
config,
'denoVersion',
process.env,
'DENO_VERSION'
);
if (denoVersion) {
console.log('DENO_VERSION env var is deprecated');
}
}
if (denoVersion && !denoVersion.startsWith('v')) {
denoVersion = `v${denoVersion}`;
}
const env: Env = {
...process.env,
...args.env,
BUILDER: __dirname,
ENTRYPOINT: entrypoint,
DENO_VERSION: denoVersion || DEFAULT_DENO_VERSION,
};
if (debug) {
env.DEBUG = '1';
}
// @deprecated
if (unstable) {
console.log('DENO_UNSTABLE env var is deprecated');
args['--unstable'] = true;
}
// Flags that accept file paths are relative to the entrypoint in
// the source file, but `deno run` is executed at the root directory
// of the project, so the arguments need to be relativized to the root
for (const flag of [
'--cert',
'--config',
'--import-map',
'--lock',
] as const) {
const val = args[flag];
if (typeof val === 'string' && !isURL(val)) {
args[flag] = relative(workPath, resolve(absEntrypointDir, val));
}
}
// @deprecated
if (denoTsConfig && !args['--config']) {
console.log('DENO_TSCONFIG env var is deprecated');
args['--config'] = denoTsConfig;
}
// This flag is specific to `vercel-deno`, so it does not
// get included in the args that are passed to `deno run`
const includeFiles = (args['--include-files'] || []).map((f) => {
return relative(workPath, join(absEntrypointDir, f));
});
delete args['--include-files'];
const argv = ['--allow-all', ...args];
const builderPath = join(__dirname, 'build.sh');
const cp = spawn(builderPath, argv, {
env,
cwd: workPath,
stdio: 'inherit',
});
const [code] = await once(cp, 'exit');
if (code !== 0) {
throw new Error(`Build script failed with exit code ${code}`);
}
const sourceFiles = new Set<string>();
sourceFiles.add(entrypoint);
// Patch the `.graph` files to use file paths beginning with `/var/task`
// to hot-fix a Deno issue (https://github.com/denoland/deno/issues/6080).
const workPathUri = `file://${workPath}`;
const genFileDir = join(workPath, '.deno/gen/file');
for await (const file of getFilesWithExtension(genFileDir, '.graph')) {
let needsWrite = false;
const graph: Graph = JSON.parse(await readFile(file, 'utf8'));
for (let i = 0; i < graph.deps.length; i++) {
const dep = graph.deps[i];
if (typeof dep === 'string' && dep.startsWith(workPathUri)) {
const relative = dep.substring(workPathUri.length + 1);
const updated = `file:///var/task/${relative}`;
graph.deps[i] = updated;
sourceFiles.add(relative);
needsWrite = true;
}
}
if (needsWrite) {
console.log('Patched %j', file);
await writeFile(file, JSON.stringify(graph, null, 2));
}
}
for await (const file of getFilesWithExtension(genFileDir, '.buildinfo')) {
let needsWrite = false;
const buildInfo: BuildInfo = JSON.parse(await readFile(file, 'utf8'));
const {
fileNames = [],
fileInfos,
referencedMap,
exportedModulesMap,
semanticDiagnosticsPerFile = [],
} = buildInfo.program;
for (const filename of Object.keys(fileInfos)) {
if (
typeof filename === 'string' &&
filename.startsWith(workPathUri)
) {
const relative = filename.substring(workPathUri.length + 1);
const updated = `file:///var/task/${relative}`;
fileInfos[updated] = fileInfos[filename];
delete fileInfos[filename];
sourceFiles.add(relative);
needsWrite = true;
}
}
for (const [filename, refs] of Object.entries(referencedMap)) {
for (let i = 0; i < refs.length; i++) {
const ref = refs[i];
if (typeof ref === 'string' && ref.startsWith(workPathUri)) {
const relative = ref.substring(workPathUri.length + 1);
const updated = `file:///var/task/${relative}`;
refs[i] = updated;
sourceFiles.add(relative);
needsWrite = true;
}
}
if (
typeof filename === 'string' &&
filename.startsWith(workPathUri)
) {
const relative = filename.substring(workPathUri.length + 1);
const updated = `file:///var/task/${relative}`;
referencedMap[updated] = refs;
delete referencedMap[filename];
sourceFiles.add(relative);
needsWrite = true;
}
}
for (const [filename, refs] of Object.entries(exportedModulesMap)) {
for (let i = 0; i < refs.length; i++) {
const ref = refs[i];
if (typeof ref === 'string' && ref.startsWith(workPathUri)) {
const relative = ref.substring(workPathUri.length + 1);
const updated = `file:///var/task/${relative}`;
refs[i] = updated;
sourceFiles.add(relative);
needsWrite = true;
}
}
if (
typeof filename === 'string' &&
filename.startsWith(workPathUri)
) {
const relative = filename.substring(workPathUri.length + 1);
const updated = `file:///var/task/${relative}`;
exportedModulesMap[updated] = refs;
delete exportedModulesMap[filename];
sourceFiles.add(relative);
needsWrite = true;
}
}
for (let i = 0; i < fileNames.length; i++) {
const ref = fileNames[i];
if (typeof ref === 'string' && ref.startsWith(workPathUri)) {
const relative = ref.substring(workPathUri.length + 1);
const updated = `file:///var/task/${relative}`;
fileNames[i] = updated;
sourceFiles.add(relative);
needsWrite = true;
}
}
for (let i = 0; i < semanticDiagnosticsPerFile.length; i++) {
const ref = semanticDiagnosticsPerFile[i];
if (typeof ref === 'string' && ref.startsWith(workPathUri)) {
const relative = ref.substring(workPathUri.length + 1);
const updated = `file:///var/task/${relative}`;
semanticDiagnosticsPerFile[i] = updated;
sourceFiles.add(relative);
needsWrite = true;
}
}
if (needsWrite) {
console.log('Patched %j', file);
await writeFile(file, JSON.stringify(buildInfo, null, 2));
}
}
const bootstrapData = (
await readFile(join(workPath, 'bootstrap'), 'utf8')
).replace('$args', bashShellQuote(argv));
const outputFiles: Files = {
bootstrap: new FileBlob({
data: bootstrapData,
mode: fs.statSync(join(workPath, 'bootstrap')).mode,
}),
...(await glob('.deno/**/*', workPath)),
};
for (const flag of [
'--cert',
'--config',
'--import-map',
'--lock',
] as const) {
const val = args[flag];
if (typeof val === 'string' && !isURL(val)) {
sourceFiles.add(val);
}
}
console.log('Detected source files:');
for (const filename of Array.from(sourceFiles).sort()) {
console.log(` - ${filename}`);
outputFiles[filename] = await FileFsRef.fromFsPath({
fsPath: join(workPath, filename),
});
}
if (config.includeFiles) {
if (typeof config.includeFiles === 'string') {
includeFiles.push(config.includeFiles);
} else {
includeFiles.push(...config.includeFiles);
}
}
if (includeFiles.length > 0) {
console.log('Including additional files:');
for (const pattern of includeFiles) {
const matches = await glob(pattern, workPath);
for (const name of Object.keys(matches)) {
if (!outputFiles[name]) {
console.log(` - ${name}`);
outputFiles[name] = matches[name];
}
}
}
}
const output = await createLambda({
files: outputFiles,
handler: entrypoint,
runtime: 'provided.al2',
environment: args.env,
});
return { output };
}
async function* getFilesWithExtension(
dir: string,
ext: string
): AsyncIterable<string> {
const files = await readdir(dir);
for (const file of files) {
const absolutePath = join(dir, file);
if (file.endsWith(ext)) {
yield absolutePath;
} else {
const s = await stat(absolutePath);
if (s.isDirectory()) {
yield* getFilesWithExtension(absolutePath, ext);
}
}
}
}
interface PortInfo {
port: number;
}
function isPortInfo(v: any): v is PortInfo {
return v && typeof v.port === 'number';
}
function isReadable(v: any): v is Readable {
return v && v.readable === true;
}
export async function startDevServer({
entrypoint,
workPath,
config,
meta = {},
}: StartDevServerOptions): Promise<StartDevServerResult> {
// @deprecated
const unstable =
configBool(
config,
'denoUnstable',
meta.buildEnv || {},
'DENO_UNSTABLE'
) || false;
// @deprecated
const denoTsConfig = configString(
config,
'tsconfig',
meta.buildEnv || {},
'DENO_TSCONFIG'
);
const portFile = join(
TMP,
`vercel-deno-port-${Math.random().toString(32).substring(2)}`
);
const absEntrypoint = join(workPath, entrypoint);
const absEntrypointDir = dirname(absEntrypoint);
const env: Env = {
...process.env,
...meta.env,
VERCEL_DEV_ENTRYPOINT: absEntrypoint,
VERCEL_DEV_PORT_FILE: portFile,
};
const args = await shebang.parse(absEntrypoint);
// @deprecated
if (unstable) {
console.log('DENO_UNSTABLE env var is deprecated');
args['--unstable'] = true;
}
// Flags that accept file paths are relative to the entrypoint in
// the source file, but `deno run` is executed at the root directory
// of the project, so the arguments need to be relativized to the root
for (const flag of [
'--cert',
'--config',
'--import-map',
'--lock',
] as const) {
const val = args[flag];
if (typeof val === 'string' && !isURL(val)) {
args[flag] = relative(workPath, resolve(absEntrypointDir, val));
}
}
// @deprecated
if (denoTsConfig && !args['--config']) {
console.log('DENO_TSCONFIG env var is deprecated');
args['--config'] = denoTsConfig;
}
const argv = [
'run',
'--allow-all',
...args,
join(__dirname, 'dev-server.ts'),
];
const child = spawn('deno', argv, {
cwd: workPath,
env,
stdio: ['ignore', 'inherit', 'inherit', 'pipe'],
});
const portPipe = child.stdio[3];
if (!isReadable(portPipe)) {
throw new Error('Not readable');
}
const controller = new AbortController();
const { signal } = controller;
const onPort = new Promise<PortInfo>((resolve) => {
portPipe.setEncoding('utf8');
portPipe.once('data', (d) => {
resolve({ port: Number(d) });
});
});
const onPortFile = waitForPortFile({ portFile, signal });
const onExit = once(child, 'exit', { signal });
try {
const result = await Promise.race([onPort, onPortFile, onExit]);
if (isPortInfo(result)) {
return {
port: result.port,
pid: child.pid,
};
} else if (Array.isArray(result)) {
// Got "exit" event from child process
throw new Error(
`Failed to start dev server for "${entrypoint}" (code=${result[0]}, signal=${result[1]})`
);
} else {
throw new Error('Unexpected error');
}
} finally {
controller.abort();
}
}
async function waitForPortFile(opts: {
portFile: string;
signal: AbortSignal;
}): Promise<PortInfo | void> {
while (!opts.signal.aborted) {
await new Promise((resolve) => setTimeout(resolve, 100));
try {
const port = Number(await readFile(opts.portFile, 'ascii'));
unlink(opts.portFile).catch((_) => {
console.error('Could not delete port file: %j', opts.portFile);
});
return { port };
} catch (err: any) {
if (err.code !== 'ENOENT') {
throw err;
}
}
}
} | the_stack |
import {
EdgeMaterial,
ExtrusionFeatureDefs,
FadingFeature,
MixinShaderProperties,
UniformsType
} from "@here/harp-materials";
import { chainCallbacks } from "@here/harp-utils";
import * as THREE from "three";
import { DepthPrePassProperties } from "../DepthPrePass";
const vertexShaderChunk = `
#ifdef USE_EXTRUSION
#ifndef HAS_EXTRUSION_PARS_VERTEX
#include <extrusion_pars_vertex>
#endif
#endif
#ifdef USE_FADING
#include <fading_pars_vertex>
#endif
uniform float outlineThickness;
vec4 calculateOutline( vec4 pos, vec3 objectNormal, vec4 skinned ) {
float thickness = outlineThickness;
const float ratio = 1.0;
vec4 pos2 = projectionMatrix * modelViewMatrix * vec4( skinned.xyz + objectNormal, 1.0 );
vec4 norm = normalize( pos - pos2 );
return pos + norm * thickness * pos.w * ratio;
}`;
const vertexShaderChunk2 = `
#if ! defined( LAMBERT ) && ! defined( PHONG ) && ! defined( TOON ) && ! defined( STANDARD )
#ifndef USE_ENVMAP
vec3 objectNormal = normalize( normal );
#endif
#endif
#ifdef FLIP_SIDED
objectNormal = -objectNormal;
#endif
#ifdef DECLARE_TRANSFORMED
vec3 transformed = vec3( position );
#endif
#ifdef USE_EXTRUSION
#ifndef HAS_EXTRUSION_VERTEX
#include <extrusion_vertex>
#endif
#endif
#ifdef USE_FADING
#include <fading_vertex>
#endif
#ifdef USE_EXTRUSION
gl_Position = calculateOutline( projectionMatrix * modelViewMatrix * vec4( transformed, 1.0 ),
objectNormal, vec4( transformed, 1.0 ) );
#else
gl_Position = calculateOutline( gl_Position, objectNormal, vec4( transformed, 1.0 ) );
#endif
#include <fog_vertex>`;
const fragmentShader = `
#include <common>
#include <fog_pars_fragment>
#ifdef USE_EXTRUSION
#include <extrusion_pars_fragment>
#endif
#ifdef USE_FADING
#include <fading_pars_fragment>
#endif
uniform vec3 outlineColor;
uniform float outlineAlpha;
void main() {
gl_FragColor = vec4( outlineColor, outlineAlpha );
#include <fog_fragment>
#ifdef USE_EXTRUSION
#include <extrusion_fragment>
#endif
#ifdef USE_FADING
#include <fading_fragment>
#endif
}`;
/**
* Effect to render bold lines around extruded polygons.
*
* Implemented by rendering the mesh geometries with an outline material before rendering them
* again with their original.
*/
export class OutlineEffect {
enabled: boolean = true;
autoClear: boolean;
domElement: HTMLCanvasElement;
shadowMap: THREE.WebGLShadowMap;
private m_defaultThickness: number = 0.02;
private readonly m_defaultColor: THREE.Color = new THREE.Color(0, 0, 0);
private readonly m_defaultAlpha: number = 1;
private readonly m_defaultKeepAlive: boolean = false;
private m_ghostExtrudedPolygons: boolean = false;
private m_cache: any = {};
private readonly m_removeThresholdCount: number = 60;
private m_originalMaterials: any = {};
private m_originalOnBeforeRenders: any = {};
private readonly m_shaderIDs: { [key: string]: string } = {
MeshBasicMaterial: "basic",
MeshLambertMaterial: "lambert",
MeshPhongMaterial: "phong",
MeshToonMaterial: "phong",
MeshStandardMaterial: "physical",
MeshPhysicalMaterial: "physical"
};
private readonly m_uniformsChunk = {
outlineThickness: { value: this.m_defaultThickness },
outlineColor: { value: this.m_defaultColor },
outlineAlpha: { value: this.m_defaultAlpha }
};
constructor(private m_renderer: THREE.WebGLRenderer) {
this.autoClear = m_renderer.autoClear;
this.domElement = m_renderer.domElement;
this.shadowMap = m_renderer.shadowMap;
}
set thickness(thickness: number) {
this.m_defaultThickness = thickness;
this.m_uniformsChunk.outlineThickness.value = thickness;
this.m_cache = {};
}
set color(color: string) {
this.m_defaultColor.set(color);
this.m_cache = {};
}
set ghostExtrudedPolygons(ghost: boolean) {
this.m_ghostExtrudedPolygons = ghost;
}
clear(color: boolean, depth: boolean, stencil: boolean) {
this.m_renderer.clear(color, depth, stencil);
}
getPixelRatio() {
return this.m_renderer.getPixelRatio();
}
setPixelRatio(value: number) {
this.m_renderer.setPixelRatio(value);
}
getSize(target: THREE.Vector2) {
return this.m_renderer.getSize(target);
}
setSize(width: number, height: number, updateStyle: boolean) {
this.m_renderer.setSize(width, height, updateStyle);
}
setViewport(x: number, y: number, width: number, height: number) {
this.m_renderer.setViewport(x, y, width, height);
}
setScissor(x: number, y: number, width: number, height: number) {
this.m_renderer.setScissor(x, y, width, height);
}
setScissorTest(boolean: boolean) {
this.m_renderer.setScissorTest(boolean);
}
setRenderTarget(renderTarget: THREE.WebGLRenderTarget) {
this.m_renderer.setRenderTarget(renderTarget);
}
render(scene: THREE.Scene, camera: THREE.Camera) {
// Re-rendering the scene with the outline effect enables to hide the
// extruded polygons and show only the outlines (it is a hack and should be
// implemented another way!).
if (this.m_ghostExtrudedPolygons) {
if (!this.enabled) {
this.m_renderer.render(scene, camera);
return;
}
const currentAutoClear = this.m_renderer.autoClear;
this.m_renderer.autoClear = this.autoClear;
this.m_renderer.render(scene, camera);
this.m_renderer.autoClear = currentAutoClear;
}
this.renderOutline(scene, camera);
}
renderOutline(scene: THREE.Scene, camera: THREE.Camera) {
const currentAutoClear = this.m_renderer.autoClear;
const currentSceneAutoUpdate = scene.autoUpdate;
const currentSceneBackground = scene.background;
const currentShadowMapEnabled = this.m_renderer.shadowMap.enabled;
scene.autoUpdate = false;
scene.background = null;
this.m_renderer.autoClear = false;
this.m_renderer.shadowMap.enabled = false;
scene.traverse(this.setOutlineMaterial.bind(this));
this.m_renderer.render(scene, camera);
scene.traverse(this.restoreOriginalMaterial.bind(this));
this.cleanupCache();
scene.autoUpdate = currentSceneAutoUpdate;
scene.background = currentSceneBackground;
this.m_renderer.autoClear = currentAutoClear;
this.m_renderer.shadowMap.enabled = currentShadowMapEnabled;
}
private createInvisibleMaterial() {
return new THREE.ShaderMaterial({ name: "invisible", visible: false });
}
private createMaterial(originalMaterial: THREE.Material) {
// EdgeMaterial or depth prepass material should not be used for outlines.
if (
originalMaterial instanceof EdgeMaterial ||
(originalMaterial as DepthPrePassProperties).isDepthPrepassMaterial === true
) {
return this.createInvisibleMaterial();
}
const shaderID = this.m_shaderIDs[originalMaterial.type];
let originalVertexShader;
let originalUniforms: UniformsType | undefined =
(originalMaterial as MixinShaderProperties).shaderUniforms !== undefined
? (originalMaterial as MixinShaderProperties).shaderUniforms
: (originalMaterial as THREE.ShaderMaterial).uniforms;
if (shaderID !== undefined) {
const shader = THREE.ShaderLib[shaderID];
originalUniforms = shader.uniforms;
originalVertexShader = shader.vertexShader;
} else if ((originalMaterial as any).isRawShaderMaterial === true) {
originalVertexShader = (originalMaterial as any).vertexShader;
if (
!/attribute\s+vec3\s+position\s*;/.test(originalVertexShader) ||
!/attribute\s+vec3\s+normal\s*;/.test(originalVertexShader)
) {
return this.createInvisibleMaterial();
}
} else if ((originalMaterial as any).isShaderMaterial === true) {
originalVertexShader = (originalMaterial as any).vertexShader;
} else {
return this.createInvisibleMaterial();
}
const isExtrusionMaterial =
(originalMaterial as MixinShaderProperties).shaderUniforms !== undefined &&
(originalMaterial as any).shaderUniforms.extrusionRatio !== undefined;
const isFadingMaterial = FadingFeature.isDefined(originalMaterial as FadingFeature);
const uniforms: UniformsType = { ...originalUniforms, ...this.m_uniformsChunk };
const vertexShader = originalVertexShader
// put vertexShaderChunk right before "void main() {...}"
.replace(/void\s+main\s*\(\s*\)/, vertexShaderChunk + "\nvoid main()")
// put vertexShaderChunk2 the end of "void main() {...}"
// Note: here assums originalVertexShader ends with "}" of "void main() {...}"
.replace(/\}\s*$/, vertexShaderChunk2 + "\n}")
// remove any light related lines
// Note: here is very sensitive to originalVertexShader
// TODO: consider safer way
.replace(/#include\s+<[\w_]*light[\w_]*>/g, "");
const defines: any = {};
if (
!/vec3\s+transformed\s*=/.test(originalVertexShader) &&
!/#include\s+<begin_vertex>/.test(originalVertexShader)
) {
(defines as any).DECLARE_TRANSFORMED = true;
}
if (isExtrusionMaterial) {
// If the original material is setup for animated extrusion (like buildings), add the
// uniform describing the extrusion to the outline material.
uniforms.extrusionRatio = { value: ExtrusionFeatureDefs.DEFAULT_RATIO_MIN };
defines.USE_EXTRUSION = 1;
}
if (isFadingMaterial) {
uniforms.fadeNear = {
value:
originalUniforms!.fadeNear !== undefined
? originalUniforms!.fadeNear.value
: FadingFeature.DEFAULT_FADE_NEAR
};
uniforms.fadeFar = {
value:
originalUniforms!.fadeFar !== undefined
? originalUniforms!.fadeFar.value
: FadingFeature.DEFAULT_FADE_FAR
};
defines.USE_FADING = 1;
}
const outlineMaterial = new THREE.ShaderMaterial({
defines,
uniforms,
vertexShader,
fragmentShader,
side: THREE.BackSide,
morphTargets: false,
morphNormals: false,
fog: false,
blending: THREE.CustomBlending,
blendSrc: THREE.SrcAlphaFactor,
blendDst: THREE.OneMinusSrcAlphaFactor,
blendSrcAlpha: THREE.OneFactor,
blendDstAlpha: THREE.OneMinusSrcAlphaFactor,
transparent: true,
polygonOffset: true,
// Extreme values used here to reduce artifacts, especially at tile borders.
polygonOffsetFactor: 10.0,
polygonOffsetUnits: 30.0
});
return outlineMaterial;
}
private getOutlineMaterialFromCache(originalMaterial: THREE.Material) {
let data = this.m_cache[originalMaterial.uuid];
if (data === undefined) {
data = {
material: this.createMaterial(originalMaterial),
used: true,
keepAlive: this.m_defaultKeepAlive,
count: 0
};
this.m_cache[originalMaterial.uuid] = data;
}
data.used = true;
return data.material;
}
private getOutlineMaterial(originalMaterial: THREE.Material) {
const outlineMaterial = this.getOutlineMaterialFromCache(originalMaterial);
this.m_originalMaterials[outlineMaterial.uuid] = originalMaterial;
this.updateOutlineMaterial(outlineMaterial, originalMaterial);
return outlineMaterial;
}
private setOutlineMaterial(object: THREE.Object3D) {
if ((object as THREE.Mesh).material === undefined) {
return;
}
if (Array.isArray((object as THREE.Mesh).material)) {
for (
let i = 0, il = ((object as THREE.Mesh).material as THREE.Material[]).length;
i < il;
i++
) {
((object as THREE.Mesh).material as THREE.Material[])[i] = this.getOutlineMaterial(
((object as THREE.Mesh).material as THREE.Material[])[i]
);
}
} else {
(object as THREE.Mesh).material = this.getOutlineMaterial(
(object as THREE.Mesh).material as THREE.Material
);
}
this.m_originalOnBeforeRenders[object.uuid] = object.onBeforeRender;
object.onBeforeRender = chainCallbacks(
object.onBeforeRender,
this.onBeforeRender.bind(this)
);
}
private restoreOriginalMaterial(object: THREE.Object3D) {
if ((object as THREE.Mesh).material === undefined) {
return;
}
if (Array.isArray((object as THREE.Mesh).material)) {
for (
let i = 0, il = ((object as THREE.Mesh).material as THREE.Material[]).length;
i < il;
i++
) {
((object as THREE.Mesh).material as THREE.Material[])[i] = this.m_originalMaterials[
((object as THREE.Mesh).material as THREE.Material[])[i].uuid
];
}
} else {
(object as THREE.Mesh).material = this.m_originalMaterials[
((object as THREE.Mesh).material as THREE.Material).uuid
];
}
object.onBeforeRender = this.m_originalOnBeforeRenders[object.uuid];
}
private onBeforeRender(
renderer: THREE.WebGLRenderer,
scene: THREE.Scene,
camera: THREE.Camera,
geometry: THREE.BufferGeometry,
material: THREE.Material,
group: THREE.Group
) {
const originalMaterial = this.m_originalMaterials[material.uuid];
// just in case
if (originalMaterial === undefined) {
return;
}
this.updateUniforms(material, originalMaterial);
}
private updateUniforms(material: THREE.Material, originalMaterial: THREE.Material) {
const outlineParameters = originalMaterial.userData.outlineParameters;
const outlineUniforms = (material as THREE.ShaderMaterial).uniforms;
outlineUniforms.outlineAlpha.value = originalMaterial.opacity;
const originalUniforms =
(originalMaterial as any).shaderUniforms !== undefined
? (originalMaterial as any).shaderUniforms
: (originalMaterial as any).uniforms;
if (outlineParameters !== undefined) {
if (outlineParameters.thickness !== undefined) {
outlineUniforms.outlineThickness.value = outlineParameters.thickness;
}
if (outlineParameters.color !== undefined) {
outlineUniforms.outlineColor.value.fromArray(outlineParameters.color);
}
if (outlineParameters.alpha !== undefined) {
outlineUniforms.outlineAlpha.value = outlineParameters.alpha;
}
}
// If the original material is setup for animated extrusion (like buildings), update the
// uniforms in the outline material.
if (originalUniforms !== undefined && originalUniforms.extrusionRatio !== undefined) {
const value = (originalMaterial as any).shaderUniforms.extrusionRatio.value;
(material as any).extrusionRatio = value;
(material as any).uniforms.extrusionRatio.value =
value !== undefined ? value : ExtrusionFeatureDefs.DEFAULT_RATIO_MIN;
}
// Copy available fading params to the outline material.
if (
material.defines?.USE_FADING !== undefined &&
originalUniforms.fadeNear !== undefined &&
originalUniforms.fadeFar !== undefined &&
originalUniforms.fadeFar.value >= 0.0
) {
outlineUniforms.fadeNear.value = originalUniforms.fadeNear.value;
outlineUniforms.fadeFar.value = originalUniforms.fadeFar.value;
}
}
private updateOutlineMaterial(material: THREE.Material, originalMaterial: THREE.Material) {
if (material.name === "invisible") {
return;
}
const outlineParameters = originalMaterial.userData.outlineParameters;
(material as any).skinning = (originalMaterial as any).skinning;
(material as any).morphTargets = (originalMaterial as any).morphTargets;
(material as any).morphNormals = (originalMaterial as any).morphNormals;
material.fog = originalMaterial.fog;
if (outlineParameters !== undefined) {
material.visible =
originalMaterial.visible === false
? false
: outlineParameters.visible !== undefined
? outlineParameters.visible
: true;
if (outlineParameters.keepAlive !== undefined) {
this.m_cache[originalMaterial.uuid].keepAlive = outlineParameters.keepAlive;
}
} else {
material.visible = originalMaterial.visible;
}
if ((originalMaterial as any).wireframe === true || originalMaterial.depthTest === false) {
material.visible = false;
}
}
private cleanupCache() {
let keys;
// clear originialMaterials
keys = Object.keys(this.m_originalMaterials);
for (let i = 0, il = keys.length; i < il; i++) {
this.m_originalMaterials[keys[i]] = undefined;
}
// clear originalOnBeforeRenders
keys = Object.keys(this.m_originalOnBeforeRenders);
for (let i = 0, il = keys.length; i < il; i++) {
this.m_originalOnBeforeRenders[keys[i]] = undefined;
}
// remove unused outlineMaterial from cache
keys = Object.keys(this.m_cache);
for (const key of keys) {
if (this.m_cache[key].used === false) {
this.m_cache[key].count++;
if (
this.m_cache[key].keepAlive === false &&
this.m_cache[key].count > this.m_removeThresholdCount
) {
delete this.m_cache[key];
}
} else {
this.m_cache[key].used = false;
this.m_cache[key].count = 0;
}
}
}
} | the_stack |
import { defineComponent, h, ref, Ref, computed, Teleport, VNode, onUnmounted, reactive, nextTick, PropType, onMounted } from 'vue'
import XEUtils from 'xe-utils'
import GlobalConfig from '../../v-x-e-table/src/conf'
import { useSize } from '../../hooks/size'
import { getAbsolutePos, getEventTargetNode } from '../../tools/dom'
import { getFuncText, getLastZIndex, nextZIndex } from '../../tools/utils'
import { GlobalEvent } from '../../tools/event'
import { VxeButtonConstructor, VxeButtonPropTypes, VxeButtonEmits, ButtonReactData, ButtonMethods, ButtonPrivateRef, ButtonInternalData } from '../../../types/all'
export default defineComponent({
name: 'VxeButton',
props: {
/**
* 按钮类型
*/
type: String as PropType<VxeButtonPropTypes.Type>,
className: String as PropType<VxeButtonPropTypes.ClassName>,
/**
* 按钮尺寸
*/
size: { type: String as PropType<VxeButtonPropTypes.Size>, default: () => GlobalConfig.button.size || GlobalConfig.size },
/**
* 用来标识这一项
*/
name: [String, Number] as PropType<VxeButtonPropTypes.Name>,
/**
* 按钮内容
*/
content: String as PropType<VxeButtonPropTypes.Content>,
/**
* 固定显示下拉面板的方向
*/
placement: String as PropType<VxeButtonPropTypes.Placement>,
/**
* 按钮状态
*/
status: String as PropType<VxeButtonPropTypes.Status>,
/**
* 按钮的图标
*/
icon: String as PropType<VxeButtonPropTypes.Icon>,
/**
* 圆角边框
*/
round: Boolean as PropType<VxeButtonPropTypes.Round>,
/**
* 圆角按钮
*/
circle: Boolean as PropType<VxeButtonPropTypes.Circle>,
/**
* 是否禁用
*/
disabled: Boolean as PropType<VxeButtonPropTypes.Disabled>,
/**
* 是否加载中
*/
loading: Boolean as PropType<VxeButtonPropTypes.Loading>,
/**
* 在下拉面板关闭时销毁内容
*/
destroyOnClose: Boolean as PropType<VxeButtonPropTypes.DestroyOnClose>,
/**
* 是否将弹框容器插入于 body 内
*/
transfer: { type: Boolean as PropType<VxeButtonPropTypes.Transfer>, default: () => GlobalConfig.button.transfer }
},
emits: [
'click',
'dropdown-click'
] as VxeButtonEmits,
setup (props, context) {
const { slots, emit } = context
const xID = XEUtils.uniqueId()
const computeSize = useSize(props)
const reactData = reactive<ButtonReactData>({
inited: false,
showPanel: false,
animatVisible: false,
panelIndex: 0,
panelStyle: {},
panelPlacement: ''
})
const internalData: ButtonInternalData = {
showTime: null
}
const refElem = ref() as Ref<HTMLDivElement>
const refButton = ref() as Ref<HTMLButtonElement>
const refBtnPanel = ref() as Ref<HTMLDivElement>
const refMaps: ButtonPrivateRef = {
refElem
}
const $xebutton = {
xID,
props,
context,
reactData,
internalData,
getRefMaps: () => refMaps
} as unknown as VxeButtonConstructor
let buttonMethods = {} as ButtonMethods
const computeIsFormBtn = computed(() => {
const { type } = props
if (type) {
return ['submit', 'reset', 'button'].indexOf(type) > -1
}
return false
})
const computeBtnType = computed(() => {
const { type } = props
return type && type === 'text' ? type : 'button'
})
const updateZindex = () => {
if (reactData.panelIndex < getLastZIndex()) {
reactData.panelIndex = nextZIndex()
}
}
const updatePlacement = () => {
return nextTick().then(() => {
const { transfer, placement } = props
const { panelIndex } = reactData
const targetElem = refButton.value
const panelElem = refBtnPanel.value
if (panelElem && targetElem) {
const targetHeight = targetElem.offsetHeight
const targetWidth = targetElem.offsetWidth
const panelHeight = panelElem.offsetHeight
const panelWidth = panelElem.offsetWidth
const marginSize = 5
const panelStyle: { [key: string]: string | number } = {
zIndex: panelIndex
}
const { boundingTop, boundingLeft, visibleHeight, visibleWidth } = getAbsolutePos(targetElem)
let panelPlacement = 'bottom'
if (transfer) {
let left = boundingLeft + targetWidth - panelWidth
let top = boundingTop + targetHeight
if (placement === 'top') {
panelPlacement = 'top'
top = boundingTop - panelHeight
} else if (!placement) {
// 如果下面不够放,则向上
if (top + panelHeight + marginSize > visibleHeight) {
panelPlacement = 'top'
top = boundingTop - panelHeight
}
// 如果上面不够放,则向下(优先)
if (top < marginSize) {
panelPlacement = 'bottom'
top = boundingTop + targetHeight
}
}
// 如果溢出右边
if (left + panelWidth + marginSize > visibleWidth) {
left -= left + panelWidth + marginSize - visibleWidth
}
// 如果溢出左边
if (left < marginSize) {
left = marginSize
}
Object.assign(panelStyle, {
left: `${left}px`,
right: 'auto',
top: `${top}px`,
minWidth: `${targetWidth}px`
})
} else {
if (placement === 'top') {
panelPlacement = 'top'
panelStyle.bottom = `${targetHeight}px`
} else if (!placement) {
// 如果下面不够放,则向上
if (boundingTop + targetHeight + panelHeight > visibleHeight) {
// 如果上面不够放,则向下(优先)
if (boundingTop - targetHeight - panelHeight > marginSize) {
panelPlacement = 'top'
panelStyle.bottom = `${targetHeight}px`
}
}
}
}
reactData.panelStyle = panelStyle
reactData.panelPlacement = panelPlacement
return nextTick()
}
})
}
const clickEvent = (evnt: Event) => {
buttonMethods.dispatchEvent('click', { $event: evnt }, evnt)
}
const mousedownDropdownEvent = (evnt: MouseEvent) => {
const isLeftBtn = evnt.button === 0
if (isLeftBtn) {
evnt.stopPropagation()
}
}
const clickDropdownEvent = (evnt: Event) => {
const dropdownElem = evnt.currentTarget
const panelElem = refBtnPanel.value
const { flag, targetElem } = getEventTargetNode(evnt, dropdownElem, 'vxe-button')
if (flag) {
if (panelElem) {
panelElem.dataset.active = 'N'
}
reactData.showPanel = false
setTimeout(() => {
if (!panelElem || panelElem.dataset.active !== 'Y') {
reactData.animatVisible = false
}
}, 350)
buttonMethods.dispatchEvent('dropdown-click', { name: targetElem.getAttribute('name'), $event: evnt }, evnt)
}
}
const mouseenterEvent = () => {
const panelElem = refBtnPanel.value
if (panelElem) {
panelElem.dataset.active = 'Y'
reactData.animatVisible = true
setTimeout(() => {
if (panelElem.dataset.active === 'Y') {
reactData.showPanel = true
updateZindex()
updatePlacement()
setTimeout(() => {
if (reactData.showPanel) {
updatePlacement()
}
}, 50)
}
}, 20)
}
}
const mouseenterTargetEvent = () => {
const panelElem = refBtnPanel.value
if (panelElem) {
panelElem.dataset.active = 'Y'
if (!reactData.inited) {
reactData.inited = true
}
internalData.showTime = setTimeout(() => {
if (panelElem.dataset.active === 'Y') {
mouseenterEvent()
} else {
reactData.animatVisible = false
}
}, 250)
}
}
const closePanel = () => {
const panelElem = refBtnPanel.value
clearTimeout(internalData.showTime)
if (panelElem) {
panelElem.dataset.active = 'N'
setTimeout(() => {
if (panelElem.dataset.active !== 'Y') {
reactData.showPanel = false
setTimeout(() => {
if (panelElem.dataset.active !== 'Y') {
reactData.animatVisible = false
}
}, 350)
}
}, 100)
} else {
reactData.animatVisible = false
reactData.showPanel = false
}
}
const mouseleaveEvent = () => {
closePanel()
}
const renderContent = () => {
const { content, icon, loading } = props
const contVNs: VNode[] = []
if (loading) {
contVNs.push(
h('i', {
class: ['vxe-button--loading-icon', GlobalConfig.icon.BUTTON_LOADING]
})
)
} else if (icon) {
contVNs.push(
h('i', {
class: ['vxe-button--icon', icon]
})
)
}
if (slots.default) {
contVNs.push(
h('span', {
class: 'vxe-button--content'
}, slots.default({}))
)
} else if (content) {
contVNs.push(
h('span', {
class: 'vxe-button--content'
}, getFuncText(content))
)
}
return contVNs
}
buttonMethods = {
dispatchEvent (type, params, evnt) {
emit(type, Object.assign({ $button: $xebutton, $event: evnt }, params))
},
focus () {
const btnElem = refButton.value
btnElem.focus()
return nextTick()
},
blur () {
const btnElem = refButton.value
btnElem.blur()
return nextTick()
}
}
Object.assign($xebutton, buttonMethods)
onMounted(() => {
GlobalEvent.on($xebutton, 'mousewheel', (evnt: Event) => {
const panelElem = refBtnPanel.value
if (reactData.showPanel && !getEventTargetNode(evnt, panelElem).flag) {
closePanel()
}
})
})
onUnmounted(() => {
GlobalEvent.off($xebutton, 'mousewheel')
})
const renderVN = () => {
const { className, transfer, type, round, circle, destroyOnClose, status, name, disabled, loading } = props
const { inited, showPanel } = reactData
const isFormBtn = computeIsFormBtn.value
const btnType = computeBtnType.value
const vSize = computeSize.value
if (slots.dropdowns) {
return h('div', {
ref: refElem,
class: ['vxe-button--dropdown', className, {
[`size--${vSize}`]: vSize,
'is--active': showPanel
}]
}, [
h('button', {
ref: refButton,
class: ['vxe-button', `type--${btnType}`, {
[`size--${vSize}`]: vSize,
[`theme--${status}`]: status,
'is--round': round,
'is--circle': circle,
'is--disabled': disabled || loading,
'is--loading': loading
}],
name,
type: isFormBtn ? type : 'button',
disabled: disabled || loading,
onMouseenter: mouseenterTargetEvent,
onMouseleave: mouseleaveEvent,
onClick: clickEvent
}, renderContent().concat([
h('i', {
class: `vxe-button--dropdown-arrow ${GlobalConfig.icon.BUTTON_DROPDOWN}`
})
])),
h(Teleport, {
to: 'body',
disabled: transfer ? !inited : true
}, [
h('div', {
ref: refBtnPanel,
class: ['vxe-button--dropdown-panel', {
[`size--${vSize}`]: vSize,
'animat--leave': reactData.animatVisible,
'animat--enter': showPanel
}],
placement: reactData.panelPlacement,
style: reactData.panelStyle
}, inited ? [
h('div', {
class: 'vxe-button--dropdown-wrapper',
onMousedown: mousedownDropdownEvent,
onClick: clickDropdownEvent,
onMouseenter: mouseenterEvent,
onMouseleave: mouseleaveEvent
}, destroyOnClose && !showPanel ? [] : slots.dropdowns({}))
] : [])
])
])
}
return h('button', {
ref: refButton,
class: ['vxe-button', `type--${btnType}`, {
[`size--${vSize}`]: vSize,
[`theme--${status}`]: status,
'is--round': round,
'is--circle': circle,
'is--disabled': disabled || loading,
'is--loading': loading
}],
name,
type: isFormBtn ? type : 'button',
disabled: disabled || loading,
onClick: clickEvent
}, renderContent())
}
$xebutton.renderVN = renderVN
return $xebutton
},
render () {
return this.renderVN()
}
}) | the_stack |
'use strict';
import * as assert from 'assert';
import URI from 'vs/base/common/uri';
import { isMacintosh, isLinux } from 'vs/base/common/platform';
import { OutputLinkComputer } from 'vs/workbench/parts/output/common/outputLinkComputer';
import { TestContextService } from 'vs/workbench/test/workbenchTestServices';
function toOSPath(p: string): string {
if (isMacintosh || isLinux) {
return p.replace(/\\/g, '/');
}
return p;
}
suite('Workbench - OutputWorker', () => {
test('OutputWorker - Link detection', function () {
let patternsSlash = OutputLinkComputer.createPatterns(
URI.file('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala')
);
let patternsBackSlash = OutputLinkComputer.createPatterns(
URI.file('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala')
);
let contextService = new TestContextService();
let line = toOSPath('Foo bar');
let result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 0);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 0);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString());
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 84);
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts in');
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString());
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 84);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336 in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#336');
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 88);
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336 in');
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#336');
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 88);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336:9
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336:9 in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#336,9');
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 90);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#336,9');
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 90);
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336:9 in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#336,9');
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 90);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#336,9');
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 90);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts>dir
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts>dir in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString());
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 84);
// Example: at [C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336:9]
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:336:9] in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#336,9');
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 90);
// Example: at [C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts]
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts] in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString());
// Example: C:\Users\someone\AppData\Local\Temp\_monacodata_9888\workspaces\express\server.js on line 8
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts on line 8');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#8');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 90);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#8');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 90);
// Example: C:\Users\someone\AppData\Local\Temp\_monacodata_9888\workspaces\express\server.js on line 8, column 13
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts on line 8, column 13');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#8,13');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 101);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#8,13');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 101);
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts on LINE 8, COLUMN 13');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#8,13');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 101);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#8,13');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 101);
// Example: C:\Users\someone\AppData\Local\Temp\_monacodata_9888\workspaces\express\server.js:line 8
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts:line 8');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#8');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 87);
// Example: at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts)
line = toOSPath(' at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts)');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString());
assert.equal(result[0].range.startColumn, 15);
assert.equal(result[0].range.endColumn, 94);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString());
assert.equal(result[0].range.startColumn, 15);
assert.equal(result[0].range.endColumn, 94);
// Example: at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts:278)
line = toOSPath(' at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts:278)');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#278');
assert.equal(result[0].range.startColumn, 15);
assert.equal(result[0].range.endColumn, 98);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#278');
assert.equal(result[0].range.startColumn, 15);
assert.equal(result[0].range.endColumn, 98);
// Example: at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts:278:34)
line = toOSPath(' at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts:278:34)');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#278,34');
assert.equal(result[0].range.startColumn, 15);
assert.equal(result[0].range.endColumn, 101);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#278,34');
assert.equal(result[0].range.startColumn, 15);
assert.equal(result[0].range.endColumn, 101);
line = toOSPath(' at File.put (C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Game.ts:278:34)');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#278,34');
assert.equal(result[0].range.startColumn, 15);
assert.equal(result[0].range.endColumn, 101);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString() + '#278,34');
assert.equal(result[0].range.startColumn, 15);
assert.equal(result[0].range.endColumn, 101);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts(45): error
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts(45): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 102);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 102);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts (45,18): error
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts (45): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 103);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 103);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts(45,18): error
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts(45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 105);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 105);
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts(45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 105);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 105);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts (45,18): error
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts (45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 106);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 106);
line = toOSPath('C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/lib/something/Features.ts (45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 106);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 106);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts(45): error
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts(45): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 102);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 102);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts (45,18): error
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts (45): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 103);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 103);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts(45,18): error
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts(45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 105);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 105);
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts(45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 105);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 105);
// Example: C:/Users/someone/AppData/Local/Temp/_monacodata_9888/workspaces/mankala/Features.ts (45,18): error
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts (45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 106);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 106);
line = toOSPath('C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\lib\\something\\Features.ts (45,18): error');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 106);
result = OutputLinkComputer.detectLinks(line, 1, patternsBackSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/lib/something/Features.ts').toString() + '#45,18');
assert.equal(result[0].range.startColumn, 1);
assert.equal(result[0].range.endColumn, 106);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts.
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts. in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString());
assert.equal(result[0].range.startColumn, 5);
assert.equal(result[0].range.endColumn, 84);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
// Example: at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game\\
line = toOSPath(' at C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game\\ in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
// Example: at "C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts"
line = toOSPath(' at "C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts" in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString());
assert.equal(result[0].range.startColumn, 6);
assert.equal(result[0].range.endColumn, 85);
// Example: at 'C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts'
line = toOSPath(' at \'C:\\Users\\someone\\AppData\\Local\\Temp\\_monacodata_9888\\workspaces\\mankala\\Game.ts\' in');
result = OutputLinkComputer.detectLinks(line, 1, patternsSlash, contextService);
assert.equal(result.length, 1);
assert.equal(result[0].url, contextService.toResource('/Game.ts').toString());
assert.equal(result[0].range.startColumn, 6);
assert.equal(result[0].range.endColumn, 85);
});
}); | the_stack |
import { describe, expect, it } from 'vitest'
class TestError extends Error {}
// For expect.extend
interface CustomMatchers<R = unknown> {
toBeDividedBy(divisor: number): R
}
declare global {
namespace Vi {
interface JestAssertion extends CustomMatchers {}
interface AsymmetricMatchersContaining extends CustomMatchers {}
}
}
describe('jest-expect', () => {
it('basic', () => {
expect(1).toBe(1)
expect(null).toBeNull()
expect(1).not.toBeNull()
expect(null).toBeDefined()
expect(undefined).not.toBeDefined()
expect(undefined).toBeUndefined()
expect(null).not.toBeUndefined()
expect([]).toBeTruthy()
expect(0).toBeFalsy()
expect('Hello').toMatch(/llo/)
expect('Hello').toMatch('llo')
expect('Hello').toContain('llo')
expect(['Hello']).toContain('Hello')
expect([{ text: 'Hello' }]).toContainEqual({ text: 'Hello' })
expect([{ text: 'Bye' }]).not.toContainEqual({ text: 'Hello' })
expect(1).toBeGreaterThan(0)
expect(BigInt(1)).toBeGreaterThan(BigInt(0))
expect(1).toBeGreaterThan(BigInt(0))
expect(BigInt(1)).toBeGreaterThan(0)
expect(1).toBeGreaterThanOrEqual(1)
expect(1).toBeGreaterThanOrEqual(0)
expect(BigInt(1)).toBeGreaterThanOrEqual(BigInt(1))
expect(BigInt(1)).toBeGreaterThanOrEqual(BigInt(0))
expect(BigInt(1)).toBeGreaterThanOrEqual(1)
expect(1).toBeGreaterThanOrEqual(BigInt(1))
expect(0).toBeLessThan(1)
expect(BigInt(0)).toBeLessThan(BigInt(1))
expect(BigInt(0)).toBeLessThan(1)
expect(1).toBeLessThanOrEqual(1)
expect(0).toBeLessThanOrEqual(1)
expect(BigInt(1)).toBeLessThanOrEqual(BigInt(1))
expect(BigInt(0)).toBeLessThanOrEqual(BigInt(1))
expect(BigInt(1)).toBeLessThanOrEqual(1)
expect(1).toBeLessThanOrEqual(BigInt(1))
expect(() => {
throw new Error('this is the error message')
}).toThrow('this is the error message')
expect(() => {}).not.toThrow()
expect(() => {
throw new TestError('error')
}).toThrow(TestError)
const err = new Error('hello world')
expect(() => {
throw err
}).toThrow(err)
expect(() => {
throw new Error('message')
}).toThrow(expect.objectContaining({
message: expect.stringContaining('mes'),
}))
expect([1, 2, 3]).toHaveLength(3)
expect('abc').toHaveLength(3)
expect('').not.toHaveLength(5)
expect({ length: 3 }).toHaveLength(3)
expect(0.2 + 0.1).not.toBe(0.3)
expect(0.2 + 0.1).toBeCloseTo(0.3, 5)
expect(0.2 + 0.1).not.toBeCloseTo(0.3, 100) // expect.closeTo will fail in chai
})
it('asymmetric matchers (jest style)', () => {
expect({ foo: 'bar' }).toEqual({ foo: expect.stringContaining('ba') })
expect('bar').toEqual(expect.stringContaining('ba'))
expect(['bar']).toEqual([expect.stringContaining('ba')])
expect(new Set(['bar'])).toEqual(new Set([expect.stringContaining('ba')]))
expect({ foo: 'bar' }).not.toEqual({ foo: expect.stringContaining('zoo') })
expect('bar').not.toEqual(expect.stringContaining('zoo'))
expect(['bar']).not.toEqual([expect.stringContaining('zoo')])
expect({ foo: 'bar', bar: 'foo', hi: 'hello' }).toEqual({
foo: expect.stringContaining('ba'),
bar: expect.stringContaining('fo'),
hi: 'hello',
})
expect(0).toEqual(expect.anything())
expect({}).toEqual(expect.anything())
expect('string').toEqual(expect.anything())
expect(null).not.toEqual(expect.anything())
expect(undefined).not.toEqual(expect.anything())
expect({ a: 0, b: 0 }).toEqual(expect.objectContaining({ a: 0 }))
expect({ a: 0, b: 0 }).not.toEqual(expect.objectContaining({ z: 0 }))
expect(0).toEqual(expect.any(Number))
expect('string').toEqual(expect.any(String))
expect('string').not.toEqual(expect.any(Number))
expect(['Bob', 'Eve']).toEqual(expect.arrayContaining(['Bob']))
expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(['Mohammad']))
expect([
{ name: 'Bob' },
{ name: 'Eve' },
]).toEqual(expect.arrayContaining<{ name: string }>([
{ name: 'Bob' },
]))
expect([
{ name: 'Bob' },
{ name: 'Eve' },
]).not.toEqual(expect.arrayContaining<{ name: string }>([
{ name: 'Mohammad' },
]))
expect('Mohammad').toEqual(expect.stringMatching(/Moh/))
expect('Mohammad').not.toEqual(expect.stringMatching(/jack/))
// TODO: support set
// expect(new Set(['bar'])).not.toEqual(new Set([expect.stringContaining('zoo')]))
})
it('asymmetric matchers negate', () => {
expect('bar').toEqual(expect.not.stringContaining('zoo'))
expect('bar').toEqual(expect.not.stringMatching(/zoo/))
expect({ bar: 'zoo' }).toEqual(expect.not.objectContaining({ zoo: 'bar' }))
expect(['Bob', 'Eve']).toEqual(expect.not.arrayContaining(['Steve']))
})
it('expect.extend', () => {
expect.extend({
toBeDividedBy(received, divisor) {
const pass = received % divisor === 0
if (pass) {
return {
message: () =>
`expected ${received} not to be divisible by ${divisor}`,
pass: true,
}
}
else {
return {
message: () =>
`expected ${received} to be divisible by ${divisor}`,
pass: false,
}
}
},
})
expect(5).toBeDividedBy(5)
expect(5).not.toBeDividedBy(4)
expect({ one: 1, two: 2 }).toEqual({
one: expect.toBeDividedBy(1),
two: expect.not.toBeDividedBy(5),
})
})
it('object', () => {
expect({}).toEqual({})
expect({ apples: 13 }).toEqual({ apples: 13 })
expect({}).toStrictEqual({})
expect({}).not.toBe({})
const foo = {}
const complex = {
'foo': 1,
'foo.bar[0]': 'baz',
'bar': {
foo: 'foo',
bar: 100,
arr: ['first', { zoo: 'monkey' }],
},
}
expect(foo).toBe(foo)
expect(foo).toStrictEqual(foo)
expect(complex).toMatchObject({})
expect(complex).toMatchObject({ foo: 1 })
expect([complex]).toMatchObject([{ foo: 1 }])
expect(complex).not.toMatchObject({ foo: 2 })
expect(complex).toMatchObject({ bar: { bar: 100 } })
expect(complex).toMatchObject({ foo: expect.any(Number) })
expect(complex).toHaveProperty('foo')
expect(complex).toHaveProperty('foo', 1)
expect(complex).toHaveProperty('bar.foo', 'foo')
expect(complex).toHaveProperty('bar.arr[0]')
expect(complex).toHaveProperty('bar.arr[1].zoo', 'monkey')
expect(complex).toHaveProperty('bar.arr.0')
expect(complex).toHaveProperty('bar.arr.1.zoo', 'monkey')
expect(complex).toHaveProperty(['bar', 'arr', '1', 'zoo'], 'monkey')
expect(complex).toHaveProperty(['foo.bar[0]'], 'baz')
})
it('assertions', () => {
expect(1).toBe(1)
expect(1).toBe(1)
expect(1).toBe(1)
expect.assertions(3)
})
it('assertions with different order', () => {
expect.assertions(3)
expect(1).toBe(1)
expect(1).toBe(1)
expect(1).toBe(1)
})
it('assertions when asynchronous code', async () => {
expect.assertions(3)
await Promise.all([
expect(1).toBe(1),
expect(1).toBe(1),
expect(1).toBe(1),
])
})
it.fails('assertions when asynchronous code', async () => {
// Error: expected number of assertions to be 2, but got 3
expect.assertions(2)
await Promise.all([
expect(1).toBe(1),
expect(1).toBe(1),
expect(1).toBe(1),
])
})
it.fails('has assertions', () => {
expect.hasAssertions()
})
it('has assertions', () => {
expect(1).toBe(1)
expect.hasAssertions()
})
it('has assertions with different order', () => {
expect.hasAssertions()
expect(1).toBe(1)
})
it.fails('toBe with null/undefined values', () => {
expect(undefined).toBe(true)
expect(null).toBe(true)
})
// https://jestjs.io/docs/expect#tostrictequalvalue
class LaCroix {
constructor(public flavor: any) {}
}
describe('the La Croix cans on my desk', () => {
it('are not semantically the same', () => {
expect(new LaCroix('lemon')).toEqual({ flavor: 'lemon' })
expect(new LaCroix('lemon')).not.toStrictEqual({ flavor: 'lemon' })
})
})
it('array', () => {
expect([]).toEqual([])
expect([]).not.toBe([])
expect([]).toStrictEqual([])
const foo: any[] = []
expect(foo).toBe(foo)
expect(foo).toStrictEqual(foo)
const complex = [
{
foo: 1,
bar: { foo: 'foo', bar: 100, arr: ['first', { zoo: 'monkey' }] },
},
]
expect(complex).toStrictEqual([
{
foo: 1,
bar: { foo: 'foo', bar: 100, arr: ['first', { zoo: 'monkey' }] },
},
])
})
})
describe('.toStrictEqual()', () => {
class TestClassA {
constructor(public a: any, public b: any) {}
}
class TestClassB {
constructor(public a: any, public b: any) {}
}
const TestClassC = class Child extends TestClassA {
constructor(a: any, b: any) {
super(a, b)
}
}
const TestClassD = class Child extends TestClassB {
constructor(a: any, b: any) {
super(a, b)
}
}
it('does not ignore keys with undefined values', () => {
expect({
a: undefined,
b: 2,
}).not.toStrictEqual({ b: 2 })
})
it('does not ignore keys with undefined values inside an array', () => {
expect([{ a: undefined }]).not.toStrictEqual([{}])
})
it('does not ignore keys with undefined values deep inside an object', () => {
expect([{ a: [{ a: undefined }] }]).not.toStrictEqual([{ a: [{}] }])
})
it('does not consider holes as undefined in sparse arrays', () => {
expect([, , , 1, , ,]).not.toStrictEqual([, , , 1, undefined, ,])
})
it('passes when comparing same type', () => {
expect({
test: new TestClassA(1, 2),
}).toStrictEqual({ test: new TestClassA(1, 2) })
})
it('does not pass for different types', () => {
expect({
test: new TestClassA(1, 2),
}).not.toStrictEqual({ test: new TestClassB(1, 2) })
})
it('does not simply compare constructor names', () => {
const c = new TestClassC(1, 2)
const d = new TestClassD(1, 2)
expect(c.constructor.name).toEqual(d.constructor.name)
expect({ test: c }).not.toStrictEqual({ test: d })
})
it('passes for matching sparse arrays', () => {
expect([, 1]).toStrictEqual([, 1])
})
it('does not pass when sparseness of arrays do not match', () => {
expect([, 1]).not.toStrictEqual([undefined, 1])
expect([undefined, 1]).not.toStrictEqual([, 1])
expect([, , , 1]).not.toStrictEqual([, 1])
})
it('does not pass when equally sparse arrays have different values', () => {
expect([, 1]).not.toStrictEqual([, 2])
})
it('does not pass when ArrayBuffers are not equal', () => {
expect(Uint8Array.from([1, 2]).buffer).not.toStrictEqual(
Uint8Array.from([0, 0]).buffer,
)
expect(Uint8Array.from([2, 1]).buffer).not.toStrictEqual(
Uint8Array.from([2, 2]).buffer,
)
expect(Uint8Array.from([]).buffer).not.toStrictEqual(
Uint8Array.from([1]).buffer,
)
})
it('passes for matching buffers', () => {
expect(Uint8Array.from([1]).buffer).toStrictEqual(
Uint8Array.from([1]).buffer,
)
expect(Uint8Array.from([]).buffer).toStrictEqual(
Uint8Array.from([]).buffer,
)
expect(Uint8Array.from([9, 3]).buffer).toStrictEqual(
Uint8Array.from([9, 3]).buffer,
)
})
})
describe('toBeTypeOf()', () => {
it.each([
[1n, 'bigint'],
[true, 'boolean'],
[false, 'boolean'],
[() => {}, 'function'],
[function () {}, 'function'],
[1, 'number'],
[Infinity, 'number'],
[NaN, 'number'],
[0, 'number'],
[{}, 'object'],
[[], 'object'],
[null, 'object'],
['', 'string'],
['test', 'string'],
[Symbol('test'), 'symbol'],
[undefined, 'undefined'],
] as const)('pass with typeof %s === %s', (actual, expected) => {
expect(actual).toBeTypeOf(expected)
})
it('pass with negotiation', () => {
expect('test').not.toBeTypeOf('number')
})
})
describe('toSatisfy()', () => {
const isOdd = (value: number) => value % 2 !== 0
it('pass with 0', () => {
expect(1).toSatisfy(isOdd)
})
it('pass with negotiation', () => {
expect(2).not.toSatisfy(isOdd)
})
})
describe('async expect', () => {
it('resolves', async () => {
await expect((async () => 'true')()).resolves.toBe('true')
await expect((async () => 'true')()).resolves.not.toBe('true22')
})
it.fails('failed to resolve', async () => {
await expect((async () => {
throw new Error('err')
})()).resolves.toBe('true')
})
it('rejects', async () => {
await expect((async () => {
throw new Error('err')
})()).rejects.toStrictEqual(new Error('err'))
await expect((async () => {
throw new Error('err')
})()).rejects.toThrow('err')
expect((async () => {
throw new TestError('error')
})()).rejects.toThrow(TestError)
const err = new Error('hello world')
expect((async () => {
throw err
})()).rejects.toThrow(err)
expect((async () => {
throw new Error('message')
})()).rejects.toThrow(expect.objectContaining({
message: expect.stringContaining('mes'),
}))
await expect((async () => {
throw new Error('err')
})()).rejects.not.toStrictEqual(new Error('fake err'))
})
it.fails('failed to reject', async () => {
await expect((async () => 'test')()).rejects.toBe('test')
})
})
it('timeout', () => new Promise(resolve => setTimeout(resolve, 500))) | the_stack |
import Divider from '@material-ui/core/Divider';
import Drawer from '@material-ui/core/Drawer';
import IconButton from '@material-ui/core/IconButton';
import List from '@material-ui/core/List';
import { useTheme } from '@material-ui/core/styles';
import { Breakpoint } from '@material-ui/core/styles/createBreakpoints';
import withWidth, { isWidthDown, isWidthUp } from '@material-ui/core/withWidth';
import ChevronLeftIcon from '@material-ui/icons/ChevronLeft';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import DeveloperBoardIcon from '@material-ui/icons/DeveloperBoard';
import DeveloperModeIcon from '@material-ui/icons/DeveloperMode';
import GithubIcon from '@material-ui/icons/GitHub';
import EventIcon from '@material-ui/icons/Event';
import HomeIcon from '@material-ui/icons/Home';
import LinkIcon from '@material-ui/icons/Link';
import LockOpenIcon from '@material-ui/icons/LockOpen';
import PaletteIcon from '@material-ui/icons/Palette';
import SelectAllIcon from '@material-ui/icons/SelectAll';
import SimCardIcon from '@material-ui/icons/SimCard';
import TextFieldsIcon from '@material-ui/icons/TextFields';
import TextRotationNoneIcon from '@material-ui/icons/TextRotationNone';
import TocIcon from '@material-ui/icons/Toc';
import WrapTextIcon from '@material-ui/icons/WrapText';
import clsx from 'clsx';
import React, { lazy, Suspense } from 'react';
import { Helmet } from 'react-helmet';
import { NavLink, Route, Switch, useHistory } from 'react-router-dom';
import ApplicationBar from './components/ApplicationBar/ApplicationBar';
import FeaturesGroup from './components/FeaturesGroup';
import { FullCenteredContent } from './components/FullCenteredContent/FullCenteredContent';
import Home from './components/Home';
import { NavbarButtonLink } from './components/NavbarButtonLink/NavbarButtonLink';
import ToasterProvider from './components/Toaster/ToasterProvider';
import Base64Encoder from './containers/Base64Encoder';
import Base64FileEncoder from './containers/Base64FileEncoder';
import ColorPicker from './containers/ColorPicker';
import NamedColors from './containers/NamedColors';
import URLEncoder from './containers/URLEncoder';
import URLParser from './containers/URLParser';
import Banner from './images/icon.png';
import { useStyles } from './styles';
interface Props {
width: Breakpoint;
}
const App: React.FC<Props> = (props: Props) => {
const desc = 'Web Toolbox app. A collection of utilities for developers.';
const classes = useStyles();
const history = useHistory();
const theme = useTheme();
const [open, setOpen] = React.useState(isWidthUp('md', props.width));
const About = lazy(() => import('./components/About/About'));
const AppPreferences = lazy(() => import('./containers/AppPreferences'));
const JSONFormatter = lazy(() => import('./containers/JSONFormatter'));
const RegExTester = lazy(() => import('./containers/RegExTester'));
const UUIDGenerator = lazy(() => import('./containers/UUIDGenerator'));
const JWTDecoder = lazy(() => import('./containers/JWTDecoder'));
const ImageOCR = lazy(() => import('./containers/ImageOCR'));
const QRCodeGenerator = lazy(() => import('./containers/QRCodeGenerator'));
const CommonLists = lazy(() => import('./containers/CommonLists'));
const GithubUserProjects = lazy(() => import('./containers/GithubUserProjects'));
const JSONConverter = lazy(() => import('./containers/JSONConverter'));
const DateConverter = lazy(() => import('./containers/DateConverter'));
// Because of the following issue, Suspense is breaking the tab selection (fix will be part of React 18)
// @see https://github.com/mui-org/material-ui/issues/14077
// const FeaturesGroup = lazy(() => import('./components/FeaturesGroup'));
// const URLParser = lazy(() => import('./containers/URLParser'));
// const URLEncoder = lazy(() => import('./containers/URLEncoder'));
// const Base64Encoder = lazy(() => import('./containers/Base64Encoder'));
// const Base64ImageEncoder = lazy(() => import('./containers/Base64ImageEncoder'));
// const NamedColors = lazy(() => import('./containers/NamedColors'));
// const ColorPicker = lazy(() => import('./containers/ColorPicker'));
const featuresGroupURL = [
{ type: URLParser, path: '/URLParser', label: 'Parser'},
{ type: URLEncoder, path: '/URLEncoder', label: 'Encoder'}
];
const featuresGroupBase64 = [
{ type: Base64Encoder, path: '/Base64Encoder', label: 'String'},
{ type: Base64FileEncoder, path: '/Base64FileEncoder', label: 'File'}
];
const featuresGroupColors = [
{ type: ColorPicker, path: '/ColorPicker', label: 'Picker'},
{ type: NamedColors, path: '/NamedColors', label: 'Named colors'},
];
React.useEffect(setupIPC, [history]);
function setupIPC() {
// Will be defined if the React App is running inside Electron
if (window.require) {
const ipc = window.require("electron").ipcRenderer;
ipc.send('rendererAppStarted');
ipc.on('navigateTo', (_event: any, path: string) => history.push(path));
}
}
const menuClick = () => {
if (open && isWidthDown('sm', props.width)) {
setOpen(false);
}
}
return (
<>
<Helmet titleTemplate="Web Toolbox - %s" defaultTitle="Web Toolbox">
<meta name="description" content={desc} />
</Helmet>
<div className={classes.root}>
<ApplicationBar open={open} setOpen={setOpen} />
<Drawer
variant="permanent"
className={clsx(classes.drawer, {
[classes.drawerOpen]: open,
[classes.drawerClose]: !open,
})}
classes={{
paper: clsx({
[classes.drawerOpen]: open,
[classes.drawerClose]: !open,
}),
}}
>
<div className={classes.toolbar}>
<div className={classes.toolbarIconContainer}>
<NavLink exact to='/about' title='About Web Toolbox…'><img src={Banner} alt='Web Toolbox' className={classes.toolbarIcon} /></NavLink>
</div>
<IconButton onClick={() => setOpen(false)} title="Toggle sidebar menu">
{theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />}
</IconButton>
</div>
<Divider />
<List className={classes.menu}>
<NavbarButtonLink icon={<HomeIcon />} to="/" title="Home" detail="Home" exact={true} onClick={menuClick} />
<NavbarButtonLink icon={<LinkIcon />} to="/URL" title="URL parse, encode" detail="URL utilities for parsing and encoding url parameters" onClick={menuClick} />
<NavbarButtonLink icon={<DeveloperBoardIcon />} to="/Base64" title="Base64" detail="Base64 encoders/decoders" onClick={menuClick} />
<NavbarButtonLink icon={<PaletteIcon />} to="/Colors" title="Color picker" detail="Image color picker" onClick={menuClick} />
<NavbarButtonLink icon={<WrapTextIcon />} to="/JSONFormatter" title="JSON Formatter" detail="JSON Formatter" onClick={menuClick} />
<NavbarButtonLink icon={<DeveloperModeIcon />} to="/JSONConverter" title="JSON Converter" detail="Convert json into multiple output languages" onClick={menuClick} />
<NavbarButtonLink icon={<TextRotationNoneIcon />} to="/RegExTester" title="RegEx tester" detail="Regular expression tester" onClick={menuClick} />
<NavbarButtonLink icon={<SimCardIcon />} to="/UUIDGenerator" title="UUID generator" detail="UUID generator" onClick={menuClick} />
<NavbarButtonLink icon={<LockOpenIcon />} to="/JWTDecoder" title="JWT decoder" detail="JSON Web Token decoder" onClick={menuClick} />
<NavbarButtonLink icon={<SelectAllIcon />} to="/QRCodeGenerator" title="QR Code generator" detail="QR Code generator" onClick={menuClick} />
<NavbarButtonLink icon={<TextFieldsIcon />} to="/ImageOCR" title="Image OCR" detail="Image text extractor" onClick={menuClick} />
<NavbarButtonLink icon={<TocIcon />} to="/CommonLists" title="Mime-types, HTML" detail="Html entities, Mime-types, and more…" onClick={menuClick} />
<NavbarButtonLink icon={<GithubIcon />} to="/GithubUserProjects" title="Github search" detail="Github user projects" onClick={menuClick} />
<NavbarButtonLink icon={<EventIcon />} to="/DateConverter" title="Date & Epoch" detail="Date and Epoch utilities" onClick={menuClick} />
</List>
</Drawer>
<ToasterProvider>
<main className={classes.content}>
<div className={classes.toolbar} />
<Suspense fallback={<FullCenteredContent>Loading…</FullCenteredContent>}>
<Switch>
<Route exact path="/"><Home /></Route>
<Route exact path="/about"><About /></Route>
<Route exact path="/preferences"><AppPreferences /></Route>
<Route path="/URL"><FeaturesGroup tabs={featuresGroupURL} /></Route>
<Route path="/Base64"><FeaturesGroup tabs={featuresGroupBase64} /></Route>
<Route path="/Colors"><FeaturesGroup tabs={featuresGroupColors} /></Route>
<Route exact path="/Base64Encoder"><Base64Encoder /></Route>
<Route exact path="/Base64FileEncoder"><Base64FileEncoder /></Route>
<Route exact path="/JSONFormatter"><JSONFormatter /></Route>
<Route exact path="/JSONConverter"><JSONConverter /></Route>
<Route exact path="/RegExTester"><RegExTester /></Route>
<Route exact path="/UUIDGenerator"><UUIDGenerator /></Route>
<Route exact path="/JWTDecoder"><JWTDecoder /></Route>
<Route exact path="/QRCodeGenerator"><QRCodeGenerator /></Route>
<Route exact path="/ImageOCR"><ImageOCR /></Route>
<Route exact path="/CommonLists"><CommonLists /></Route>
<Route exact path="/GithubUserProjects"><GithubUserProjects /></Route>
<Route exact path="/DateConverter"><DateConverter /></Route>
{/** Default route is the home */}
<Route component={Home} />
</Switch>
</Suspense>
</main>
</ToasterProvider>
</div>
</>
);
}
export default withWidth()(App); | the_stack |
import {ComponentHarness, HarnessLoader, HarnessPredicate, parallel} from '@angular/cdk/testing';
import {createFakeEvent, dispatchFakeEvent} from '../../../cdk/testing/private';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Component, Type} from '@angular/core';
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {FormControl, ReactiveFormsModule, Validators} from '@angular/forms';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {MatFormFieldHarness} from './form-field-harness';
/** Shared tests to run on both the original and MDC-based form-field's. */
export function runHarnessTests(
modules: Type<any>[],
{
formFieldHarness,
inputHarness,
selectHarness,
datepickerInputHarness,
dateRangeInputHarness,
isMdcImplementation,
}: {
formFieldHarness: typeof MatFormFieldHarness;
inputHarness: Type<any>;
selectHarness: Type<any>;
datepickerInputHarness: Type<any>;
dateRangeInputHarness: Type<any>;
isMdcImplementation: boolean;
},
) {
let fixture: ComponentFixture<FormFieldHarnessTest>;
let loader: HarnessLoader;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [NoopAnimationsModule, ReactiveFormsModule, ...modules],
declarations: [FormFieldHarnessTest],
}).compileComponents();
fixture = TestBed.createComponent(FormFieldHarnessTest);
fixture.componentInstance.isMdc = isMdcImplementation;
fixture.detectChanges();
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should be able to load harnesses', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(formFields.length).toBe(7);
});
it('should be able to load form-field that matches specific selector', async () => {
const formFieldMatches = await loader.getAllHarnesses(
formFieldHarness.with({
selector: '#first-form-field',
}),
);
expect(formFieldMatches.length).toBe(1);
});
it('should be able to get appearance of form-field', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[0].getAppearance()).toBe(isMdcImplementation ? 'fill' : 'legacy');
expect(await formFields[1].getAppearance()).toBe(isMdcImplementation ? 'fill' : 'standard');
expect(await formFields[2].getAppearance()).toBe('fill');
expect(await formFields[3].getAppearance()).toBe('outline');
expect(await formFields[4].getAppearance()).toBe(isMdcImplementation ? 'fill' : 'legacy');
});
it('should be able to get control of form-field', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect((await formFields[0].getControl()) instanceof inputHarness).toBe(true);
expect((await formFields[1].getControl()) instanceof inputHarness).toBe(true);
expect((await formFields[2].getControl()) instanceof selectHarness).toBe(true);
expect((await formFields[3].getControl()) instanceof inputHarness).toBe(true);
expect((await formFields[4].getControl()) instanceof inputHarness).toBe(true);
expect((await formFields[5].getControl()) instanceof datepickerInputHarness).toBe(true);
expect((await formFields[6].getControl()) instanceof dateRangeInputHarness).toBe(true);
});
it('should be able to get custom control of form-field', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[0].getControl(CustomControlHarness)).toBe(null);
expect(
(await formFields[1].getControl(CustomControlHarness)) instanceof CustomControlHarness,
).toBe(true);
expect(await formFields[2].getControl(CustomControlHarness)).toBe(null);
expect(await formFields[3].getControl(CustomControlHarness)).toBe(null);
expect(await formFields[4].getControl(CustomControlHarness)).toBe(null);
});
it('should be able to get custom control of form-field using a predicate', async () => {
const predicate = new HarnessPredicate(CustomControlHarness, {});
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[0].getControl(predicate)).toBe(null);
expect((await formFields[1].getControl(predicate)) instanceof CustomControlHarness).toBe(true);
expect(await formFields[2].getControl(predicate)).toBe(null);
expect(await formFields[3].getControl(predicate)).toBe(null);
expect(await formFields[4].getControl(predicate)).toBe(null);
});
it('should be able to check whether form-field has label', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
// The non MDC-based form-field elevates the placeholder to a floating
// label. This is not the case in the MDC-based implementation.
expect(await formFields[0].hasLabel()).toBe(!isMdcImplementation);
expect(await formFields[1].hasLabel()).toBe(false);
expect(await formFields[2].hasLabel()).toBe(true);
expect(await formFields[3].hasLabel()).toBe(true);
expect(await formFields[4].hasLabel()).toBe(true);
});
it('should be able to check whether label is floating', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
// The first form-field uses the legacy appearance. This means that the
// placeholder will be elevated to a label. Also since there is a static
// value, the label will float initially. The MDC implementation does not
// elevate placeholders to floating labels.
expect(await formFields[0].isLabelFloating()).toBe(!isMdcImplementation);
expect(await formFields[1].isLabelFloating()).toBe(false);
expect(await formFields[2].isLabelFloating()).toBe(false);
expect(await formFields[3].isLabelFloating()).toBe(true);
expect(await formFields[4].isLabelFloating()).toBe(false);
fixture.componentInstance.shouldLabelFloat = 'always';
expect(await formFields[4].isLabelFloating()).toBe(true);
});
it('should be able to check whether form-field is disabled', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[0].isDisabled()).toBe(false);
expect(await formFields[1].isDisabled()).toBe(false);
expect(await formFields[2].isDisabled()).toBe(false);
expect(await formFields[3].isDisabled()).toBe(false);
expect(await formFields[4].isDisabled()).toBe(false);
fixture.componentInstance.isDisabled = true;
expect(await formFields[0].isDisabled()).toBe(true);
expect(await formFields[1].isDisabled()).toBe(false);
expect(await formFields[2].isDisabled()).toBe(true);
expect(await formFields[3].isDisabled()).toBe(false);
expect(await formFields[4].isDisabled()).toBe(false);
});
it('should be able to check whether form-field is auto-filled', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[0].isAutofilled()).toBe(false);
expect(await formFields[1].isAutofilled()).toBe(false);
expect(await formFields[2].isAutofilled()).toBe(false);
expect(await formFields[3].isAutofilled()).toBe(false);
expect(await formFields[4].isAutofilled()).toBe(false);
const autofillTriggerEvent: any = createFakeEvent('animationstart');
autofillTriggerEvent.animationName = 'cdk-text-field-autofill-start';
// Dispatch an "animationstart" event on the input to trigger the
// autofill monitor.
fixture.nativeElement
.querySelector('#first-form-field input')
.dispatchEvent(autofillTriggerEvent);
expect(await formFields[0].isAutofilled()).toBe(true);
expect(await formFields[1].isAutofilled()).toBe(false);
expect(await formFields[2].isAutofilled()).toBe(false);
expect(await formFields[3].isAutofilled()).toBe(false);
expect(await formFields[4].isAutofilled()).toBe(false);
});
it('should be able to get theme color of form-field', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[0].getThemeColor()).toBe('primary');
expect(await formFields[1].getThemeColor()).toBe('warn');
expect(await formFields[2].getThemeColor()).toBe('accent');
expect(await formFields[3].getThemeColor()).toBe('primary');
expect(await formFields[4].getThemeColor()).toBe('primary');
});
it('should be able to get label of form-field', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
// In the MDC based implementation, the placeholder will not be elevated
// to a label, and the harness will return `null`.
expect(await formFields[0].getLabel()).toBe(isMdcImplementation ? null : 'With placeholder');
expect(await formFields[1].getLabel()).toBe(null);
expect(await formFields[2].getLabel()).toBe('Label');
expect(await formFields[3].getLabel()).toBe('autocomplete_label');
expect(await formFields[4].getLabel()).toBe('Label');
});
it('should be able to get error messages of form-field', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[1].getTextErrors()).toEqual([]);
fixture.componentInstance.requiredControl.setValue('');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'blur');
expect(await formFields[1].getTextErrors()).toEqual(['Error 1', 'Error 2']);
});
it('should be able to get hint messages of form-field', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[1].getTextHints()).toEqual(['Hint 1', 'Hint 2']);
fixture.componentInstance.requiredControl.setValue('');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'blur');
expect(await formFields[1].getTextHints()).toEqual([]);
});
it('should be able to get the prefix text of a form-field', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
const prefixTexts = await parallel(() => formFields.map(f => f.getPrefixText()));
expect(prefixTexts).toEqual(['prefix_textprefix_text_2', '', '', '', '', '', '']);
});
it('should be able to get the suffix text of a form-field', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
const suffixTexts = await parallel(() => formFields.map(f => f.getSuffixText()));
expect(suffixTexts).toEqual(['suffix_text', '', '', '', '', '', '']);
});
it('should be able to check if form field has been touched', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[0].isControlTouched()).toBe(null);
expect(await formFields[1].isControlTouched()).toBe(false);
fixture.componentInstance.requiredControl.setValue('');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'blur');
expect(await formFields[1].isControlTouched()).toBe(true);
});
it('should be able to check if form field is invalid', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[0].isControlValid()).toBe(null);
expect(await formFields[1].isControlValid()).toBe(true);
fixture.componentInstance.requiredControl.setValue('');
expect(await formFields[1].isControlValid()).toBe(false);
});
it('should be able to check if form field is dirty', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[0].isControlDirty()).toBe(null);
expect(await formFields[1].isControlDirty()).toBe(false);
fixture.componentInstance.requiredControl.setValue('new value');
dispatchFakeEvent(fixture.nativeElement.querySelector('#with-errors input'), 'input');
expect(await formFields[1].isControlDirty()).toBe(true);
});
it('should be able to check if form field is pending async validation', async () => {
const formFields = await loader.getAllHarnesses(formFieldHarness);
expect(await formFields[0].isControlPending()).toBe(null);
expect(await formFields[1].isControlPending()).toBe(false);
fixture.componentInstance.setupAsyncValidator();
fixture.componentInstance.requiredControl.setValue('');
expect(await formFields[1].isControlPending()).toBe(true);
});
}
@Component({
template: `
<mat-form-field id="first-form-field" [floatLabel]="shouldLabelFloat">
<span matPrefix *ngIf="!isMdc">prefix_text</span>
<span matPrefix *ngIf="!isMdc">prefix_text_2</span>
<span matTextPrefix *ngIf="isMdc">prefix_text</span>
<span matTextPrefix *ngIf="isMdc">prefix_text_2</span>
<input matInput value="Sushi" name="favorite-food" placeholder="With placeholder"
[disabled]="isDisabled">
<span matSuffix *ngIf="!isMdc">suffix_text</span>
<span matTextSuffix *ngIf="isMdc">suffix_text</span>
</mat-form-field>
<mat-form-field appearance="standard" color="warn" id="with-errors">
<span class="custom-control">Custom control harness</span>
<input matInput [formControl]="requiredControl">
<mat-error>Error 1</mat-error>
<mat-error>Error 2</mat-error>
<mat-hint align="start">Hint 1</mat-hint>
<mat-hint align="end">Hint 2</mat-hint>
</mat-form-field>
<mat-form-field appearance="fill" color="accent">
<mat-label>Label</mat-label>
<mat-select [disabled]="isDisabled">
<mat-option>First</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field floatLabel="always" appearance="outline" color="primary">
<mat-label>autocomplete_label</mat-label>
<input type="text" matInput [matAutocomplete]="auto">
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete">
<mat-option>autocomplete_option</mat-option>
</mat-autocomplete>
<mat-form-field id="last-form-field" [floatLabel]="shouldLabelFloat">
<mat-label>Label</mat-label>
<input matInput>
</mat-form-field>
<mat-form-field>
<mat-label>Date</mat-label>
<input matInput [matDatepicker]="datepicker">
<mat-datepicker #datepicker></mat-datepicker>
</mat-form-field>
<mat-form-field>
<mat-label>Date range</mat-label>
<mat-date-range-input [rangePicker]="rangePicker">
<input matStartDate placeholder="Start date"/>
<input matEndDate placeholder="End date"/>
</mat-date-range-input>
<mat-date-range-picker #rangePicker></mat-date-range-picker>
</mat-form-field>
`,
})
class FormFieldHarnessTest {
requiredControl = new FormControl('Initial value', [Validators.required]);
shouldLabelFloat: 'always' | 'auto' = 'auto';
hasLabel = false;
isDisabled = false;
isMdc = false;
setupAsyncValidator() {
this.requiredControl.setValidators(() => null);
this.requiredControl.setAsyncValidators(() => new Promise(res => setTimeout(res, 10000)));
}
}
class CustomControlHarness extends ComponentHarness {
static hostSelector = '.custom-control';
} | the_stack |
import * as arrayUtil from "dojo/_base/array";
import * as config from "dojo/_base/config";
import * as declare from "dojo/_base/declare";
import * as Deferred from "dojo/_base/Deferred";
import * as lang from "dojo/_base/lang";
import * as cookie from "dojo/cookie";
import * as QueryResults from "dojo/store/util/QueryResults";
import * as topic from "dojo/topic";
import * as ESPUtil from "./ESPUtil";
import * as hpccComms from "@hpcc-js/comms";
declare const dojo: any;
declare const debugConfig: any;
class RequestHelper {
readonly serverIP: null;
readonly timeOutSeconds: number;
constructor() {
this.serverIP = (typeof debugConfig !== "undefined") ? debugConfig.IP : this.getParamFromURL("ServerIP");
this.timeOutSeconds = 120;
}
getParamFromURL(key) {
let value = "";
if (dojo.doc.location.search) {
const searchStr = dojo.doc.location.search.substr((dojo.doc.location.search.substr(0, 1) === "?" ? 1 : 0));
value = searchStr ? dojo.queryToObject(searchStr)[key] : "";
}
if (value)
return value;
return config[key];
}
getBaseURL(service?) {
if (service === undefined) {
service = "WsWorkunits";
}
if (this.serverIP)
return "http://" + this.serverIP + ":8010/" + service;
return "/" + service;
}
isCrossSite() {
return this.serverIP ? true : false;
}
isSessionCall(service, action) {
switch (service) {
case "esp":
switch (action) {
// case "login":
// case "logout":
// case "lock":
case "unlock":
return true;
}
break;
}
return false;
}
hasServerSetCookie() {
return cookie("ESPSessionState") !== undefined;
}
hasAuthentication() {
const retVal = cookie("ESPSessionState");
return retVal === "true" || retVal === true;
}
isAuthenticated() {
const retVal = cookie("ESPAuthenticated");
return retVal === "true" || retVal === true;
}
isLocked() {
return cookie("Status") === "Locked";
}
_send(service, action, _params) {
const params = lang.mixin({
request: {},
load(response) {
},
error(error) {
},
event(evt) {
}
}, _params);
lang.mixin(params.request, {
rawxml_: true
});
const handleAs = params.handleAs ? params.handleAs : "json";
let postfix = "";
if (handleAs === "json") {
postfix = ".json";
}
// var method = params.method ? params.method : "get";
let retVal = null;
if (this.isCrossSite()) {
const transport = new hpccComms.Connection({ baseUrl: this.getBaseURL(service), timeoutSecs: params.request.timeOutSeconds || this.timeOutSeconds, type: "jsonp" });
retVal = transport.send(action + postfix, params.request, handleAs === "text" ? "text" : "json");
} else {
const transport = new hpccComms.Connection({ baseUrl: this.getBaseURL(service), timeoutSecs: params.request.timeOutSeconds || this.timeOutSeconds });
retVal = transport.send(action + postfix, params.request, handleAs === "text" ? "text" : "json");
}
return retVal.then(function (response) {
if (lang.exists("Exceptions.Exception", response)) {
if (response.Exceptions.Exception.Code === "401") {
if (cookie("Status") === "Unlocked") {
topic.publish("hpcc/session_management_status", {
status: "DoIdle"
});
}
cookie("Status", "Locked");
ESPUtil.LocalStorage.removeItem("Status");
}
}
params.load(response);
return response;
}).catch(function (error) {
params.error(error);
return error;
});
}
send(service, action, params?): Promise<any> {
if (!this.isSessionCall(service, action) && (!this.hasServerSetCookie() || (this.hasAuthentication() && !this.isAuthenticated()))) {
// @ts-ignore
window.location.reload(true);
return new Promise((resolve, reject) => { });
}
if (this.isLocked()) {
topic.publish("hpcc/brToaster", {
Severity: "Error",
Source: service + "." + action,
Exceptions: [{ Message: "<h3>Session is Locked<h3>" }]
});
return Promise.resolve({});
}
if (!params)
params = {};
const handleAs = params.handleAs ? params.handleAs : "json";
return this._send(service, action, params).then(function (response) {
if (handleAs === "json") {
if (lang.exists("Exceptions.Source", response) && !params.skipExceptions) {
let severity = params.suppressExceptionToaster ? "Info" : "Error";
const source = service + "." + action;
if (lang.exists("Exceptions.Exception", response) && response.Exceptions.Exception.length === 1) {
switch (source) {
case "WsWorkunits.WUInfo":
if (response.Exceptions.Exception[0].Code === 20080) {
severity = "Info";
}
break;
case "WsWorkunits.WUQuery":
if (response.Exceptions.Exception[0].Code === 20081) {
severity = "Info";
}
break;
case "WsWorkunits.WUCDebug":
if (response.Exceptions.Exception[0].Code === -10) {
severity = "Info";
}
break;
case "FileSpray.GetDFUWorkunit":
if (response.Exceptions.Exception[0].Code === 20080) {
severity = "Info";
}
break;
case "WsDfu.DFUInfo":
if (response.Exceptions.Exception[0].Code === 20038) {
severity = "Info";
}
break;
case "WsWorkunits.WUUpdate":
if (response.Exceptions.Exception[0].Code === 20049) {
severity = "Error";
}
break;
}
}
topic.publish("hpcc/brToaster", {
Severity: severity,
Source: source,
Exceptions: response.Exceptions.Exception
});
}
}
return response;
},
function (error) {
let message = "Unknown Error";
if (lang.exists("response.text", error)) {
message = error.response.text;
} else if (error.message && error.stack) {
message = "<h3>" + error.message + "</h3>";
message += "<p>" + error.stack + "</p>";
}
topic.publish("hpcc/brToaster", {
Severity: "Error",
Source: service + "." + action,
Exceptions: [{ Message: message }]
});
return error;
});
}
// XML to JSON helpers ---
getValue(domXml, tagName, knownObjectArrays) {
const retVal = this.getValues(domXml, tagName, knownObjectArrays);
if (retVal.length === 0) {
return null;
} else if (retVal.length !== 1) {
alert("Invalid length: " + retVal.length);
}
return retVal[0];
}
getValues(domXml, tagName, knownObjectArrays) {
const retVal = [];
const items = domXml.getElementsByTagName(tagName);
const parentNode = items.length ? items[0].parentNode : null; // Prevent <Dataset><row><field><row> scenario
for (let i = 0; i < items.length; ++i) {
if (items[i].parentNode === parentNode)
retVal.push(this.flattenXml(items[i], knownObjectArrays));
}
return retVal;
}
flattenXml(domXml, knownObjectArrays) {
const retValArr = [];
let retValStr = "";
const retVal = {};
for (let i = 0; i < domXml.childNodes.length; ++i) {
const childNode = domXml.childNodes[i];
if (childNode.childNodes) {
if (childNode.nodeName && knownObjectArrays != null && dojo.indexOf(knownObjectArrays, childNode.nodeName) >= 0) {
retValArr.push(this.flattenXml(childNode, knownObjectArrays));
} else if (childNode.nodeName === "#text") {
retValStr += childNode.nodeValue;
} else if (childNode.childNodes.length === 0) {
retVal[childNode.nodeName] = null;
} else {
const value = this.flattenXml(childNode, knownObjectArrays);
if (retVal[childNode.nodeName] == null) {
retVal[childNode.nodeName] = value;
} else if (dojo.isArray(retVal[childNode.nodeName])) {
retVal[childNode.nodeName].push(value);
} else if (dojo.isObject(retVal[childNode.nodeName])) {
const tmp = retVal[childNode.nodeName];
retVal[childNode.nodeName] = [];
retVal[childNode.nodeName].push(tmp);
retVal[childNode.nodeName].push(value);
}
}
}
}
if (retValArr.length)
return retValArr;
else if (retValStr.length)
return retValStr;
return retVal;
}
}
const _StoreSingletons = [];
export function getURL(_params) {
const requestHelper = new RequestHelper();
const params = lang.mixin({
protocol: location.protocol,
hostname: requestHelper.serverIP ? requestHelper.serverIP : location.hostname,
port: location.port,
pathname: ""
}, _params);
return params.protocol + "//" + params.hostname + ":" + params.port + params.pathname;
}
export function flattenArray(target, arrayName, arrayID) {
if (lang.exists(arrayName + ".length", target)) {
const tmp = {};
for (let i = 0; i < target[arrayName].length; ++i) {
tmp[arrayName + "_i" + i] = target[arrayName][i][arrayID];
}
delete target[arrayName];
return lang.mixin(target, tmp);
}
return target;
}
export function flattenMap(target, arrayName, _singularName?, supressAppName?, excludeEmptyValues?) {
if (lang.exists(arrayName, target)) {
const appData = target[arrayName];
delete target[arrayName];
const singularName = _singularName ? _singularName : arrayName.substr(0, arrayName.length - 1);
let i = 0;
for (const key in appData) {
if (excludeEmptyValues && (!appData[key] || appData[key] === "")) {
continue;
}
if (!supressAppName) {
target[arrayName + "." + singularName + "." + i + ".Application"] = "ESPRequest.js";
}
target[arrayName + "." + singularName + "." + i + ".Name"] = key;
target[arrayName + "." + singularName + "." + i + ".Value"] = appData[key];
++i;
}
target[arrayName + "." + singularName + ".itemcount"] = i;
}
return target;
}
export function getBaseURL(service?) {
const helper = new RequestHelper();
return helper.getBaseURL(service);
}
export function send(service, action, params?) {
const helper = new RequestHelper();
return helper.send(service, action, params);
}
export abstract class Store {
abstract service: string;
abstract action: string;
abstract responseQualifier: string;
abstract responseTotalQualifier: string;
abstract idProperty: string;
startProperty: string;
countProperty: string;
SortbyProperty = "Sortby";
DescendingProperty = "Descending";
useSingletons = true;
cachedArray = {};
constructor(options?) {
// TODO Remove Options
if (options) {
declare.safeMixin(this, options);
}
}
notify(itme, id) {
// Overriden by Observable
}
preRequest(request: any) { }
preProcessFullResponse(response, request, query, options) { }
preProcessResponse(response, request, query, options) { }
preProcessRow(item, request, query, options) { }
postProcessResults(items) { }
endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
getIdentity(item) {
return item[this.idProperty];
}
getCachedArray(create) {
return this.useSingletons ? lang.getObject(this.service + "." + this.action, create, _StoreSingletons) : this.cachedArray;
}
exists(id) {
const cachedArray = this.getCachedArray(false);
if (cachedArray) {
return cachedArray[id] !== undefined;
}
return false;
}
get(id, item?) {
if (!this.exists(id)) {
const cachedArray = this.getCachedArray(true);
cachedArray[id] = this.create(id, item);
return cachedArray[id];
}
const cachedArray = this.getCachedArray(false);
return cachedArray[id];
}
create(id, item) {
const retVal = {
};
retVal[this.idProperty] = id;
return retVal;
}
update(id, item) {
lang.mixin(this.get(id), item);
}
remove(id) {
const cachedArray = this.getCachedArray(false);
if (cachedArray) {
delete cachedArray[id];
}
}
_hasResponseContent(response) {
return lang.exists(this.responseQualifier, response);
}
_getResponseContent(response) {
return lang.getObject(this.responseQualifier, false, response);
}
query(query, options) {
const request = query;
if (options !== undefined && options.start !== undefined && options.count !== undefined) {
if (this.startProperty) {
request[this.startProperty] = options.start;
}
if (this.countProperty) {
request[this.countProperty] = options.count;
}
}
if (options !== undefined && options.sort !== undefined && options.sort[0].attribute !== undefined) {
request[this.SortbyProperty] = options.sort[0].attribute;
request[this.DescendingProperty] = options.sort[0].descending ? true : false;
}
if (this.preRequest) {
this.preRequest(request);
}
const deferredResults = new Deferred();
deferredResults.total = new Deferred();
const helper = new RequestHelper();
const context = this;
helper.send(this.service, this.action, {
request
}).then(function (response) {
if (context.preProcessFullResponse) {
context.preProcessFullResponse(response, request, query, options);
}
const items = [];
if (context._hasResponseContent(response)) {
if (context.preProcessResponse) {
const responseQualiferArray = context.responseQualifier.split(".");
context.preProcessResponse(lang.getObject(responseQualiferArray[0], false, response), request, query, options);
}
arrayUtil.forEach(context._getResponseContent(response), function (item, index) {
if (context.preProcessRow) {
context.preProcessRow(item, request, query, options);
}
const storeItem = context.get(context.getIdentity(item), item);
context.update(context.getIdentity(item), item);
items.push(storeItem);
});
}
if (context.postProcessResults) {
context.postProcessResults(items);
}
if (context.responseTotalQualifier) {
deferredResults.total.resolve(lang.getObject(context.responseTotalQualifier, false, response));
} else if (context._hasResponseContent(response)) {
deferredResults.total.resolve(items.length);
} else {
deferredResults.total.resolve(0);
}
deferredResults.resolve(items);
return response;
});
return QueryResults(deferredResults);
}
} | the_stack |
import { ParserSymbol } from './parsertokens/ParserSymbol';
import { Token } from './parsertokens/Token';
import { PrimitiveElement } from './PrimitiveElement';
import { Expression } from './Expression';
import { java } from 'j4ts/j4ts';
import { javaemul } from 'j4ts/j4ts';
import { FunctionConstants } from './FunctionConstants';
import { ArgumentConstants } from './ArgumentConstants';
import { ExpressionConstants } from './ExpressionConstants';
import { Constant } from './Constant';
import { HeadEqBody } from './Miscellaneous';
import { Argument } from './Argument';
import { mXparserConstants } from './mXparserConstants';
import { FunctionExtensionVariadic } from './FunctionExtensionVariadic';
import { FunctionExtension } from './FunctionExtension';
/**
* Constructor - creates function from function name
* and function expression string.
*
* @param {string} functionName the function name
* @param {string} functionExpressionString the function expression string
* @param {org.mariuszgromada.math.mxparser.PrimitiveElement[]} elements Optional elements list (variadic - comma separated) of types: Argument, Constant, Function
*
* @see PrimitiveElement
* @see Expression
* @class
* @extends PrimitiveElement
*/
export class Function extends PrimitiveElement {
public static createWithFunctionDefinition(functionDefinition : string) : Function {
const newFunction : Function = new Function(null, null, null);
if (mXparserConstants.regexMatch(functionDefinition, ParserSymbol.functionDefStrRegExp_$LI$())) {
const headEqBody = new HeadEqBody(functionDefinition);
newFunction.functionName = headEqBody.headTokens.get(0).tokenStr;
newFunction.functionExpression = <any>new Expression(headEqBody.bodyStr, null);
newFunction.functionExpression.setDescription(headEqBody.headStr);
newFunction.functionExpression.UDFExpression = true;
newFunction.isVariadic = false;
if(headEqBody.headTokens.size() > 1) {
for(let i : number = 1; i < headEqBody.headTokens.size(); i++) {
const token = headEqBody.headTokens.get(i);
if(token.tokenTypeId !== ParserSymbol.TYPE_ID) {
newFunction.functionExpression.addArguments(Argument.createArgumentWithName(token.tokenStr));
}
}
}
newFunction.parametersNumber = newFunction.functionExpression.getArgumentsNumber()
- newFunction.countRecursiveArguments();
newFunction.setDescription("");
newFunction.functionBodyType = FunctionConstants.BODY_RUNTIME;
newFunction.addFunctions(newFunction);
}
else if (mXparserConstants.regexMatch(functionDefinition, ParserSymbol.functionVariadicDefStrRegExp_$LI$())) {
const headEqBody = new HeadEqBody(functionDefinition);
newFunction.functionName = headEqBody.headTokens.get(0).tokenStr;
newFunction.functionExpression = <any>new Expression(headEqBody.bodyStr, null);
newFunction.functionExpression.setDescription(headEqBody.headStr);
newFunction.functionExpression.UDFExpression = true;
newFunction.isVariadic = true;
newFunction.parametersNumber = -1;
newFunction.setDescription("");
newFunction.functionBodyType = FunctionConstants.BODY_RUNTIME;
newFunction.addFunctions(newFunction);
}
else {
newFunction.functionExpression.setDescription(functionDefinition);
let errorMessage :string = "";
errorMessage = errorMessage + "\n [" + functionDefinition + "] " +
"--> pattern not mathes: f(x1,...,xn) = ... reg exp: " +
ParserSymbol.functionDefStrRegExp;
newFunction.functionExpression.setSyntaxStatus(ExpressionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN, errorMessage);
}
return newFunction;
}
/**
* Function body type.
*
* @see Function#BODY_RUNTIME
* @see Function#BODY_EXTENDED
* @see Function#getFunctionBodyType()
*/
/*private*/ functionBodyType: number;
/**
* function expression
*/
functionExpression: Expression;
/**
* function name
*/
/*private*/ functionName: string;
/**
* function description
*/
/*private*/ description: string;
/**
* Indicates whether UDF is variadic
*/
isVariadic: boolean;
/**
* The number of function parameters
*/
/*private*/ parametersNumber: number;
/**
* Function extension (body based in code)
*
* @see FunctionExtension
* @see FunctionExtensionVariadic
* @see Function#Function(String, FunctionExtension)
*/
/*private*/ functionExtension: FunctionExtension;
/**
* Function extension variadic (body based in code)
*
* @see FunctionExtension
* @see FunctionExtensionVariadic
* @see Function#Function(String, FunctionExtension)
*/
/*private*/ functionExtensionVariadic: FunctionExtensionVariadic;
public constructor(functionName?: any, functionExpressionString?: any, ...elements: any[]) {
if(functionExpressionString !== null && functionExpressionString !== undefined &&
((typeof functionExpressionString === 'string') || functionExpressionString.constructor.name === 'String')) {
functionExpressionString = <string>functionExpressionString.split(' ').join('');
}
if (((typeof functionName === 'string') || functionName === null) && ((typeof functionExpressionString === 'string') || functionExpressionString === null) && ((elements != null && elements instanceof <any>Array && (elements.length == 0 || elements[0] == null || (elements[0] != null && elements[0] instanceof <any>PrimitiveElement))) || elements === null)) {
let __args = arguments;
super(FunctionConstants.TYPE_ID);
if (this.functionBodyType === undefined) { this.functionBodyType = 0; }
if (this.functionExpression === undefined) { this.functionExpression = null; }
if (this.functionName === undefined) { this.functionName = null; }
if (this.description === undefined) { this.description = null; }
if (this.isVariadic === undefined) { this.isVariadic = false; }
if (this.parametersNumber === undefined) { this.parametersNumber = 0; }
if (this.functionExtension === undefined) { this.functionExtension = null; }
if (this.functionExtensionVariadic === undefined) { this.functionExtensionVariadic = null; }
if (functionName !== null && mXparserConstants.regexMatch(functionName, ParserSymbol.nameOnlyTokenRegExp)) {
this.functionName = functionName;
this.functionExpression = <any>new Expression(functionExpressionString, elements);
this.functionExpression.setDescription(functionName);
this.functionExpression.UDFExpression = true;
this.isVariadic = false;
this.parametersNumber = 0;
this.description = "";
this.functionBodyType = FunctionConstants.BODY_RUNTIME;
this.addFunctions(this);
} else {
this.parametersNumber = 0;
this.description = "";
this.functionExpression = Expression.create();
this.functionExpression.setSyntaxStatus(FunctionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + functionName + "]Invalid function name, pattern not matches: " + ParserSymbol.nameTokenRegExp_$LI$());
}
} else if (((typeof functionName === 'string') || functionName === null) && ((typeof functionExpressionString === 'string') || functionExpressionString === null) && ((elements != null && elements instanceof <any>Array && (elements.length == 0 || elements[0] == null || (typeof elements[0] === 'string'))) || elements === null)) {
let __args = elements;
let argumentsNames: any[] = __args;
super(FunctionConstants.TYPE_ID);
if (this.functionBodyType === undefined) { this.functionBodyType = 0; }
if (this.functionExpression === undefined) { this.functionExpression = null; }
if (this.functionName === undefined) { this.functionName = null; }
if (this.description === undefined) { this.description = null; }
if (this.isVariadic === undefined) { this.isVariadic = false; }
if (this.parametersNumber === undefined) { this.parametersNumber = 0; }
if (this.functionExtension === undefined) { this.functionExtension = null; }
if (this.functionExtensionVariadic === undefined) { this.functionExtensionVariadic = null; }
if (functionName !== null && mXparserConstants.regexMatch(functionName, ParserSymbol.nameOnlyTokenRegExp)) {
this.functionName = functionName;
this.functionExpression = Expression.createWithExpression(functionExpressionString);
this.functionExpression.setDescription(functionName);
this.functionExpression.UDFExpression = true;
this.isVariadic = false;
for (let index197 = 0; index197 < argumentsNames.length; index197++) {
let argName = argumentsNames[index197];
this.functionExpression.addArguments(new Argument(argName))
}
this.parametersNumber = this.functionExpression.getArgumentsNumber() - this.countRecursiveArguments();
this.description = "";
this.functionBodyType = FunctionConstants.BODY_RUNTIME;
this.addFunctions(this);
} else {
this.parametersNumber = 0;
this.description = "";
this.functionExpression = Expression.create();
this.functionExpression.setSyntaxStatus(FunctionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + functionName + "]Invalid function name, pattern not matches: " + ParserSymbol.nameTokenRegExp_$LI$());
}
} else if (((typeof functionName === 'string') || functionName === null) && ((functionExpressionString != null && functionExpressionString instanceof <any>Array && (functionExpressionString.length == 0 || functionExpressionString[0] == null || (functionExpressionString[0] != null && functionExpressionString[0] instanceof <any>PrimitiveElement))) || functionExpressionString === null) && elements === undefined || elements.length === 0) {
let __args = arguments;
let functionDefinitionString: any = __args[0];
let elements: any[] = __args[1];
super(FunctionConstants.TYPE_ID);
if (this.functionBodyType === undefined) { this.functionBodyType = 0; }
if (this.functionExpression === undefined) { this.functionExpression = null; }
if (this.functionName === undefined) { this.functionName = null; }
if (this.description === undefined) { this.description = null; }
if (this.isVariadic === undefined) { this.isVariadic = false; }
if (this.parametersNumber === undefined) { this.parametersNumber = 0; }
if (this.functionExtension === undefined) { this.functionExtension = null; }
if (this.functionExtensionVariadic === undefined) { this.functionExtensionVariadic = null; }
this.parametersNumber = 0;
if (functionDefinitionString !== null && mXparserConstants.regexMatch(functionDefinitionString, ParserSymbol.functionDefStrRegExp_$LI$())) {
const headEqBody: HeadEqBody = new HeadEqBody(functionDefinitionString);
this.functionName = headEqBody.headTokens.get(0).tokenStr;
this.functionExpression = Expression.createWithExpression(headEqBody.bodyStr);
this.functionExpression.setDescription(headEqBody.headStr);
this.functionExpression.UDFExpression = true;
this.isVariadic = false;
if (headEqBody.headTokens.size() > 1) {
let t: Token;
for (let i: number = 1; i < headEqBody.headTokens.size(); i++) {
{
t = headEqBody.headTokens.get(i);
if (t.tokenTypeId !== ParserSymbol.TYPE_ID) this.functionExpression.addArguments(new Argument(t.tokenStr));
};
}
}
this.parametersNumber = this.functionExpression.getArgumentsNumber() - this.countRecursiveArguments();
this.description = "";
this.functionBodyType = FunctionConstants.BODY_RUNTIME;
this.addFunctions(this);
} else if (functionDefinitionString !== null && mXparserConstants.regexMatch(functionDefinitionString, ParserSymbol.functionVariadicDefStrRegExp_$LI$())) {
const headEqBody: HeadEqBody = new HeadEqBody(functionDefinitionString);
this.functionName = headEqBody.headTokens.get(0).tokenStr;
this.functionExpression = <any>new Expression(headEqBody.bodyStr, elements);
this.functionExpression.setDescription(headEqBody.headStr);
this.functionExpression.UDFExpression = true;
this.isVariadic = true;
this.parametersNumber = -1;
this.description = "";
this.functionBodyType = FunctionConstants.BODY_RUNTIME;
this.addFunctions(this);
} else {
this.functionExpression = new Expression();
this.functionExpression.setDescription(functionDefinitionString);
let errorMessage: string = "";
errorMessage = errorMessage + "\n [" + functionDefinitionString + "] --> pattern not mathes: f(x1,...,xn) = ... reg exp: " + ParserSymbol.functionDefStrRegExp_$LI$();
this.functionExpression.setSyntaxStatus(ExpressionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN, errorMessage);
}
} else if (((typeof functionName === 'string') || functionName === null) && ((functionExpressionString != null && (functionExpressionString.constructor != null && functionExpressionString.constructor["__interfaces"] != null && functionExpressionString.constructor["__interfaces"].indexOf("org.mariuszgromada.math.mxparser.FunctionExtension") >= 0)) || functionExpressionString === null) && elements === undefined || elements.length === 0) {
let __args = arguments;
let functionExtension: any = __args[1];
super(FunctionConstants.TYPE_ID);
if (this.functionBodyType === undefined) { this.functionBodyType = 0; }
if (this.functionExpression === undefined) { this.functionExpression = null; }
if (this.functionName === undefined) { this.functionName = null; }
if (this.description === undefined) { this.description = null; }
if (this.isVariadic === undefined) { this.isVariadic = false; }
if (this.parametersNumber === undefined) { this.parametersNumber = 0; }
if (this.functionExtension === undefined) { this.functionExtension = null; }
if (this.functionExtensionVariadic === undefined) { this.functionExtensionVariadic = null; }
if (functionName !== null && mXparserConstants.regexMatch(functionName, ParserSymbol.nameOnlyTokenRegExp)) {
this.functionName = functionName;
this.functionExpression = new Expression("{body-ext}");
this.isVariadic = false;
this.parametersNumber = functionExtension.getParametersNumber();
this.description = "";
this.functionExtension = functionExtension;
this.functionBodyType = FunctionConstants.BODY_EXTENDED;
} else {
this.parametersNumber = 0;
this.description = "";
this.functionExpression = new Expression("");
this.functionExpression.setSyntaxStatus(FunctionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + functionName + "]Invalid function name, pattern not matches: " + ParserSymbol.nameTokenRegExp_$LI$());
}
} else if (((typeof functionName === 'string') || functionName === null) && ((functionExpressionString != null && (functionExpressionString.constructor != null && functionExpressionString.constructor["__interfaces"] != null && functionExpressionString.constructor["__interfaces"].indexOf("org.mariuszgromada.math.mxparser.FunctionExtensionVariadic") >= 0)) || functionExpressionString === null) && elements === undefined || elements.length === 0) {
let __args = arguments;
let functionExtensionVariadic: any = __args[1];
super(FunctionConstants.TYPE_ID);
if (this.functionBodyType === undefined) { this.functionBodyType = 0; }
if (this.functionExpression === undefined) { this.functionExpression = null; }
if (this.functionName === undefined) { this.functionName = null; }
if (this.description === undefined) { this.description = null; }
if (this.isVariadic === undefined) { this.isVariadic = false; }
if (this.parametersNumber === undefined) { this.parametersNumber = 0; }
if (this.functionExtension === undefined) { this.functionExtension = null; }
if (this.functionExtensionVariadic === undefined) { this.functionExtensionVariadic = null; }
if (functionName !== null && mXparserConstants.regexMatch(functionName, ParserSymbol.nameOnlyTokenRegExp)) {
this.functionName = functionName;
this.functionExpression = new Expression("{body-ext-var}");
this.isVariadic = true;
this.parametersNumber = -1;
this.description = "";
this.functionExtensionVariadic = functionExtensionVariadic;
this.functionBodyType = FunctionConstants.BODY_EXTENDED;
} else {
this.parametersNumber = 0;
this.description = "";
this.functionExpression = new Expression("");
this.functionExpression.setSyntaxStatus(FunctionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + functionName + "]Invalid function name, pattern not matches: " + ParserSymbol.nameTokenRegExp_$LI$());
}
} else if (((functionName != null && functionName instanceof <any>Function) || functionName === null) && functionExpressionString === undefined && elements === undefined || elements.length === 0) {
let __args = arguments;
let __function: any = __args[0];
super(FunctionConstants.TYPE_ID);
if (this.functionBodyType === undefined) { this.functionBodyType = 0; }
if (this.functionExpression === undefined) { this.functionExpression = null; }
if (this.functionName === undefined) { this.functionName = null; }
if (this.description === undefined) { this.description = null; }
if (this.isVariadic === undefined) { this.isVariadic = false; }
if (this.parametersNumber === undefined) { this.parametersNumber = 0; }
if (this.functionExtension === undefined) { this.functionExtension = null; }
if (this.functionExtensionVariadic === undefined) { this.functionExtensionVariadic = null; }
this.functionName = __function.functionName;
this.description = __function.description;
this.parametersNumber = __function.parametersNumber;
this.functionExpression = /* clone */((o: any) => { if (o.clone != undefined) { return (<any>o).clone(); } else { let clone = Object.create(o); for (let p in o) { if (o.hasOwnProperty(p)) clone[p] = o[p]; } return clone; } })(__function.functionExpression);
this.functionBodyType = __function.functionBodyType;
this.isVariadic = __function.isVariadic;
if (this.functionBodyType === FunctionConstants.BODY_EXTENDED) {
if (__function.functionExtension != null) this.functionExtension = /* clone */((o: any) => { if (o.clone != undefined) { return (<any>o).clone(); } else { let clone = Object.create(o); for (let p in o) { if (o.hasOwnProperty(p)) clone[p] = o[p]; } return clone; } })(__function.functionExtension);
if (__function.functionExtensionVariadic != null) this.functionExtensionVariadic = /* clone */((o: any) => { if (o.clone != undefined) { return (<any>o).clone(); } else { let clone = Object.create(o); for (let p in o) { if (o.hasOwnProperty(p)) clone[p] = o[p]; } return clone; } })(__function.functionExtensionVariadic);
}
} else throw new Error('invalid overload');
}
/**
* Constructor for function definition in natural math language,
* for instance providing on string "f(x,y) = sin(x) + cos(x)"
* is enough to define function "f" with parameters "x and y"
* and function body "sin(x) + cos(x)".
*
* @param {string} functionDefinitionString Function definition in the form
* of one String, ie "f(x,y) = sin(x) + cos(x)"
* @param {org.mariuszgromada.math.mxparser.PrimitiveElement[]} elements Optional elements list (variadic - comma separated)
* of types: Argument, Constant, Function
*
* @see PrimitiveElement
*/
public setFunction(functionDefinitionString: string, ...elements: PrimitiveElement[]) {
this.parametersNumber = 0;
if (mXparserConstants.regexMatch(functionDefinitionString, ParserSymbol.functionDefStrRegExp_$LI$())) {
const headEqBody: HeadEqBody = new HeadEqBody(functionDefinitionString);
this.functionName = headEqBody.headTokens.get(0).tokenStr;
this.functionExpression = <any>new Expression(headEqBody.bodyStr, elements);
this.functionExpression.setDescription(headEqBody.headStr);
this.functionExpression.UDFExpression = true;
this.isVariadic = false;
if (headEqBody.headTokens.size() > 1) {
let t: Token;
for (let i: number = 1; i < headEqBody.headTokens.size(); i++) {
{
t = headEqBody.headTokens.get(i);
if (t.tokenTypeId !== ParserSymbol.TYPE_ID) this.functionExpression.addArguments(new Argument(t.tokenStr));
};
}
}
this.parametersNumber = this.functionExpression.getArgumentsNumber() - this.countRecursiveArguments();
this.description = "";
this.functionBodyType = FunctionConstants.BODY_RUNTIME;
this.addFunctions(this);
} else if (mXparserConstants.regexMatch(functionDefinitionString, ParserSymbol.functionVariadicDefStrRegExp_$LI$())) {
const headEqBody: HeadEqBody = new HeadEqBody(functionDefinitionString);
this.functionName = headEqBody.headTokens.get(0).tokenStr;
this.functionExpression = <any>new Expression(headEqBody.bodyStr, elements);
this.functionExpression.setDescription(headEqBody.headStr);
this.functionExpression.UDFExpression = true;
this.isVariadic = true;
this.parametersNumber = -1;
this.description = "";
this.functionBodyType = FunctionConstants.BODY_RUNTIME;
this.addFunctions(this);
} else {
this.functionExpression = new Expression();
this.functionExpression.setDescription(functionDefinitionString);
let errorMessage: string = "";
errorMessage = errorMessage + "\n [" + functionDefinitionString + "] --> pattern not mathes: f(x1,...,xn) = ... reg exp: " + ParserSymbol.functionDefStrRegExp_$LI$();
this.functionExpression.setSyntaxStatus(ExpressionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN, errorMessage);
}
}
/**
* Sets function description.
*
* @param {string} description the function description
*/
public setDescription(description: string) {
this.description = description;
}
/**
* Gets function description
*
* @return {string} Function description as string
*/
public getDescription(): string {
return this.description;
}
/**
* Gets function name.
*
* @return {string} Function name as string.
*/
public getFunctionName(): string {
return this.functionName;
}
/**
* Gets function expression string
*
* @return {string} Function expression as string.
*/
public getFunctionExpressionString(): string {
return this.functionExpression.getExpressionString();
}
/**
* Sets function name.
*
* @param {string} functionName the function name
*/
public setFunctionName(functionName: string) {
if (mXparserConstants.regexMatch(functionName, ParserSymbol.nameOnlyTokenRegExp)) {
this.functionName = functionName;
this.setExpressionModifiedFlags();
} else this.functionExpression.setSyntaxStatus(FunctionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + functionName + "]Invalid function name, pattern not matches: " + ParserSymbol.nameTokenRegExp_$LI$());
}
/**
* Sets value of function argument (function parameter).
*
* @param {number} argumentIndex the argument index (in accordance to
* arguments declaration sequence)
* @param {number} argumentValue the argument value
*/
public setArgumentValue(argumentIndex: number, argumentValue: number) {
if (this.isVariadic === false) if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) this.functionExpression.argumentsList.get(argumentIndex).argumentValue = argumentValue; else if (this.isVariadic === false) this.functionExtension.setParameterValue(argumentIndex, argumentValue);
}
/**
* Returns function body type: {@link Function#BODY_RUNTIME} {@link Function#BODY_EXTENDED}
* @return {number} Returns function body type: {@link Function#BODY_RUNTIME} {@link Function#BODY_EXTENDED}
*/
public getFunctionBodyType(): number {
return this.functionBodyType;
}
/**
* Checks function syntax
*
* @return {boolean} syntax status: FunctionConstants.NO_SYNTAX_ERRORS,
* FunctionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN
*/
public checkSyntax(): boolean {
let syntaxStatus: boolean = FunctionConstants.NO_SYNTAX_ERRORS_$LI$();
if (this.functionBodyType !== FunctionConstants.BODY_EXTENDED) syntaxStatus = this.functionExpression.checkSyntax$();
this.checkRecursiveMode();
return syntaxStatus;
}
/**
* Returns error message after checking the syntax.
*
* @return {string} Error message as string.
*/
public getErrorMessage(): string {
return this.functionExpression.getErrorMessage();
}
/**
* clone method
* @return {Function}
*/
clone(): Function {
const newFunction: Function = new Function(null,null, null);
newFunction.functionName = this.functionName;
newFunction.description = this.description;
newFunction.parametersNumber = this.parametersNumber;
newFunction.functionExpression = this.functionExpression.clone();
newFunction.functionBodyType = this.functionBodyType;
newFunction.isVariadic = this.isVariadic;
if(this.functionBodyType === FunctionConstants.BODY_EXTENDED) {
if(this.functionExtension !== null) newFunction.functionExtension = this.functionExtension.clone();
if(this.functionExtensionVariadic !== null) newFunction.functionExtensionVariadic = this.functionExtensionVariadic.clone();
}
return newFunction;
}
public calculate$(): number {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.calculate(); else if (this.isVariadic === false) return this.functionExtension.calculate(); else {
const paramsList: java.util.List<number> = this.functionExpression.UDFVariadicParamsAtRunTime;
if (paramsList != null) {
const n: number = paramsList.size();
const parameters: number[] = (s => { let a = []; while (s-- > 0) a.push(0); return a; })(n);
for (let i: number = 0; i < n; i++) { parameters[i] = paramsList.get(i); }
return (o => o.calculate.apply(o, parameters))(this.functionExtensionVariadic);
} else return javaemul.internal.DoubleHelper.NaN;
}
}
public calculate$double_A(...parameters: number[]): number {
if (parameters.length > 0) {
this.functionExpression.UDFVariadicParamsAtRunTime = <any>(new java.util.ArrayList<number>());
for (let index198 = 0; index198 < parameters.length; index198++) {
let x = parameters[index198];
this.functionExpression.UDFVariadicParamsAtRunTime.add(x)
}
} else return javaemul.internal.DoubleHelper.NaN;
if (this.isVariadic) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.calculate(); else return (o => o.calculate.apply(o, parameters))(this.functionExtensionVariadic);
} else if (parameters.length === this.getParametersNumber()) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) {
for (let p: number = 0; p < parameters.length; p++) { this.setArgumentValue(p, parameters[p]); }
return this.functionExpression.calculate();
} else {
for (let p: number = 0; p < parameters.length; p++) { this.functionExtension.setParameterValue(p, parameters[p]); }
return this.functionExtension.calculate();
}
} else {
this.functionExpression.setSyntaxStatus(FunctionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + this.functionName + "] incorrect number of function parameters (expecting " + this.getParametersNumber() + ", provided " + parameters.length + ")!");
return javaemul.internal.DoubleHelper.NaN;
}
}
/**
* Calculates function value
*
* @param {double[]} parameters the function parameters values (as doubles)
*
* @return {number} function value as double.
*/
public calculate(...parameters: any[]): any {
if (((parameters != null && parameters instanceof <any>Array && (parameters.length == 0 || parameters[0] == null || (typeof parameters[0] === 'number'))) || parameters === null)) {
return <any>this.calculate$double_A(...parameters);
} else if (((parameters != null && parameters instanceof <any>Array && (parameters.length == 0 || parameters[0] == null || (parameters[0] != null && parameters[0] instanceof <any>Argument))) || parameters === null)) {
return <any>this.calculate$org_mariuszgromada_math_mxparser_Argument_A(...parameters);
} else if (parameters === undefined || parameters.length === 0) {
return <any>this.calculate$();
} else throw new Error('invalid overload');
}
public calculate$org_mariuszgromada_math_mxparser_Argument_A(...__arguments: Argument[]): number {
let parameters: number[];
if (__arguments.length > 0) {
this.functionExpression.UDFVariadicParamsAtRunTime = <any>(new java.util.ArrayList<number>());
parameters = (s => { let a = []; while (s-- > 0) a.push(0); return a; })(__arguments.length);
let x: number;
for (let i: number = 0; i < __arguments.length; i++) {
{
x = __arguments[i].getArgumentValue();
this.functionExpression.UDFVariadicParamsAtRunTime.add(x);
parameters[i] = x;
};
}
} else return javaemul.internal.DoubleHelper.NaN;
if (this.isVariadic) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.calculate(); else return (o => o.calculate.apply(o, parameters))(this.functionExtensionVariadic);
} else if (__arguments.length === this.getParametersNumber()) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) {
for (let p: number = 0; p < __arguments.length; p++) { this.setArgumentValue(p, __arguments[p].getArgumentValue()); }
return this.functionExpression.calculate();
} else {
for (let p: number = 0; p < __arguments.length; p++) { this.functionExtension.setParameterValue(p, __arguments[p].getArgumentValue()); }
return this.functionExtension.calculate();
}
} else {
this.functionExpression.setSyntaxStatus(FunctionConstants.SYNTAX_ERROR_OR_STATUS_UNKNOWN_$LI$(), "[" + this.functionName + "] incorrect number of function parameters (expecting " + this.getParametersNumber() + ", provided " + __arguments.length + ")!");
return javaemul.internal.DoubleHelper.NaN;
}
}
/**
* Adds user defined elements (such as: Arguments, Constants, Functions)
* to the function expressions.
*
* @param {org.mariuszgromada.math.mxparser.PrimitiveElement[]} elements Elements list (variadic), where Argument, Constant, Function
* extend the same class PrimitiveElement
*
* @see PrimitiveElement
*/
public addDefinitions(...elements: PrimitiveElement[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) (o => o.addDefinitions.apply(o, elements))(this.functionExpression);
}
/**
* Removes user defined elements (such as: Arguments, Constants, Functions)
* from the function expressions.
*
* @param {org.mariuszgromada.math.mxparser.PrimitiveElement[]} elements Elements list (variadic), where Argument, Constant, Function
* extend the same class PrimitiveElement
*
* @see PrimitiveElement
*/
public removeDefinitions(...elements: PrimitiveElement[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) (o => o.removeDefinitions.apply(o, elements))(this.functionExpression);
}
/*private*/ countRecursiveArguments(): number {
let numOfRecursiveArguments: number = 0;
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) for (let index199 = this.functionExpression.argumentsList.iterator(); index199.hasNext();) {
let argument = index199.next();
if (argument.getArgumentType() === ArgumentConstants.RECURSIVE_ARGUMENT) numOfRecursiveArguments++;
}
return numOfRecursiveArguments;
}
/**
* Adds arguments (variadic) to the function expression definition.
*
* @param {org.mariuszgromada.math.mxparser.Argument[]} arguments the arguments list
* (comma separated list)
* @see Argument
* @see RecursiveArgument
*/
public addArguments(...__arguments: Argument[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) {
(o => o.addArguments.apply(o, __arguments))(this.functionExpression);
this.parametersNumber = this.functionExpression.getArgumentsNumber() - this.countRecursiveArguments();
}
}
/**
* Enables to define the arguments (associated with
* the function expression) based on the given arguments names.
*
* @param {java.lang.String[]} argumentsNames the arguments names (variadic)
* comma separated list
*
* @see Argument
* @see RecursiveArgument
*/
public defineArguments(...argumentsNames: string[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) {
(o => o.defineArguments.apply(o, argumentsNames))(this.functionExpression);
this.parametersNumber = this.functionExpression.getArgumentsNumber() - this.countRecursiveArguments();
}
}
/**
* Enables to define the argument (associated with the function expression)
* based on the argument name and the argument value.
*
* @param {string} argumentName the argument name
* @param {number} argumentValue the the argument value
*
* @see Argument
* @see RecursiveArgument
*/
public defineArgument(argumentName: string, argumentValue: number) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) {
this.functionExpression.defineArgument(argumentName, argumentValue);
this.parametersNumber = this.functionExpression.getArgumentsNumber() - this.countRecursiveArguments();
}
}
/**
* Gets argument index from the function expression.
*
* @param {string} argumentName the argument name
*
* @return {number} The argument index if the argument name was found,
* otherwise returns Argument.NOT_FOUND
*
* @see Argument
* @see RecursiveArgument
*/
public getArgumentIndex(argumentName: string): number {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getArgumentIndex(argumentName); else return -1;
}
public getArgument$java_lang_String(argumentName: string): Argument {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getArgument$java_lang_String(argumentName); else return null;
}
/**
* Gets argument from the function expression.
*
*
* @param {string} argumentName the argument name
*
* @return {Argument} The argument if the argument name was found,
* otherwise returns null.
*
* @see Argument
* @see RecursiveArgument
*/
public getArgument(argumentName?: any): any {
if (((typeof argumentName === 'string') || argumentName === null)) {
return <any>this.getArgument$java_lang_String(argumentName);
} else if (((typeof argumentName === 'number') || argumentName === null)) {
return <any>this.getArgument$int(argumentName);
} else throw new Error('invalid overload');
}
public getArgument$int(argumentIndex: number): Argument {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getArgument$int(argumentIndex); else return null;
}
/**
* Gets number of parameters associated with the function expression.
*
* @return {number} The number of function parameters (int >= 0)
*
* @see Argument
* @see RecursiveArgument
*/
public getParametersNumber(): number {
if (this.isVariadic === false) return this.parametersNumber; else {
if (this.functionExpression.UDFVariadicParamsAtRunTime != null) return this.functionExpression.UDFVariadicParamsAtRunTime.size(); else return -1;
}
}
/**
* Set parameters number.
*
* @param {number} parametersNumber the number of function parameters (default = number of arguments
* (less number might be specified).
*/
public setParametersNumber(parametersNumber: number) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) {
this.parametersNumber = parametersNumber;
this.functionExpression.setExpressionModifiedFlag();
}
}
/**
* Gets user defined function parameter name
*
* @param {number} parameterIndex Parameter index between 0 and n-1
* @return {string} If parameter exists returns parameters name, otherwise empty string is returned.
*/
public getParameterName(parameterIndex: number): string {
if (parameterIndex < 0) return "";
if (parameterIndex >= this.parametersNumber) return "";
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.getArgument$int(parameterIndex).getArgumentName();
if (this.functionBodyType === FunctionConstants.BODY_EXTENDED) return this.functionExtension.getParameterName(parameterIndex);
return "";
}
/**
* Gets number of arguments associated with the function expression.
*
* @return {number} The number of arguments (int >= 0)
*
* @see Argument
* @see RecursiveArgument
*/
public getArgumentsNumber(): number {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getArgumentsNumber(); else return 0;
}
public removeArguments$java_lang_String_A(...argumentsNames: string[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) {
(o => o.removeArguments.apply(o, argumentsNames))(this.functionExpression);
this.parametersNumber = this.functionExpression.getArgumentsNumber() - this.countRecursiveArguments();
}
}
/**
* Removes first occurrences of the arguments
* associated with the function expression.
*
* @param {java.lang.String[]} argumentsNames the arguments names
* (variadic parameters) comma separated
* list
*
* @see Argument
* @see RecursiveArgument
*/
public removeArguments(...argumentsNames: any[]) {
if (((argumentsNames != null && argumentsNames instanceof <any>Array && (argumentsNames.length == 0 || argumentsNames[0] == null || (typeof argumentsNames[0] === 'string'))) || argumentsNames === null)) {
return <any>this.removeArguments$java_lang_String_A(...argumentsNames);
} else if (((argumentsNames != null && argumentsNames instanceof <any>Array && (argumentsNames.length == 0 || argumentsNames[0] == null || (argumentsNames[0] != null && argumentsNames[0] instanceof <any>Argument))) || argumentsNames === null)) {
return <any>this.removeArguments$org_mariuszgromada_math_mxparser_Argument_A(...argumentsNames);
} else throw new Error('invalid overload');
}
public removeArguments$org_mariuszgromada_math_mxparser_Argument_A(...__arguments: Argument[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) {
(o => o.removeArguments.apply(o, __arguments))(this.functionExpression);
this.parametersNumber = this.functionExpression.getArgumentsNumber() - this.countRecursiveArguments();
}
}
/**
* Removes all arguments associated with the function expression.
*
* @see Argument
* @see RecursiveArgument
*/
public removeAllArguments() {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) {
this.functionExpression.removeAllArguments();
this.parametersNumber = 0;
}
}
public addConstants$org_mariuszgromada_math_mxparser_Constant_A(...constants: Constant[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) (o => o.addConstants.apply(o, constants))(this.functionExpression);
}
/**
* Adds constants (variadic parameters) to the function expression definition.
*
* @param {org.mariuszgromada.math.mxparser.Constant[]} constants the constants
* (comma separated list)
*
* @see Constant
*/
public addConstants(...constants: any[]) {
if (((constants != null && constants instanceof <any>Array && (constants.length == 0 || constants[0] == null || (constants[0] != null && constants[0] instanceof <any>Constant))) || constants === null)) {
return <any>this.addConstants$org_mariuszgromada_math_mxparser_Constant_A(...constants);
} else if (((constants != null && (constants.constructor != null && constants.constructor["__interfaces"] != null && constants.constructor["__interfaces"].indexOf("java.util.List") >= 0)) || constants === null)) {
return <any>this.addConstants$java_util_List(<any>constants);
} else throw new Error('invalid overload');
}
public addConstants$java_util_List(constantsList: java.util.List<Constant>) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) this.functionExpression.addConstants$java_util_List(constantsList);
}
/**
* Enables to define the constant (associated with
* the function expression) based on the constant name and
* constant value.
*
* @param {string} constantName the constant name
* @param {number} constantValue the constant value
*
* @see Constant
*/
public defineConstant(constantName: string, constantValue: number) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) this.functionExpression.defineConstant(constantName, constantValue);
}
/**
* Gets constant index associated with the function expression.
*
* @param {string} constantName the constant name
*
* @return {number} Constant index if constant name was found,
* otherwise return Constant.NOT_FOUND.
*
* @see Constant
*/
public getConstantIndex(constantName: string): number {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getConstantIndex(constantName); else return -1;
}
public getConstant$java_lang_String(constantName: string): Constant {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getConstant$java_lang_String(constantName); else return null;
}
/**
* Gets constant associated with the function expression.
*
* @param {string} constantName the constant name
*
* @return {Constant} Constant if constant name was found,
* otherwise return null.
*
* @see Constant
*/
public getConstant(constantName?: any): any {
if (((typeof constantName === 'string') || constantName === null)) {
return <any>this.getConstant$java_lang_String(constantName);
} else if (((typeof constantName === 'number') || constantName === null)) {
return <any>this.getConstant$int(constantName);
} else throw new Error('invalid overload');
}
public getConstant$int(constantIndex: number): Constant {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getConstant$int(constantIndex); else return null;
}
/**
* Gets number of constants associated with the function expression.
*
* @return {number} number of constants (int >= 0)
*
* @see Constant
*/
public getConstantsNumber(): number {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getConstantsNumber(); else return 0;
}
public removeConstants$java_lang_String_A(...constantsNames: string[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) (o => o.removeConstants.apply(o, constantsNames))(this.functionExpression);
}
/**
* Removes first occurrences of the constants
* associated with the function expression.
*
* @param {java.lang.String[]} constantsNames the constants names (variadic parameters)
* comma separated list
*
* @see Constant
*/
public removeConstants(...constantsNames: any[]) {
if (((constantsNames != null && constantsNames instanceof <any>Array && (constantsNames.length == 0 || constantsNames[0] == null || (typeof constantsNames[0] === 'string'))) || constantsNames === null)) {
return <any>this.removeConstants$java_lang_String_A(...constantsNames);
} else if (((constantsNames != null && constantsNames instanceof <any>Array && (constantsNames.length == 0 || constantsNames[0] == null || (constantsNames[0] != null && constantsNames[0] instanceof <any>Constant))) || constantsNames === null)) {
return <any>this.removeConstants$org_mariuszgromada_math_mxparser_Constant_A(...constantsNames);
} else throw new Error('invalid overload');
}
public removeConstants$org_mariuszgromada_math_mxparser_Constant_A(...constants: Constant[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) (o => o.removeConstants.apply(o, constants))(this.functionExpression);
}
/**
* Removes all constants
* associated with the function expression
*
* @see Constant
*/
public removeAllConstants() {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) this.functionExpression.removeAllConstants();
}
/**
* Adds functions (variadic parameters) to the function expression definition.
*
* @param {org.mariuszgromada.math.mxparser.Function[]} functions the functions
* (variadic parameters) comma separated list
*
* @see Function
*/
public addFunctions(...functions: Function[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) (o => o.addFunctions.apply(o, functions))(this.functionExpression);
}
/**
* Enables to define the function (associated with
* the function expression) based on the function name,
* function expression string and arguments names (variadic parameters).
*
* @param {string} functionName the function name
* @param {string} functionExpressionString the expression string
* @param {java.lang.String[]} argumentsNames the function arguments names
* (variadic parameters)
* comma separated list
*
* @see Function
*/
public defineFunction(functionName: string, functionExpressionString: string, ...argumentsNames: string[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) (o => o.defineFunction.apply(o, [functionName, functionExpressionString].concat(<any[]>argumentsNames)))(this.functionExpression);
}
/**
* Gets index of function associated with the function expression.
*
* @param {string} functionName the function name
*
* @return {number} Function index if function name was found,
* otherwise returns FunctionConstants.NOT_FOUND
*
* @see Function
*/
public getFunctionIndex(functionName: string): number {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getFunctionIndex(functionName); else return -1;
}
public getFunction$java_lang_String(functionName: string): Function {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getFunction$java_lang_String(functionName); else return null;
}
/**
* Gets function associated with the function expression.
*
* @param {string} functionName the function name
*
* @return {Function} Function if function name was found,
* otherwise returns null.
*
* @see Function
*/
public getFunction(functionName?: any): any {
if (((typeof functionName === 'string') || functionName === null)) {
return <any>this.getFunction$java_lang_String(functionName);
} else if (((typeof functionName === 'number') || functionName === null)) {
return <any>this.getFunction$int(functionName);
} else throw new Error('invalid overload');
}
public getFunction$int(functionIndex: number): Function {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getFunction$int(functionIndex); else return null;
}
/**
* Gets number of functions associated with the function expression.
*
* @return {number} number of functions (int >= 0)
*
* @see Function
*/
public getFunctionsNumber(): number {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) return this.functionExpression.getFunctionsNumber(); else return 0;
}
public removeFunctions$java_lang_String_A(...functionsNames: string[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) (o => o.removeFunctions.apply(o, functionsNames))(this.functionExpression);
}
/**
* Removes first occurrences of the functions
* associated with the function expression.
*
* @param {java.lang.String[]} functionsNames the functions names (variadic parameters)
* comma separated list
*
* @see Function
*/
public removeFunctions(...functionsNames: any[]) {
if (((functionsNames != null && functionsNames instanceof <any>Array && (functionsNames.length == 0 || functionsNames[0] == null || (typeof functionsNames[0] === 'string'))) || functionsNames === null)) {
return <any>this.removeFunctions$java_lang_String_A(...functionsNames);
} else if (((functionsNames != null && functionsNames instanceof <any>Array && (functionsNames.length == 0 || functionsNames[0] == null || (functionsNames[0] != null && functionsNames[0] instanceof <any>Function))) || functionsNames === null)) {
return <any>this.removeFunctions$org_mariuszgromada_math_mxparser_Function_A(...functionsNames);
} else throw new Error('invalid overload');
}
public removeFunctions$org_mariuszgromada_math_mxparser_Function_A(...functions: Function[]) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) (o => o.removeFunctions.apply(o, functions))(this.functionExpression);
}
/**
* Removes all functions
* associated with the function expression.
*
* @see Function
*/
public removeAllFunctions() {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) this.functionExpression.removeAllFunctions();
}
/**
* Enables verbose function mode
*/
public setVerboseMode() {
this.functionExpression.setVerboseMode();
}
/**
* Disables function verbose mode (sets default silent mode)
*/
public setSilentMode() {
this.functionExpression.setSilentMode();
}
/**
* Returns verbose mode status
*
* @return {boolean} true if verbose mode is on,
* otherwise returns false
*/
public getVerboseMode(): boolean {
return this.functionExpression.getVerboseMode();
}
/**
* Checks whether function name appears in function body
* if yes the recursive mode is being set
*/
checkRecursiveMode() {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) {
const functionExpressionTokens: java.util.List<Token> = this.functionExpression.getInitialTokens();
this.functionExpression.disableRecursiveMode();
if (functionExpressionTokens != null) for (let index200 = functionExpressionTokens.iterator(); index200.hasNext();) {
let t = index200.next();
if (t.tokenStr === this.functionName) {
this.functionExpression.setRecursiveMode();
break;
}
}
}
}
/**
* Gets recursive mode status
*
* @return {boolean} true if recursive mode is enabled,
* otherwise returns false
*/
public getRecursiveMode(): boolean {
return this.functionExpression.getRecursiveMode();
}
/**
* Gets computing time
*
* @return {number} computing time in seconds.
*/
public getComputingTime(): number {
return this.functionExpression.getComputingTime();
}
/**
* Adds related expression.
*
* @param {Expression} expression the related expression
*/
addRelatedExpression(expression: Expression) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) this.functionExpression.addRelatedExpression(expression);
}
/**
* Removes related expression.
*
* @param {Expression} expression the related expression
*/
removeRelatedExpression(expression: Expression) {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) this.functionExpression.removeRelatedExpression(expression);
}
/**
* Set expression modified flags in the related expressions.
*/
setExpressionModifiedFlags() {
if (this.functionBodyType === FunctionConstants.BODY_RUNTIME) this.functionExpression.setExpressionModifiedFlag();
}
}
Function["__class"] = "org.mariuszgromada.math.mxparser.Function";
var __Function = Function; | the_stack |
import * as chai from "chai"
import axios from "axios"
import * as sinon from "sinon"
import { BITBOX } from "../../lib/BITBOX"
import { Blockchain } from "../../lib/Blockchain"
import { REST_URL } from "../../lib/BITBOX"
import * as util from "util"
import { BlockHeaderResult } from "bitcoin-com-rest"
const mockData = require("./mocks/blockchain-mock")
// consts
const bitbox: BITBOX = new BITBOX()
const assert: Chai.AssertStatic = chai.assert
const blockchainMock = require("./mocks/blockchain-mock")
util.inspect.defaultOptions = {
showHidden: true,
colors: true,
depth: 3
}
describe("#Blockchain", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
describe("#BlockchainConstructor", (): void => {
it("should create instance of Blockchain", (): void => {
const blockchain: Blockchain = new Blockchain()
assert.equal(blockchain instanceof Blockchain, true)
})
it("should have a restURL property", (): void => {
const blockchain: Blockchain = new Blockchain()
assert.equal(blockchain.restURL, REST_URL)
})
})
describe("#getBlock", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = {
hash: "00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09",
confirmations: 526807,
size: 216,
height: 1000,
version: 1,
versionHex: "00000001",
merkleroot:
"fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33",
tx: ["fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33"],
time: 1232346882,
mediantime: 1232344831,
nonce: 2595206198,
bits: "1d00ffff",
difficulty: 1,
chainwork:
"000000000000000000000000000000000000000000000000000003e903e903e9",
previousblockhash:
"0000000008e647742775a230787d66fdf92c46a48c896bfbc85cdc8acc67e87d",
nextblockhash:
"00000000a2887344f8db859e372e7e4bc26b23b9de340f725afbf2edb265b4c6"
}
it("should get block by hash", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getBlock(
"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09"
)
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getBlockchainInfo", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = {
chain: "main",
blocks: 527810,
headers: 527810,
bestblockhash:
"000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0",
difficulty: 576023394804.6666,
mediantime: 1524878499,
verificationprogress: 0.9999990106793685,
chainwork:
"00000000000000000000000000000000000000000096da5b040913fa09249b4e",
pruned: false,
softforks: [
{ id: "bip34", version: 2, reject: [Object] },
{ id: "bip66", version: 3, reject: [Object] },
{ id: "bip65", version: 4, reject: [Object] }
],
bip9_softforks: {
csv: {
status: "active",
startTime: 1462060800,
timeout: 1493596800,
since: 419328
}
}
}
it("should get blockchain info", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getBlockchainInfo()
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getBlockCount", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = 527810
it("should get block count", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getBlockCount()
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getBlockHash", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data: string =
"000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0"
it("should get block hash by height", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getBlockHash(527810)
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getBlockHeader", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = {
hash: "000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0",
confirmations: 1,
height: 527810,
version: 536870912,
versionHex: "20000000",
merkleroot:
"9298432bbebe4638456aa19cb7ef91639da87668a285d88d0ecd6080424d223b",
time: 1524881438,
mediantime: 1524878499,
nonce: 3326843941,
bits: "1801e8a5",
difficulty: 576023394804.6666,
chainwork:
"00000000000000000000000000000000000000000096da5b040913fa09249b4e",
previousblockhash:
"000000000000000000b33251708bc7a7b4540e61880d8c376e8e2db6a19a4789"
}
it("should get block header by hash", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getBlockHeader(
"000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0",
true
)
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getDifficulty", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = "577528469277.1339"
it("should get difficulty", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getDifficulty()
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getMempoolAncestors", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = "Transaction not in mempool"
it("should get mempool ancestors", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getMempoolAncestors(
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88",
true
)
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getMempoolDescendants", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = {
result: "Transaction not in mempool"
}
it("should get mempool descendants", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getMempoolDescendants(
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88",
true
)
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getMempoolEntry", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = {
result: "Transaction not in mempool"
}
it("should get mempool entry", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getMempoolEntry(
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88"
)
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getMempoolInfo", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = {
result: {
size: 317,
bytes: 208583,
usage: 554944,
maxmempool: 300000000,
mempoolminfee: 0
}
}
it("should get mempool info", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getMempoolInfo()
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getRawMempool", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = {
result: {
transactions: [
{
txid:
"ab36d68dd0a618592fe34e4a898e8beeeb4049133547dbb16f9338384084af96",
size: 191,
fee: 0.00047703,
modifiedfee: 0.00047703,
time: 1524883317,
height: 527811,
startingpriority: 5287822727.272727,
currentpriority: 5287822727.272727,
descendantcount: 1,
descendantsize: 191,
descendantfees: 47703,
ancestorcount: 1,
ancestorsize: 191,
ancestorfees: 47703,
depends: []
}
]
}
}
it("should get mempool info", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.getRawMempool()
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#getTxOut", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = {
result: {}
}
it("should throw an error for improper txid.", async () => {
try {
await bitbox.Blockchain.getTxOut("badtxid", 0)
} catch (err) {
assert.include(err.message, "txid needs to be a proper transaction ID")
}
})
it("should throw an error if vout is not an integer.", async () => {
try {
await bitbox.Blockchain.getTxOut(
"daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88", 'a'
)
} catch (err) {
assert.include(err.message, "n must be an integer")
}
})
it("should get information on an unspent tx", async () => {
sandbox.stub(axios, "get").resolves({ data: mockData.txOutUnspent })
const result = await bitbox.Blockchain.getTxOut(
"62a3ea958a463a372bc0caf2c374a7f60be9c624be63a0db8db78f05809df6d8",
0,
true
)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAllKeys(result, [
"bestblock",
"confirmations",
"value",
"scriptPubKey",
"coinbase"
])
})
it("should get information on a spent tx", async () => {
sandbox.stub(axios, "get").resolves({ data: null })
const result = await bitbox.Blockchain.getTxOut(
"87380e52d151856b23173d6d8a3db01b984c6b50f77ea045a5a1cf4f54497871",
0,
true
)
// console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.equal(result, null)
})
})
describe("#preciousBlock", (): void => {
// TODO finish this test
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = {
result: {}
}
it("should get TODO", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
// @ts-ignore
bitbox.Blockchain.preciousBlock()
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#pruneBlockchain", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = "Cannot prune blocks because node is not in prune mode."
it("should prune blockchain", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "post").returns(resolved)
bitbox.Blockchain.pruneBlockchain(507)
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#verifyChain", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = true
it("should verify blockchain", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.verifyChain(3, 6)
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe("#verifyTxOutProof", (): void => {
let sandbox: any
beforeEach(() => (sandbox = sinon.sandbox.create()))
afterEach(() => sandbox.restore())
const data = "proof must be hexadecimal string (not '')"
it("should verify utxo proof", done => {
const resolved = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
bitbox.Blockchain.verifyTxOutProof("3")
.then((result: any) => {
assert.deepEqual(data, result)
})
.then(done, done)
})
})
describe(`#getBestBlockHash`, (): void => {
it(`should GET best block hash`, async () => {
// Mock out data for unit test, to prevent live network call.
const data: any = blockchainMock.bestBlockHash
const resolved: any = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
const result: string = await bitbox.Blockchain.getBestBlockHash()
//console.log(`result: ${JSON.stringify(result,null,2)}`)
// Assert that BITBOX returns the same data passed to it by rest.
assert.deepEqual(result, blockchainMock.bestBlockHash)
})
})
describe("#getBlockHeader", (): void => {
it(`should GET block header for a single hash`, async () => {
// Mock out data for unit test, to prevent live network call.
const data: any = blockchainMock.blockHeader
const resolved: any = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
const hash: string =
"000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201"
const result:
| BlockHeaderResult
| BlockHeaderResult[] = await bitbox.Blockchain.getBlockHeader(hash)
//console.log(`result: ${JSON.stringify(result,null,2)}`)
assert.hasAllKeys(result, [
"hash",
"confirmations",
"height",
"version",
"versionHex",
"merkleroot",
"time",
"mediantime",
"nonce",
"bits",
"difficulty",
"chainwork",
"previousblockhash",
"nextblockhash"
])
})
it(`should POST block headers for an array of hashes`, async () => {
// Mock out data for unit test, to prevent live network call.
const data: any = [blockchainMock.blockHeader, blockchainMock.blockHeader]
const resolved: any = new Promise(r => r({ data: data }))
sandbox.stub(axios, "post").returns(resolved)
const hash: string[] = [
"000000000000000005e14d3f9fdfb70745308706615cfa9edca4f4558332b201",
"00000000000000000568f0a96bf4348847bc84e455cbfec389f27311037a20f3"
]
const result:
| BlockHeaderResult
| BlockHeaderResult[] = await bitbox.Blockchain.getBlockHeader(hash)
assert.isArray(result)
if (Array.isArray(result)) {
assert.hasAllKeys(result[0], [
"hash",
"confirmations",
"height",
"version",
"versionHex",
"merkleroot",
"time",
"mediantime",
"nonce",
"bits",
"difficulty",
"chainwork",
"previousblockhash",
"nextblockhash"
])
}
})
it(`should pass error from server to user`, async () => {
try {
// Mock out data for unit test, to prevent live network call.
sandbox
.stub(axios, "get")
.throws("error", "Input hash must be a string or array of strings")
const hash: any = 12345
await bitbox.Blockchain.getBlockHeader(hash)
assert.equal(true, false, "Unexpected result!")
} catch (err) {
assert.include(
err.message,
`Input hash must be a string or array of strings`
)
}
})
})
describe("#getMempoolEntry", (): void => {
/*
// To run this test, the txid must be unconfirmed.
const txid =
"defea04c38ee00cf73ad402984714ed22dc0dd99b2ae5cb50d791d94343ba79b"
it(`should GET single mempool entry`, async () => {
const result = await bitbox.Blockchain.getMempoolEntry(txid)
//console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.hasAnyKeys(result, [
"size",
"fee",
"modifiedfee",
"time",
"height",
"startingpriority",
"currentpriority",
"descendantcount",
"descendantsize",
"descendantfees",
"ancestorcount",
"ancestorsize",
"ancestorfees",
"depends"
])
})
it(`should get an array of mempool entries`, async () => {
const result = await bitbox.Blockchain.getMempoolEntry([txid, txid])
console.log(`result: ${JSON.stringify(result, null, 2)}`)
assert.isArray(result)
assert.hasAnyKeys(result[0], [
"size",
"fee",
"modifiedfee",
"time",
"height",
"startingpriority",
"currentpriority",
"descendantcount",
"descendantsize",
"descendantfees",
"ancestorcount",
"ancestorsize",
"ancestorfees",
"depends"
])
})
*/
it(`should pass error from server to user`, async (): Promise<any> => {
try {
// Mock out data for unit test, to prevent live network call.
sandbox
.stub(axios, "get")
.throws({ error: "Transaction not in mempool" })
const txid: string =
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7"
await bitbox.Blockchain.getMempoolEntry(txid)
assert.equal(true, false, "Unexpected result!")
} catch (err) {
//console.log(`err: ${util.inspect(err)}`)
assert.hasAnyKeys(err, ["error"])
assert.include(err.error, `Transaction not in mempool`)
}
})
it(`should throw an error for improper single input`, async (): Promise<
any
> => {
try {
// Mock out data for unit test, to prevent live network call.
sandbox
.stub(axios, "get")
.throws("error", "Input hash must be a string or array of strings")
const txid: any = 12345
await bitbox.Blockchain.getMempoolEntry(txid)
assert.equal(true, false, "Unexpected result!")
} catch (err) {
assert.include(
err.message,
`Input must be a string or array of strings`
)
}
})
})
describe(`#getTxOutProof`, (): void => {
it(`should get single tx out proof`, async (): Promise<any> => {
// Mock out data for unit test, to prevent live network call.
const data: any = blockchainMock.txOutProof
const resolved: any = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
const txid: string =
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7"
const result = await bitbox.Blockchain.getTxOutProof(txid)
//console.log(`result: ${JSON.stringify(result,null,2)}`)
assert.isString(result)
})
it(`should POST an array of tx out proofs`, async (): Promise<any> => {
// Mock out data for unit test, to prevent live network call.
const data: any = [blockchainMock.txOutProof, blockchainMock.txOutProof]
const resolved: any = new Promise(r => r({ data: data }))
sandbox.stub(axios, "post").returns(resolved)
const txid: string[] = [
"03f69502ca32e7927fd4f38c1d3f950bff650c1eea3d09a70e9df5a9d7f989f7",
"fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33"
]
const result = await bitbox.Blockchain.getTxOutProof(txid)
assert.isArray(result)
assert.isString(result[0])
})
it(`should pass error from server to user`, async (): Promise<any> => {
try {
// Mock out data for unit test, to prevent live network call.
sandbox
.stub(axios, "get")
.throws("error", "Input hash must be a string or array of strings")
const txid: any = 12345
await bitbox.Blockchain.getTxOutProof(txid)
assert.equal(true, false, "Unexpected result!")
} catch (err) {
assert.include(
err.message,
`Input must be a string or array of strings`
)
}
})
})
describe(`#verifyTxOutProof`, (): void => {
const mockTxOutProof: string =
"0000002086a4a3161f9ba2174883ec0b93acceac3b2f37b36ed1f90000000000000000009cb02406d1094ecf3e0b4c0ca7c585125e721147c39daf6b48c90b512741e13a12333e5cb38705180f441d8c7100000008fee9b60f1edb57e5712839186277ed39e0a004a32be9096ee47472efde8eae62f789f9d7a9f59d0ea7093dea1e0c65ff0b953f1d8cf3d47f92e732ca0295f603c272d5f4a63509f7a887f2549d78af7444aa0ecbb4f66d9cbe13bc6a89f59e05a199df8325d490818ffefe6b6321d32d7496a68580459836c0183f89082fc1b491cc91b23ecdcaa4c347bf599a62904d61f1c15b400ebbd5c90149010c139d9c1e31b774b796977393a238080ab477e1d240d0c4f155d36f519668f49bae6bd8cd5b8e40522edf76faa09cca6188d83ff13af6967cc6a569d1a5e9aeb1fdb7f531ddd2d0cbb81879741d5f38166ac1932136264366a4065cc96a42e41f96294f02df01"
it(`should verify a single proof`, async (): Promise<any> => {
// Mock out data for unit test, to prevent live network call.
const data: any = [blockchainMock.verifiedProof]
const resolved: any = new Promise(r => r({ data: data }))
sandbox.stub(axios, "get").returns(resolved)
const result = await bitbox.Blockchain.verifyTxOutProof(mockTxOutProof)
//console.log(`result: ${JSON.stringify(result,null,2)}`)
assert.isArray(result)
assert.isString(result[0])
})
it(`should verify an array of proofs`, async (): Promise<any> => {
// Mock out data for unit test, to prevent live network call.
const data: any = [
blockchainMock.verifiedProof,
blockchainMock.verifiedProof
]
const resolved: any = new Promise(r => r({ data: data }))
sandbox.stub(axios, "post").returns(resolved)
const proofs: string[] = [mockTxOutProof, mockTxOutProof]
const result = await bitbox.Blockchain.verifyTxOutProof(proofs)
assert.isArray(result)
assert.isString(result[0])
})
it(`should pass error from server to user`, async (): Promise<any> => {
try {
// Mock out data for unit test, to prevent live network call.
sandbox
.stub(axios, "get")
.throws("error", "Input must be a string or array of strings")
const txid: any = 12345
await bitbox.Blockchain.verifyTxOutProof(txid)
assert.equal(true, false, "Unexpected result!")
} catch (err) {
assert.include(
err.message,
`Input must be a string or array of strings`
)
}
})
})
}) | the_stack |
import { encodeStringValue } from "../../tools/encoding";
import { generateUUID } from "../../tools/uuid";
import {
EntryLegacyHistoryItem,
EntryID,
EntryPropertyType,
FormatAEntry,
FormatAGroup,
FormatAVault,
GroupID
} from "../../types";
interface FormatACommandArgument {
test: RegExp;
wrap: (text: string) => string;
encode: boolean;
}
interface FormatACommandArguments {
[key: string]: FormatACommandArgument;
}
interface FormatACommandManifestCommand {
s: string; // The command
d: boolean; // Destructive flag
args: Array<FormatACommandArgument>; // Command argument definitions
}
interface FormatACommandManifestCommands {
[key: string]: FormatACommandManifestCommand;
}
export const COMMAND_ARGUMENT: FormatACommandArguments = {
ItemID: {
test: /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i,
wrap: (text: string) => text,
encode: false
},
ItemIDOrRoot: {
test: /^([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}|0)$/i,
wrap: (text: string) => text,
encode: false
},
StringKey: {
test: /\S+/,
wrap: (txt: string) => encodeStringValue(txt),
encode: true
},
StringValue: {
test: /(^[\s\S]+$|^$)/,
wrap: (txt: string) => encodeStringValue(txt),
encode: true
}
};
const ARG = COMMAND_ARGUMENT;
export const COMMAND_MANIFEST: FormatACommandManifestCommands = {
ArchiveID: { s: "aid", d: false, args: [ARG.ItemID] },
Comment: { s: "cmm", d: false, args: [ARG.StringValue] },
CreateEntry: { s: "cen", d: false, args: [ARG.ItemID, ARG.ItemID] },
CreateGroup: { s: "cgr", d: false, args: [ARG.ItemIDOrRoot, ARG.ItemID] },
DeleteArchiveAttribute: { s: "daa", d: true, args: [ARG.StringValue] },
DeleteEntry: { s: "den", d: true, args: [ARG.ItemID] },
DeleteEntryAttribute: { s: "dea", d: true, args: [ARG.ItemID, ARG.StringValue] },
DeleteEntryMeta: { s: "dem", d: true, args: [ARG.ItemID, ARG.StringValue] },
DeleteEntryProperty: { s: "dep", d: true, args: [ARG.ItemID, ARG.StringValue] },
DeleteGroup: { s: "dgr", d: true, args: [ARG.ItemID] },
DeleteGroupAttribute: { s: "dga", d: true, args: [ARG.ItemID, ARG.StringValue] },
Format: { s: "fmt", d: false, args: [ARG.StringValue] },
MoveEntry: { s: "men", d: false, args: [ARG.ItemID, ARG.ItemID] },
MoveGroup: { s: "mgr", d: false, args: [ARG.ItemID, ARG.ItemIDOrRoot] },
Pad: { s: "pad", d: false, args: [ARG.ItemID] },
SetArchiveAttribute: { s: "saa", d: false, args: [ARG.StringValue, ARG.StringValue] },
SetEntryAttribute: { s: "sea", d: false, args: [ARG.ItemID, ARG.StringValue, ARG.StringValue] },
SetEntryMeta: { s: "sem", d: false, args: [ARG.ItemID, ARG.StringValue, ARG.StringValue] },
SetEntryProperty: { s: "sep", d: false, args: [ARG.ItemID, ARG.StringKey, ARG.StringValue] },
SetGroupAttribute: { s: "sga", d: false, args: [ARG.ItemID, ARG.StringValue, ARG.StringValue] },
SetGroupTitle: { s: "tgr", d: false, args: [ARG.ItemID, ARG.StringValue] }
};
const PLACEHOLDER_ESCAPED = "__ESCAPED_QUOTE__";
const PLACEHOLDER_QUOTED = "__QUOTEDSTR__";
export class InigoCommand {
static Command = COMMAND_MANIFEST;
static create(cmd: FormatACommandManifestCommand) {
return new InigoCommand(cmd);
}
static generatePaddingCommand(): string {
const inigo = InigoCommand.create(COMMAND_MANIFEST.Pad);
return inigo.addArgument(generateUUID()).generateCommand();
}
_commandKey: FormatACommandManifestCommand;
_commandArgs: Array<string>;
constructor(cmdKey: FormatACommandManifestCommand) {
this._commandKey = cmdKey;
this._commandArgs = [];
}
addArgument(arg: string): this {
const newArgIndex = this._commandArgs.length;
const argRules = this._commandKey.args;
const newArgRule = argRules.length <= newArgIndex ? false : argRules[newArgIndex];
if (newArgRule === false) {
throw new Error(`Failed adding argument for command "${this._commandKey.s}": too many arguments`);
}
if (!newArgRule.test.test(arg)) {
throw new Error(
`Failed adding argument for command "${this._commandKey.s}": argument ${newArgIndex} is of invalid format`
);
}
this._commandArgs.push(newArgRule.wrap(arg));
return this;
}
generateCommand(): string {
return [this._commandKey.s].concat(this._commandArgs).join(" ");
}
}
/**
* Extract command components from a string
* @param command The command to extract from
* @returns The separated parts
*/
export function extractCommandComponents(cmd: string): Array<string> {
const patt = /("[^"]*")/;
const matches: Array<string> = [];
let match: RegExpExecArray;
let command = cmd.replace(/\\\"/g, PLACEHOLDER_ESCAPED);
// Replace complex command segments
while ((match = patt.exec(command))) {
const [matched] = match;
command = command.substr(0, match.index) + PLACEHOLDER_QUOTED + command.substr(match.index + matched.length);
matches.push(matched.substring(1, matched.length - 1));
}
// Split command, map back to original values
return command.split(" ").map(part => {
let item = part.trim();
if (item === PLACEHOLDER_QUOTED) {
item = matches.shift();
}
item = item.replace(new RegExp(PLACEHOLDER_ESCAPED, "g"), '"');
return item;
});
}
export function findEntryByID(groups: Array<FormatAGroup>, id: EntryID) {
for (let i = 0, groupsLen = groups.length; i < groupsLen; i += 1) {
const group = groups[i];
if (group.entries) {
for (let j = 0, entriesLen = group.entries.length; j < entriesLen; j += 1) {
if (group.entries[j].id === id) {
return group.entries[j];
}
}
}
if (group.groups) {
const deepEntry = findEntryByID(group.groups, id);
if (deepEntry) {
return deepEntry;
}
}
}
return null;
}
function findGroupByCheck(groups, checkFn) {
for (let i = 0, groupsLen = groups.length; i < groupsLen; i += 1) {
if (checkFn(groups[i]) === true) {
return groups[i];
}
if (groups[i].groups) {
const deepGroup = findGroupByCheck(groups[i].groups, checkFn);
if (deepGroup) {
return deepGroup;
}
}
}
return null;
}
export function findGroupByID(groups, id) {
return findGroupByCheck(groups, function(group) {
return group.id === id;
});
}
/**
* Find a raw group that contains an entry with an ID
* @param groups An array of raw groups
* @param id The entry ID to search for
* @returns The parent group of the found entry
*/
export function findGroupContainingEntryID(groups: Array<FormatAGroup>, id: EntryID) {
for (let i = 0, groupsLen = groups.length; i < groupsLen; i += 1) {
const group = groups[i];
if (group.entries) {
for (var j = 0, entriesLen = group.entries.length; j < entriesLen; j += 1) {
if (group.entries[j].id === id) {
return {
group: group,
index: j
};
}
}
}
if (group.groups) {
const deepGroup = findGroupContainingEntryID(group.groups, id);
if (deepGroup.group) {
return deepGroup;
}
}
}
return {
group: null,
index: null
};
}
/**
* Find a raw group that contains a group with an ID
* @param group The group/archive to search in
* @param id The group ID to search for
* @returns The parent of the located group ID
*/
export function findGroupContainingGroupID(group: FormatAGroup | FormatAVault, id: GroupID) {
const groups = group.groups || [];
for (let i = 0, groupsLen = groups.length; i < groupsLen; i += 1) {
if (groups[i].id === id) {
return {
group: group,
index: i
};
}
const deepGroup = findGroupContainingGroupID(groups[i], id);
if (deepGroup.group) {
return deepGroup;
}
}
return {
group: null,
index: null
};
}
/**
* @typedef {Object} EntryLegacyHistoryItem
* @property {String} property The property/attribute name
* @property {String} propertyType Either "property" or "attribute"
* @property {String|null} originalValue The original value or null if it did not exist
* before this change
* @property {String|null} newValue The new value or null if it was deleted
*/
/**
* Generate a new entry history item
* @param property The property/attribute name
* @param propertyType Either "property" or "attribute"
* @param originalValue The original value or null if it did not exist
* before this change
* @param newValue The new value or null if it was deleted
*/
export function generateEntryLegacyHistoryItem(
property: string,
propertyType: EntryPropertyType,
originalValue: string = null,
newValue: string = null
): EntryLegacyHistoryItem {
return Object.freeze({
property,
propertyType,
originalValue,
newValue
});
}
export function getAllEntries(source: FormatAVault, parentID: GroupID = null): Array<FormatAEntry> {
const entries = [];
const getEntries = (group: FormatAGroup) => {
if (parentID === null || group.id === parentID) {
entries.push(...(group.entries || []));
}
(group.groups || []).forEach(group => getEntries(group));
};
source.groups.forEach(group => getEntries(group));
return entries;
}
export function getAllGroups(source: FormatAVault, parentID: GroupID = null): Array<FormatAGroup> {
const foundGroups = [];
const getGroups = (parent: FormatAVault | FormatAGroup) => {
(parent.groups || []).forEach(subGroup => {
if (
parentID === null ||
(parentID === "0" && typeof (<any>subGroup).parentID === "undefined") ||
parentID === (<FormatAGroup>subGroup).parentID
) {
foundGroups.push(subGroup);
}
getGroups(subGroup);
});
};
getGroups(source);
return foundGroups;
}
export function historyArrayToString(historyArray: Array<string>): string {
return historyArray.join("\n");
}
export function historyStringToArray(historyString: string): Array<string> {
return historyString.split("\n");
}
/**
* Strip destructive commands from a history collection
* @param history The history
* @returns The history minus any destructive commands
*/
export function stripDestructiveCommands(history: Array<string>): Array<string> {
const getCommandType = fullCommand => (fullCommand && fullCommand.length >= 3 ? fullCommand.substr(0, 3) : "");
const destructiveSlugs = Object.keys(COMMAND_MANIFEST)
.map(key => COMMAND_MANIFEST[key])
.filter(command => command.d)
.map(command => command.s);
return history.filter(command => {
return destructiveSlugs.indexOf(getCommandType(command)) < 0;
});
} | the_stack |
import { GaxiosPromise } from 'gaxios';
import { Compute, JWT, OAuth2Client, UserRefreshClient } from 'google-auth-library';
import { APIRequestContext, BodyResponseCallback, GlobalOptions, GoogleConfigurable, MethodOptions } from 'googleapis-common';
export declare namespace appstate_v1 {
interface Options extends GlobalOptions {
version: 'v1';
}
interface StandardParameters {
/**
* Data format for the response.
*/
alt?: string;
/**
* Selector specifying which fields to include in a partial response.
*/
fields?: string;
/**
* API key. Your API key identifies your project and provides you with API
* access, quota, and reports. Required unless you provide an OAuth 2.0
* token.
*/
key?: string;
/**
* OAuth 2.0 token for the current user.
*/
oauth_token?: string;
/**
* Returns response with indentations and line breaks.
*/
prettyPrint?: boolean;
/**
* An opaque string that represents a user for quota purposes. Must not
* exceed 40 characters.
*/
quotaUser?: string;
/**
* Deprecated. Please use quotaUser instead.
*/
userIp?: string;
}
/**
* Google App State API
*
* The Google App State API.
*
* @example
* const {google} = require('googleapis');
* const appstate = google.appstate('v1');
*
* @namespace appstate
* @type {Function}
* @version v1
* @variation v1
* @param {object=} options Options for Appstate
*/
class Appstate {
context: APIRequestContext;
states: Resource$States;
constructor(options: GlobalOptions, google?: GoogleConfigurable);
}
/**
* This is a JSON template for an app state resource.
*/
interface Schema$GetResponse {
/**
* The current app state version.
*/
currentStateVersion?: string;
/**
* The requested data.
*/
data?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string appstate#getResponse.
*/
kind?: string;
/**
* The key for the data.
*/
stateKey?: number;
}
/**
* This is a JSON template to convert a list-response for app state.
*/
interface Schema$ListResponse {
/**
* The app state data.
*/
items?: Schema$GetResponse[];
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string appstate#listResponse.
*/
kind?: string;
/**
* The maximum number of keys allowed for this user.
*/
maximumKeyCount?: number;
}
/**
* This is a JSON template for a requests which update app state
*/
interface Schema$UpdateRequest {
/**
* The new app state data that your application is trying to update with.
*/
data?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string appstate#updateRequest.
*/
kind?: string;
}
/**
* This is a JSON template for an app state write result.
*/
interface Schema$WriteResult {
/**
* The version of the data for this key on the server.
*/
currentStateVersion?: string;
/**
* Uniquely identifies the type of this resource. Value is always the fixed
* string appstate#writeResult.
*/
kind?: string;
/**
* The written key.
*/
stateKey?: number;
}
class Resource$States {
context: APIRequestContext;
constructor(context: APIRequestContext);
/**
* appstate.states.clear
* @desc Clears (sets to empty) the data for the passed key if and only if
* the passed version matches the currently stored version. This method
* results in a conflict error on version mismatch.
* @alias appstate.states.clear
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.currentDataVersion The version of the data to be cleared. Version strings are returned by the server.
* @param {integer} params.stateKey The key for the data to be retrieved.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
clear(params?: Params$Resource$States$Clear, options?: MethodOptions): GaxiosPromise<Schema$WriteResult>;
clear(params: Params$Resource$States$Clear, options: MethodOptions | BodyResponseCallback<Schema$WriteResult>, callback: BodyResponseCallback<Schema$WriteResult>): void;
clear(params: Params$Resource$States$Clear, callback: BodyResponseCallback<Schema$WriteResult>): void;
clear(callback: BodyResponseCallback<Schema$WriteResult>): void;
/**
* appstate.states.delete
* @desc Deletes a key and the data associated with it. The key is removed
* and no longer counts against the key quota. Note that since this method
* is not safe in the face of concurrent modifications, it should only be
* used for development and testing purposes. Invoking this method in
* shipping code can result in data loss and data corruption.
* @alias appstate.states.delete
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {integer} params.stateKey The key for the data to be retrieved.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
delete(params?: Params$Resource$States$Delete, options?: MethodOptions): GaxiosPromise<void>;
delete(params: Params$Resource$States$Delete, options: MethodOptions | BodyResponseCallback<void>, callback: BodyResponseCallback<void>): void;
delete(params: Params$Resource$States$Delete, callback: BodyResponseCallback<void>): void;
delete(callback: BodyResponseCallback<void>): void;
/**
* appstate.states.get
* @desc Retrieves the data corresponding to the passed key. If the key does
* not exist on the server, an HTTP 404 will be returned.
* @alias appstate.states.get
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {integer} params.stateKey The key for the data to be retrieved.
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
get(params?: Params$Resource$States$Get, options?: MethodOptions): GaxiosPromise<Schema$GetResponse>;
get(params: Params$Resource$States$Get, options: MethodOptions | BodyResponseCallback<Schema$GetResponse>, callback: BodyResponseCallback<Schema$GetResponse>): void;
get(params: Params$Resource$States$Get, callback: BodyResponseCallback<Schema$GetResponse>): void;
get(callback: BodyResponseCallback<Schema$GetResponse>): void;
/**
* appstate.states.list
* @desc Lists all the states keys, and optionally the state data.
* @alias appstate.states.list
* @memberOf! ()
*
* @param {object=} params Parameters for request
* @param {boolean=} params.includeData Whether to include the full data in addition to the version number
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
list(params?: Params$Resource$States$List, options?: MethodOptions): GaxiosPromise<Schema$ListResponse>;
list(params: Params$Resource$States$List, options: MethodOptions | BodyResponseCallback<Schema$ListResponse>, callback: BodyResponseCallback<Schema$ListResponse>): void;
list(params: Params$Resource$States$List, callback: BodyResponseCallback<Schema$ListResponse>): void;
list(callback: BodyResponseCallback<Schema$ListResponse>): void;
/**
* appstate.states.update
* @desc Update the data associated with the input key if and only if the
* passed version matches the currently stored version. This method is safe
* in the face of concurrent writes. Maximum per-key size is 128KB.
* @alias appstate.states.update
* @memberOf! ()
*
* @param {object} params Parameters for request
* @param {string=} params.currentStateVersion The version of the app state your application is attempting to update. If this does not match the current version, this method will return a conflict error. If there is no data stored on the server for this key, the update will succeed irrespective of the value of this parameter.
* @param {integer} params.stateKey The key for the data to be retrieved.
* @param {().UpdateRequest} params.resource Request body data
* @param {object} [options] Optionally override request options, such as `url`, `method`, and `encoding`.
* @param {callback} callback The callback that handles the response.
* @return {object} Request object
*/
update(params?: Params$Resource$States$Update, options?: MethodOptions): GaxiosPromise<Schema$WriteResult>;
update(params: Params$Resource$States$Update, options: MethodOptions | BodyResponseCallback<Schema$WriteResult>, callback: BodyResponseCallback<Schema$WriteResult>): void;
update(params: Params$Resource$States$Update, callback: BodyResponseCallback<Schema$WriteResult>): void;
update(callback: BodyResponseCallback<Schema$WriteResult>): void;
}
interface Params$Resource$States$Clear extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The version of the data to be cleared. Version strings are returned by
* the server.
*/
currentDataVersion?: string;
/**
* The key for the data to be retrieved.
*/
stateKey?: number;
}
interface Params$Resource$States$Delete extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The key for the data to be retrieved.
*/
stateKey?: number;
}
interface Params$Resource$States$Get extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The key for the data to be retrieved.
*/
stateKey?: number;
}
interface Params$Resource$States$List extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* Whether to include the full data in addition to the version number
*/
includeData?: boolean;
}
interface Params$Resource$States$Update extends StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?: string | OAuth2Client | JWT | Compute | UserRefreshClient;
/**
* The version of the app state your application is attempting to update. If
* this does not match the current version, this method will return a
* conflict error. If there is no data stored on the server for this key,
* the update will succeed irrespective of the value of this parameter.
*/
currentStateVersion?: string;
/**
* The key for the data to be retrieved.
*/
stateKey?: number;
/**
* Request body metadata
*/
requestBody?: Schema$UpdateRequest;
}
} | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
interface Blob {}
declare class MarketplaceCatalog extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: MarketplaceCatalog.Types.ClientConfiguration)
config: Config & MarketplaceCatalog.Types.ClientConfiguration;
/**
* Used to cancel an open change request. Must be sent before the status of the request changes to APPLYING, the final stage of completing your change request. You can describe a change during the 60-day request history retention period for API calls.
*/
cancelChangeSet(params: MarketplaceCatalog.Types.CancelChangeSetRequest, callback?: (err: AWSError, data: MarketplaceCatalog.Types.CancelChangeSetResponse) => void): Request<MarketplaceCatalog.Types.CancelChangeSetResponse, AWSError>;
/**
* Used to cancel an open change request. Must be sent before the status of the request changes to APPLYING, the final stage of completing your change request. You can describe a change during the 60-day request history retention period for API calls.
*/
cancelChangeSet(callback?: (err: AWSError, data: MarketplaceCatalog.Types.CancelChangeSetResponse) => void): Request<MarketplaceCatalog.Types.CancelChangeSetResponse, AWSError>;
/**
* Provides information about a given change set.
*/
describeChangeSet(params: MarketplaceCatalog.Types.DescribeChangeSetRequest, callback?: (err: AWSError, data: MarketplaceCatalog.Types.DescribeChangeSetResponse) => void): Request<MarketplaceCatalog.Types.DescribeChangeSetResponse, AWSError>;
/**
* Provides information about a given change set.
*/
describeChangeSet(callback?: (err: AWSError, data: MarketplaceCatalog.Types.DescribeChangeSetResponse) => void): Request<MarketplaceCatalog.Types.DescribeChangeSetResponse, AWSError>;
/**
* Returns the metadata and content of the entity.
*/
describeEntity(params: MarketplaceCatalog.Types.DescribeEntityRequest, callback?: (err: AWSError, data: MarketplaceCatalog.Types.DescribeEntityResponse) => void): Request<MarketplaceCatalog.Types.DescribeEntityResponse, AWSError>;
/**
* Returns the metadata and content of the entity.
*/
describeEntity(callback?: (err: AWSError, data: MarketplaceCatalog.Types.DescribeEntityResponse) => void): Request<MarketplaceCatalog.Types.DescribeEntityResponse, AWSError>;
/**
* Returns the list of change sets owned by the account being used to make the call. You can filter this list by providing any combination of entityId, ChangeSetName, and status. If you provide more than one filter, the API operation applies a logical AND between the filters. You can describe a change during the 60-day request history retention period for API calls.
*/
listChangeSets(params: MarketplaceCatalog.Types.ListChangeSetsRequest, callback?: (err: AWSError, data: MarketplaceCatalog.Types.ListChangeSetsResponse) => void): Request<MarketplaceCatalog.Types.ListChangeSetsResponse, AWSError>;
/**
* Returns the list of change sets owned by the account being used to make the call. You can filter this list by providing any combination of entityId, ChangeSetName, and status. If you provide more than one filter, the API operation applies a logical AND between the filters. You can describe a change during the 60-day request history retention period for API calls.
*/
listChangeSets(callback?: (err: AWSError, data: MarketplaceCatalog.Types.ListChangeSetsResponse) => void): Request<MarketplaceCatalog.Types.ListChangeSetsResponse, AWSError>;
/**
* Provides the list of entities of a given type.
*/
listEntities(params: MarketplaceCatalog.Types.ListEntitiesRequest, callback?: (err: AWSError, data: MarketplaceCatalog.Types.ListEntitiesResponse) => void): Request<MarketplaceCatalog.Types.ListEntitiesResponse, AWSError>;
/**
* Provides the list of entities of a given type.
*/
listEntities(callback?: (err: AWSError, data: MarketplaceCatalog.Types.ListEntitiesResponse) => void): Request<MarketplaceCatalog.Types.ListEntitiesResponse, AWSError>;
/**
* This operation allows you to request changes for your entities. Within a single ChangeSet, you cannot start the same change type against the same entity multiple times. Additionally, when a ChangeSet is running, all the entities targeted by the different changes are locked until the ChangeSet has completed (either succeeded, cancelled, or failed). If you try to start a ChangeSet containing a change against an entity that is already locked, you will receive a ResourceInUseException. For example, you cannot start the ChangeSet described in the example later in this topic, because it contains two changes to execute the same change type (AddRevisions) against the same entity (entity-id@1). For more information about working with change sets, see Working with change sets.
*/
startChangeSet(params: MarketplaceCatalog.Types.StartChangeSetRequest, callback?: (err: AWSError, data: MarketplaceCatalog.Types.StartChangeSetResponse) => void): Request<MarketplaceCatalog.Types.StartChangeSetResponse, AWSError>;
/**
* This operation allows you to request changes for your entities. Within a single ChangeSet, you cannot start the same change type against the same entity multiple times. Additionally, when a ChangeSet is running, all the entities targeted by the different changes are locked until the ChangeSet has completed (either succeeded, cancelled, or failed). If you try to start a ChangeSet containing a change against an entity that is already locked, you will receive a ResourceInUseException. For example, you cannot start the ChangeSet described in the example later in this topic, because it contains two changes to execute the same change type (AddRevisions) against the same entity (entity-id@1). For more information about working with change sets, see Working with change sets.
*/
startChangeSet(callback?: (err: AWSError, data: MarketplaceCatalog.Types.StartChangeSetResponse) => void): Request<MarketplaceCatalog.Types.StartChangeSetResponse, AWSError>;
}
declare namespace MarketplaceCatalog {
export type ARN = string;
export interface CancelChangeSetRequest {
/**
* Required. The catalog related to the request. Fixed value: AWSMarketplace.
*/
Catalog: Catalog;
/**
* Required. The unique identifier of the StartChangeSet request that you want to cancel.
*/
ChangeSetId: ResourceId;
}
export interface CancelChangeSetResponse {
/**
* The unique identifier for the change set referenced in this request.
*/
ChangeSetId?: ResourceId;
/**
* The ARN associated with the change set referenced in this request.
*/
ChangeSetArn?: ARN;
}
export type Catalog = string;
export interface Change {
/**
* Change types are single string values that describe your intention for the change. Each change type is unique for each EntityType provided in the change's scope.
*/
ChangeType: ChangeType;
/**
* The entity to be changed.
*/
Entity: Entity;
/**
* This object contains details specific to the change type of the requested change.
*/
Details: Json;
/**
* Optional name for the change.
*/
ChangeName?: ChangeName;
}
export type ChangeName = string;
export type ChangeSetDescription = ChangeSummary[];
export type ChangeSetName = string;
export type ChangeSetSummaryList = ChangeSetSummaryListItem[];
export interface ChangeSetSummaryListItem {
/**
* The unique identifier for a change set.
*/
ChangeSetId?: ResourceId;
/**
* The ARN associated with the unique identifier for the change set referenced in this request.
*/
ChangeSetArn?: ARN;
/**
* The non-unique name for the change set.
*/
ChangeSetName?: ChangeSetName;
/**
* The time, in ISO 8601 format (2018-02-27T13:45:22Z), when the change set was started.
*/
StartTime?: DateTimeISO8601;
/**
* The time, in ISO 8601 format (2018-02-27T13:45:22Z), when the change set was finished.
*/
EndTime?: DateTimeISO8601;
/**
* The current status of the change set.
*/
Status?: ChangeStatus;
/**
* This object is a list of entity IDs (string) that are a part of a change set. The entity ID list is a maximum of 20 entities. It must contain at least one entity.
*/
EntityIdList?: ResourceIdList;
/**
* Returned if the change set is in FAILED status. Can be either CLIENT_ERROR, which means that there are issues with the request (see the ErrorDetailList of DescribeChangeSet), or SERVER_FAULT, which means that there is a problem in the system, and you should retry your request.
*/
FailureCode?: FailureCode;
}
export type ChangeStatus = "PREPARING"|"APPLYING"|"SUCCEEDED"|"CANCELLED"|"FAILED"|string;
export interface ChangeSummary {
/**
* The type of the change.
*/
ChangeType?: ChangeType;
/**
* The entity to be changed.
*/
Entity?: Entity;
/**
* This object contains details specific to the change type of the requested change.
*/
Details?: Json;
/**
* An array of ErrorDetail objects associated with the change.
*/
ErrorDetailList?: ErrorDetailList;
/**
* Optional name for the change.
*/
ChangeName?: ChangeName;
}
export type ChangeType = string;
export type ClientRequestToken = string;
export type DateTimeISO8601 = string;
export interface DescribeChangeSetRequest {
/**
* Required. The catalog related to the request. Fixed value: AWSMarketplace
*/
Catalog: Catalog;
/**
* Required. The unique identifier for the StartChangeSet request that you want to describe the details for.
*/
ChangeSetId: ResourceId;
}
export interface DescribeChangeSetResponse {
/**
* Required. The unique identifier for the change set referenced in this request.
*/
ChangeSetId?: ResourceId;
/**
* The ARN associated with the unique identifier for the change set referenced in this request.
*/
ChangeSetArn?: ARN;
/**
* The optional name provided in the StartChangeSet request. If you do not provide a name, one is set by default.
*/
ChangeSetName?: ChangeSetName;
/**
* The date and time, in ISO 8601 format (2018-02-27T13:45:22Z), the request started.
*/
StartTime?: DateTimeISO8601;
/**
* The date and time, in ISO 8601 format (2018-02-27T13:45:22Z), the request transitioned to a terminal state. The change cannot transition to a different state. Null if the request is not in a terminal state.
*/
EndTime?: DateTimeISO8601;
/**
* The status of the change request.
*/
Status?: ChangeStatus;
/**
* Returned if the change set is in FAILED status. Can be either CLIENT_ERROR, which means that there are issues with the request (see the ErrorDetailList), or SERVER_FAULT, which means that there is a problem in the system, and you should retry your request.
*/
FailureCode?: FailureCode;
/**
* Returned if there is a failure on the change set, but that failure is not related to any of the changes in the request.
*/
FailureDescription?: ExceptionMessageContent;
/**
* An array of ChangeSummary objects.
*/
ChangeSet?: ChangeSetDescription;
}
export interface DescribeEntityRequest {
/**
* Required. The catalog related to the request. Fixed value: AWSMarketplace
*/
Catalog: Catalog;
/**
* Required. The unique ID of the entity to describe.
*/
EntityId: ResourceId;
}
export interface DescribeEntityResponse {
/**
* The named type of the entity, in the format of EntityType@Version.
*/
EntityType?: EntityType;
/**
* The identifier of the entity, in the format of EntityId@RevisionId.
*/
EntityIdentifier?: Identifier;
/**
* The ARN associated to the unique identifier for the change set referenced in this request.
*/
EntityArn?: ARN;
/**
* The last modified date of the entity, in ISO 8601 format (2018-02-27T13:45:22Z).
*/
LastModifiedDate?: DateTimeISO8601;
/**
* This stringified JSON object includes the details of the entity.
*/
Details?: Json;
}
export interface Entity {
/**
* The type of entity.
*/
Type: EntityType;
/**
* The identifier for the entity.
*/
Identifier?: Identifier;
}
export type EntityNameString = string;
export interface EntitySummary {
/**
* The name for the entity. This value is not unique. It is defined by the seller.
*/
Name?: EntityNameString;
/**
* The type of the entity.
*/
EntityType?: EntityType;
/**
* The unique identifier for the entity.
*/
EntityId?: ResourceId;
/**
* The ARN associated with the unique identifier for the entity.
*/
EntityArn?: ARN;
/**
* The last time the entity was published, using ISO 8601 format (2018-02-27T13:45:22Z).
*/
LastModifiedDate?: DateTimeISO8601;
/**
* The visibility status of the entity to buyers. This value can be Public (everyone can view the entity), Limited (the entity is visible to limited accounts only), or Restricted (the entity was published and then unpublished and only existing buyers can view it).
*/
Visibility?: VisibilityValue;
}
export type EntitySummaryList = EntitySummary[];
export type EntityType = string;
export type ErrorCodeString = string;
export interface ErrorDetail {
/**
* The error code that identifies the type of error.
*/
ErrorCode?: ErrorCodeString;
/**
* The message for the error.
*/
ErrorMessage?: ExceptionMessageContent;
}
export type ErrorDetailList = ErrorDetail[];
export type ExceptionMessageContent = string;
export type FailureCode = "CLIENT_ERROR"|"SERVER_FAULT"|string;
export interface Filter {
/**
* For ListEntities, the supported value for this is an EntityId. For ListChangeSets, the supported values are as follows:
*/
Name?: FilterName;
/**
* ListEntities - This is a list of unique EntityIds. ListChangeSets - The supported filter names and associated ValueLists is as follows: ChangeSetName - The supported ValueList is a list of non-unique ChangeSetNames. These are defined when you call the StartChangeSet action. Status - The supported ValueList is a list of statuses for all change set requests. EntityId - The supported ValueList is a list of unique EntityIds. BeforeStartTime - The supported ValueList is a list of all change sets that started before the filter value. AfterStartTime - The supported ValueList is a list of all change sets that started after the filter value. BeforeEndTime - The supported ValueList is a list of all change sets that ended before the filter value. AfterEndTime - The supported ValueList is a list of all change sets that ended after the filter value.
*/
ValueList?: ValueList;
}
export type FilterList = Filter[];
export type FilterName = string;
export type FilterValueContent = string;
export type Identifier = string;
export type Json = string;
export interface ListChangeSetsRequest {
/**
* The catalog related to the request. Fixed value: AWSMarketplace
*/
Catalog: Catalog;
/**
* An array of filter objects.
*/
FilterList?: FilterList;
/**
* An object that contains two attributes, SortBy and SortOrder.
*/
Sort?: Sort;
/**
* The maximum number of results returned by a single call. This value must be provided in the next call to retrieve the next set of results. By default, this value is 20.
*/
MaxResults?: MaxResultInteger;
/**
* The token value retrieved from a previous call to access the next page of results.
*/
NextToken?: NextToken;
}
export interface ListChangeSetsResponse {
/**
* Array of ChangeSetSummaryListItem objects.
*/
ChangeSetSummaryList?: ChangeSetSummaryList;
/**
* The value of the next token, if it exists. Null if there are no more results.
*/
NextToken?: NextToken;
}
export interface ListEntitiesRequest {
/**
* The catalog related to the request. Fixed value: AWSMarketplace
*/
Catalog: Catalog;
/**
* The type of entities to retrieve.
*/
EntityType: EntityType;
/**
* An array of filter objects. Each filter object contains two attributes, filterName and filterValues.
*/
FilterList?: FilterList;
/**
* An object that contains two attributes, SortBy and SortOrder.
*/
Sort?: Sort;
/**
* The value of the next token, if it exists. Null if there are no more results.
*/
NextToken?: NextToken;
/**
* Specifies the upper limit of the elements on a single page. If a value isn't provided, the default value is 20.
*/
MaxResults?: MaxResultInteger;
}
export interface ListEntitiesResponse {
/**
* Array of EntitySummary object.
*/
EntitySummaryList?: EntitySummaryList;
/**
* The value of the next token if it exists. Null if there is no more result.
*/
NextToken?: NextToken;
}
export type MaxResultInteger = number;
export type NextToken = string;
export type RequestedChangeList = Change[];
export type ResourceId = string;
export type ResourceIdList = ResourceId[];
export interface Sort {
/**
* For ListEntities, supported attributes include LastModifiedDate (default), Visibility, EntityId, and Name. For ListChangeSets, supported attributes include StartTime and EndTime.
*/
SortBy?: SortBy;
/**
* The sorting order. Can be ASCENDING or DESCENDING. The default value is DESCENDING.
*/
SortOrder?: SortOrder;
}
export type SortBy = string;
export type SortOrder = "ASCENDING"|"DESCENDING"|string;
export interface StartChangeSetRequest {
/**
* The catalog related to the request. Fixed value: AWSMarketplace
*/
Catalog: Catalog;
/**
* Array of change object.
*/
ChangeSet: RequestedChangeList;
/**
* Optional case sensitive string of up to 100 ASCII characters. The change set name can be used to filter the list of change sets.
*/
ChangeSetName?: ChangeSetName;
/**
* A unique token to identify the request to ensure idempotency.
*/
ClientRequestToken?: ClientRequestToken;
}
export interface StartChangeSetResponse {
/**
* Unique identifier generated for the request.
*/
ChangeSetId?: ResourceId;
/**
* The ARN associated to the unique identifier generated for the request.
*/
ChangeSetArn?: ARN;
}
export type ValueList = FilterValueContent[];
export type VisibilityValue = string;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2018-09-17"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the MarketplaceCatalog client.
*/
export import Types = MarketplaceCatalog;
}
export = MarketplaceCatalog; | the_stack |
import rule from '../../src/rules/plugin-test-formatting';
import { RuleTester } from '../RuleTester';
const ruleTester = new RuleTester({
parser: '@typescript-eslint/parser',
parserOptions: {
sourceType: 'module',
},
});
const CODE_INDENT = ' ';
const PARENT_INDENT = ' ';
function wrap(strings: TemplateStringsArray, ...keys: string[]): string {
const lastIndex = strings.length - 1;
const code =
strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], '') +
strings[lastIndex];
return `
ruleTester.run({
valid: [
{
code: ${code},
},
],
});
`;
}
function wrapWithOutput(
strings: TemplateStringsArray,
...keys: string[]
): string {
const lastIndex = strings.length - 1;
const code =
strings.slice(0, lastIndex).reduce((p, s, i) => p + s + keys[i], '') +
strings[lastIndex];
return `
ruleTester.run({
invalid: [
{
code: ${code},
output: ${code},
},
],
});
`;
}
ruleTester.run('plugin-test-formatting', rule, {
valid: [
// sanity check for valid tests non-object style
`
ruleTester.run({
valid: [
'const a = 1;',
\`
const a = 1;
\`,
\`
const a = 1;
\`,
noFormat\`const x=1;\`,
],
});
`,
wrap`'const a = 1;'`,
wrap`\`
${CODE_INDENT}const a = 1;
${PARENT_INDENT}\``,
wrap`\`
const a = 1;
${PARENT_INDENT}\``,
wrap`noFormat\`const a = 1;\``,
// sanity check suggestion validation
// eslint-disable-next-line @typescript-eslint/internal/plugin-test-formatting
`
ruleTester.run({
invalid: [
{
code: 'const a = 1;',
output: 'const a = 1;',
errors: [
{
messageId: 'foo',
suggestions: [
{
messageId: 'bar',
output: 'const a = 1;',
},
],
}
]
},
{
code: \`
const a = 1;
\`,
output: \`
const a = 1;
\`,
errors: [
{
messageId: 'foo',
suggestions: [
{
messageId: 'bar',
output: \`
const a = 1;
\`,
},
],
}
]
},
{
code: \`
const a = 1;
\`,
output: \`
const a = 1;
\`,
errors: [
{
messageId: 'foo',
suggestions: [
{
messageId: 'bar',
output: \`
const a = 1;
\`,
},
],
}
]
},
],
});
`,
// test the only option
{
code: wrap`'const x=1;'`,
options: [
{
formatWithPrettier: false,
},
],
},
// empty linems are valid when everything else is indented
wrap`\`
${CODE_INDENT}const a = 1;
${CODE_INDENT}const b = 1;
${PARENT_INDENT}\``,
],
invalid: [
// Literal
{
code: wrap`'const a=1;'`,
output: wrap`'const a = 1;'`,
errors: [
{
messageId: 'invalidFormatting',
},
],
},
{
code: wrap`'const a="1";'`,
output: wrap`"const a = '1';"`,
errors: [
{
messageId: 'invalidFormatting',
},
],
},
{
code: wrap`"const a='1';"`,
output: wrap`"const a = '1';"`,
errors: [
{
messageId: 'invalidFormatting',
},
],
},
{
code: wrap`'for (const x of y) {}'`,
output: wrap`\`for (const x of y) {
}\``,
errors: [
{
messageId: 'invalidFormatting',
},
],
},
{
code: wrap`'for (const x of \`asdf\`) {}'`,
// make sure it escapes the backticks
output: wrap`\`for (const x of \\\`asdf\\\`) {
}\``,
errors: [
{
messageId: 'invalidFormatting',
},
],
},
// TemplateLiteral
// singleLineQuotes
{
code: wrap`\`const a = 1;\``,
output: wrap`'const a = 1;'`,
errors: [
{
messageId: 'singleLineQuotes',
},
],
},
{
code: wrap`\`const a = '1'\``,
output: wrap`"const a = '1'"`,
errors: [
{
messageId: 'singleLineQuotes',
},
],
},
{
code: wrap`\`const a = "1";\``,
output: wrap`'const a = "1";'`,
errors: [
{
messageId: 'singleLineQuotes',
},
],
},
// templateLiteralEmptyEnds
{
code: wrap`\`const a = "1";
${PARENT_INDENT}\``,
output: wrap`\`
const a = "1";
${PARENT_INDENT}\``,
errors: [
{
messageId: 'templateLiteralEmptyEnds',
},
],
},
{
code: wrap`\`
${CODE_INDENT}const a = "1";\``,
output: wrap`\`
${CODE_INDENT}const a = "1";
\``,
errors: [
{
messageId: 'templateLiteralEmptyEnds',
},
],
},
{
code: wrap`\`const a = "1";
${CODE_INDENT}const b = "2";\``,
output: wrap`\`
const a = "1";
${CODE_INDENT}const b = "2";
\``,
errors: [
{
messageId: 'templateLiteralEmptyEnds',
},
],
},
// templateLiteralLastLineIndent
{
code: wrap`\`
${CODE_INDENT}const a = "1";
\``,
output: wrap`\`
${CODE_INDENT}const a = "1";
${PARENT_INDENT}\``,
errors: [
{
messageId: 'templateLiteralLastLineIndent',
},
],
},
{
code: wrap`\`
${CODE_INDENT}const a = "1";
\``,
output: wrap`\`
${CODE_INDENT}const a = "1";
${PARENT_INDENT}\``,
errors: [
{
messageId: 'templateLiteralLastLineIndent',
},
],
},
// templateStringRequiresIndent
{
code: wrap`\`
const a = "1";
${PARENT_INDENT}\``,
errors: [
{
messageId: 'templateStringRequiresIndent',
data: {
indent: CODE_INDENT.length,
},
},
],
},
{
code: `
ruleTester.run({
valid: [
\`
const a = "1";
\`,
],
});
`,
errors: [
{
messageId: 'templateStringRequiresIndent',
data: {
indent: 6,
},
},
],
},
// templateStringMinimumIndent
{
code: wrap`\`
${CODE_INDENT}const a = "1";
const b = "2";
${PARENT_INDENT}\``,
errors: [
{
messageId: 'templateStringMinimumIndent',
data: {
indent: CODE_INDENT.length,
},
},
],
},
// invalidFormatting
{
code: wrap`\`
${CODE_INDENT}const a="1";
${CODE_INDENT} const b = "2";
${PARENT_INDENT}\``,
output: wrap`\`
${CODE_INDENT}const a = '1';
${CODE_INDENT}const b = '2';
${PARENT_INDENT}\``,
errors: [
{
messageId: 'invalidFormatting',
},
],
},
{
code: wrap`\`
${CODE_INDENT}const a=\\\`\\\${a}\\\`;
${PARENT_INDENT}\``,
// make sure it escapes backticks
output: wrap`\`
${CODE_INDENT}const a = \\\`\\\${a}\\\`;
${PARENT_INDENT}\``,
errors: [
{
messageId: 'invalidFormatting',
},
],
},
// sanity check that it runs on both output and code properties
{
code: wrapWithOutput`\`
${CODE_INDENT}const a="1";
${CODE_INDENT} const b = "2";
${PARENT_INDENT}\``,
output: wrapWithOutput`\`
${CODE_INDENT}const a = '1';
${CODE_INDENT}const b = '2';
${PARENT_INDENT}\``,
errors: [
{
messageId: 'invalidFormattingErrorTest',
},
{
messageId: 'invalidFormattingErrorTest',
},
],
},
// sanity check that it handles suggestion output
{
code: `
ruleTester.run({
valid: [],
invalid: [
{
code: 'const x=1;',
errors: [
{
messageId: 'foo',
suggestions: [
{
messageId: 'bar',
output: 'const x=1;',
},
],
},
],
},
],
});
`,
output: `
ruleTester.run({
valid: [],
invalid: [
{
code: 'const x = 1;',
errors: [
{
messageId: 'foo',
suggestions: [
{
messageId: 'bar',
output: 'const x = 1;',
},
],
},
],
},
],
});
`,
errors: [
{
messageId: 'invalidFormattingErrorTest',
},
{
messageId: 'invalidFormattingErrorTest',
},
],
},
// sanity check that it runs on all tests
{
code: `
ruleTester.run({
valid: [
{
code: \`foo\`,
},
{
code: \`foo
\`,
},
{
code: \`
foo\`,
},
],
invalid: [
{
code: \`foo\`,
},
{
code: \`foo
\`,
},
{
code: \`
foo\`,
},
],
});
`,
output: `
ruleTester.run({
valid: [
{
code: 'foo',
},
{
code: \`
foo
\`,
},
{
code: \`
foo
\`,
},
],
invalid: [
{
code: 'foo',
},
{
code: \`
foo
\`,
},
{
code: \`
foo
\`,
},
],
});
`,
errors: [
{
messageId: 'singleLineQuotes',
},
{
messageId: 'templateLiteralEmptyEnds',
},
{
messageId: 'templateLiteralEmptyEnds',
},
{
messageId: 'singleLineQuotes',
},
{
messageId: 'templateLiteralEmptyEnds',
},
{
messageId: 'templateLiteralEmptyEnds',
},
],
},
// handles prettier errors
{
code: wrap`'const x = ";'`,
errors: [
{
messageId: 'prettierException',
data: {
message: 'Unterminated string literal.',
},
},
],
},
// checks tests with .trimRight calls
{
code: wrap`'const a=1;'.trimRight()`,
output: wrap`'const a = 1;'.trimRight()`,
errors: [
{
messageId: 'invalidFormatting',
},
],
},
{
code: wrap`\`const a = "1";
${CODE_INDENT}\`.trimRight()`,
output: wrap`\`
const a = "1";
${CODE_INDENT}\`.trimRight()`,
errors: [
{
messageId: 'templateLiteralEmptyEnds',
},
],
},
],
}); | the_stack |
import { dirname, join } from 'path';
import { promisify } from 'util';
import { copy } from 'fs-extra';
import * as inquirer from 'inquirer';
import * as mkdirp from 'mkdirp';
import {
logger,
isOfficial
} from '@hint/utils';
import {
cwd,
readFile,
writeFileAsync
} from '@hint/utils-fs';
import {
normalizeStringByDelimiter,
toCamelCase,
toPascalCase
} from '@hint/utils-string';
import { Category } from '@hint/utils-types';
import { HintScope } from 'hint';
import Handlebars, { compileTemplate, escapeSafeString } from './handlebars-utils';
/*
* ------------------------------------------------------------------------------
* Types.
* ------------------------------------------------------------------------------
*/
/** A map that matches usecases with events. */
const events: Map<string, string[]> = new Map([
['dom', ['ElementFound']],
['request', ['FetchStart', 'FetchEnd', 'FetchError']],
['thirdPartyService', ['FetchStart', 'FetchEnd']],
['jsInjection', ['ScanEnd']]
]);
/** Usage categories that the new hint applies to */
export type UseCase = {
[key: string]: any;
/** Hint applies to DOM */
dom: boolean;
/** Hint applies to resource request */
request: boolean;
/** Hint applies to third party service */
thirdPartyService: boolean;
/** Hint applies to JS injection */
jsInjection: boolean;
};
/** Generate a new hint */
export interface INewHint {
/** Name of the new hint */
name: string;
/** Name of the hint normalized */
normalizedName: string;
/** Category of the new hint */
category: Category;
/** Description of the new hint */
description: hbs.SafeString;
/** Element type if `dom` is selected in useCase */
elementType?: string;
/** Events that should be subscribed to */
events: string;
/** Usage categories that the new hint applies to */
useCase?: UseCase;
/** If the hint works with local files */
scope: HintScope;
/** Parent name for multi hints packages */
parentName: string;
}
export enum QuestionsType {
/** Main questions to create a simple hints or a package with multiples hints */
main = 'main',
/** Questions to add more hints to the package */
hint = 'hint'
}
/*
* ------------------------------------------------------------------------------
* Classes and dependencies.
* ------------------------------------------------------------------------------
*/
/** Get all events associted with a particular use case. */
const getEventsByUseCase = (useCase: string): string => {
const relatedEvents = events.get(useCase);
/* istanbul ignore if */
if (!relatedEvents) {
return '';
}
return relatedEvents.join(', ');
};
class NewHint implements INewHint {
public name: string;
public normalizedName: string;
public className: string;
public category: Category;
public description: hbs.SafeString;
public elementType?: string;
public events: string;
public scope: HintScope;
public isHint: Boolean = true;
public parentName: string;
public useCase: UseCase = {
dom: false,
jsInjection: false,
request: false,
thirdPartyService: false
};
public constructor(hintData: inquirer.Answers, parentName?: string) {
this.name = hintData.name;
this.normalizedName = normalizeStringByDelimiter(hintData.name, '-');
this.className = `${parentName ? toPascalCase(parentName) : ''}${toPascalCase(this.normalizedName)}Hint`;
this.category = hintData.category || Category.other;
this.description = escapeSafeString(hintData.description);
this.elementType = hintData.elementType;
this.events = getEventsByUseCase(hintData.useCase);
this.useCase[hintData.useCase] = true;
this.scope = hintData.scope;
this.parentName = parentName || '';
}
}
class HintPackage {
public name: string;
public description: hbs.SafeString;
public isMulti: boolean;
public normalizedName: string;
public official: boolean;
public packageMain: string;
public packageName: string;
public hints: INewHint[];
public destination: string;
public isHint: boolean = true;
public constructor(data: inquirer.Answers) {
this.name = data.name;
this.isMulti = data.multi;
this.normalizedName = normalizeStringByDelimiter(data.name, '-');
this.description = escapeSafeString(data.description);
this.official = data.official;
const prefix = this.official ? '@hint/hint' : 'hint'; // package.json#name
this.packageName = `${prefix}-${this.normalizedName}`;
this.hints = [];
if (this.isMulti) {
this.packageMain = `dist/src/index.js`; // package.json#main
(data.hints as inquirer.Answers[]).forEach((hint) => {
this.hints.push(new NewHint(hint, this.normalizedName));
});
} else {
this.packageMain = `dist/src/hint.js`; // package.json#main
this.hints.push(new NewHint(data));
}
if (this.official) {
/**
* If we are creating an official package it should be under `/packages/`
* but it is very common to run it from the root of the project so we
* take into account that scenario and add the folder if needed.
*/
const root = cwd();
const packagesPath = root.endsWith('packages') ?
'' :
'packages';
this.destination = join(root, packagesPath, `hint-${this.normalizedName}`);
} else {
this.destination = join(cwd(), `hint-${this.normalizedName}`);
}
}
}
/*
* ------------------------------------------------------------------------------
* Constants and Private functions.
* ------------------------------------------------------------------------------
*/
const mkdirpAsync = promisify(mkdirp) as (dir: string) => Promise<void>;
/** Name of the package to use as a template. */
const TEMPLATE_PATH = './templates';
const SHARED_TEMPLATE_PATH = './shared-templates';
const partialEventCode = readFile(join(__dirname, 'templates', 'partial-event-code.hbs'));
Handlebars.registerPartial('event-code', partialEventCode);
Handlebars.registerHelper('toCamelCase', toCamelCase);
/** List hint categories. */
const categories: any[] = [];
for (const [, value] of Object.entries(Category)) {
if (value !== 'other') {
categories.push({ name: value });
}
}
/** List of scopes */
const scopes: any[] = [];
for (const [, value] of Object.entries(HintScope)) {
scopes.push({ name: value });
}
/** List of different use cases of a hint. */
const useCases = [
{
name: 'DOM',
value: 'dom'
},
{
name: 'Resource Request',
value: 'request'
},
{
name: 'Third Party Service',
value: 'thirdPartyService'
},
{
name: 'JS injection',
value: 'jsInjection'
}
];
/** List of questions to prompt the user. */
export const questions = (type: QuestionsType): inquirer.QuestionCollection => {
/* istanbul ignore next */
const notEmpty = (value: string) => {
return value.trim() !== '';
};
/* istanbul ignore next */
return [{
message: `Is this a package with multiple hints? (yes)`,
name: 'multi',
type: 'confirm',
when: () => {
return type === QuestionsType.main;
}
},
{
default(answers: inquirer.Answers) {
return answers.multi ? 'newPackage' : 'newHint';
},
message(answers: inquirer.Answers) {
return `What's the name of this new ${answers.multi ? 'package' : 'hint'}?`;
},
name: 'name',
type: 'input',
validate: notEmpty
},
{
default(answers: inquirer.Answers) {
return `Description for ${answers.name}`;
},
message(answers: inquirer.Answers) {
return `What's the description of this new ${answers.multi ? 'package' : 'hint'} '${answers.name}'?`;
},
name: 'description',
type: 'input',
validate: notEmpty
},
{
choices: categories,
default: Category.compatibility,
message: 'Please select the category of this new hint:',
name: 'category',
type: 'list',
when(answers: inquirer.Answers) {
return !answers.multi;
}
},
{
choices: useCases,
default: 'dom',
message: 'Please select the category of use case:',
name: 'useCase',
type: 'list',
when(answers: inquirer.Answers) {
return !answers.multi;
}
},
{
default: 'div',
message: 'What DOM element does the hint need access to?',
name: 'elementType',
type: 'input',
validate: notEmpty,
when: (answers: inquirer.Answers) => {
return answers.useCase === 'dom';
}
},
{
choices: scopes,
default: HintScope.any,
message: 'Please select the scope of this new hint:',
name: 'scope',
type: 'list',
when(answers: inquirer.Answers) {
return !answers.multi;
}
},
{
default: true,
message: 'Want to add more hints (yes)?',
name: 'again',
type: 'confirm',
when: () => {
return type === QuestionsType.hint;
}
}];
};
/** Copies the required files for no official hints. */
const copyFiles = async (origin: string, destination: string) => {
logger.log(`Creating new hint in ${destination}`);
await copy(origin, destination);
logger.log('External files copied');
};
/** Copies and processes the required files for a hint package (multi or not). */
const generateHintFiles = async (destination: string, data: HintPackage) => {
const commonFiles = [
{
destination: join(destination, 'README.md'),
path: join(__dirname, TEMPLATE_PATH, 'readme.md.hbs')
},
{
destination: join(destination, 'tsconfig.json'),
path: join(__dirname, SHARED_TEMPLATE_PATH, 'tsconfig.json.hbs')
},
{
destination: join(destination, 'package.json'),
path: join(__dirname, SHARED_TEMPLATE_PATH, 'package.hbs')
}];
/**
* `index.ts` is only necessary if we have multiple files. Otherwise
* `package.json#main` points to `hint.ts`
*/
if (data.isMulti) {
commonFiles.push({
destination: join(destination, 'src', `index.ts`),
path: join(__dirname, TEMPLATE_PATH, 'index.ts.hbs')
});
}
if (!data.official) {
commonFiles.push({
destination: join(destination, '.hintrc'),
path: join(__dirname, SHARED_TEMPLATE_PATH, 'config.hbs')
});
}
const hintFile = {
destination: join(destination, 'src'),
path: join(__dirname, TEMPLATE_PATH, 'hint.ts.hbs')
};
const metaIndexFile = {
destination: join(destination, 'src'),
path: join(__dirname, TEMPLATE_PATH, 'meta-index.ts.hbs')
};
const metaFile = {
destination: join(destination, 'src'),
path: join(__dirname, TEMPLATE_PATH, 'meta.ts.hbs')
};
const testFile = {
destination: join(destination, 'tests'),
path: join(__dirname, TEMPLATE_PATH, 'tests.ts.hbs')
};
const docFile = {
destination: join(destination, 'docs'),
path: join(__dirname, TEMPLATE_PATH, 'hint-doc.hbs')
};
for (const file of commonFiles) {
const { destination: dest, path: p } = file;
const fileContent = await compileTemplate(p, data);
await mkdirpAsync(dirname(dest));
await writeFileAsync(dest, fileContent);
}
// For packages with multiple hints, we need to create an "index" meta file.
if (data.isMulti) {
const metaIndexContent = await compileTemplate(metaIndexFile.path, data);
// e.g.: hint-ssllabs/src/meta.ts
const metaIndexPath = join(metaIndexFile.destination, 'meta.ts');
await mkdirpAsync(dirname(metaIndexPath));
await writeFileAsync(metaIndexPath, metaIndexContent);
}
for (const hint of data.hints) {
const [hintContent, testContent, metaContent] = await Promise.all([
compileTemplate(hintFile.path, { hint, packageData: data }),
compileTemplate(testFile.path, hint),
compileTemplate(metaFile.path, { hint, packageData: data })
]);
const { metaPath, hintPath, testPath } = data.isMulti ?
{
hintPath: join(hintFile.destination, `${hint.normalizedName}.ts`),
metaPath: join(metaFile.destination, 'meta', `${hint.normalizedName}.ts`),
testPath: join(testFile.destination, `${hint.normalizedName}.ts`)
} :
{
hintPath: join(hintFile.destination, 'hint.ts'),
metaPath: join(metaFile.destination, 'meta.ts'),
testPath: join(testFile.destination, `tests.ts`)
};
await Promise.all([mkdirpAsync(dirname(hintPath)), mkdirpAsync(dirname(testPath)), mkdirpAsync(dirname(metaPath))]);
await Promise.all([writeFileAsync(hintPath, hintContent), writeFileAsync(testPath, testContent), writeFileAsync(metaPath, metaContent)]);
if (data.isMulti) {
const docContent = await compileTemplate(docFile.path, hint);
// e.g.: hint-typescript-config/docs/is-valid.ts
const docPath = join(docFile.destination, `${hint.normalizedName}.md`);
await mkdirpAsync(dirname(docPath));
await writeFileAsync(docPath, docContent);
}
}
// Create `_locales` directory
if (data.official) {
const localeDir = {
destination: join(destination, 'src', '_locales', 'en', 'messages.json'),
path: join(__dirname, TEMPLATE_PATH, 'locales-messages.json.hbs')
};
const localesContent = await compileTemplate(localeDir.path, data);
await mkdirpAsync(dirname(localeDir.destination));
await writeFileAsync(localeDir.destination, localesContent);
}
};
/** Initializes a wizard to create a new hint */
export default async (): Promise<boolean> => {
try {
const results = await inquirer.prompt(questions(QuestionsType.main));
const hints: inquirer.Answers[] = [];
results.official = await isOfficial();
const askHints = async () => {
const hint = await inquirer.prompt(questions(QuestionsType.hint));
hints.push(hint);
if (hint.again) {
await askHints();
}
};
if (results.multi) {
await askHints();
}
results.hints = hints;
const hintPackage = new HintPackage(results);
const noOfficialOrigin: string = join(__dirname, 'no-official-files');
const files: string = join(__dirname, 'files');
if (!hintPackage.official) {
await copyFiles(noOfficialOrigin, hintPackage.destination);
}
await copyFiles(files, hintPackage.destination);
await generateHintFiles(hintPackage.destination, hintPackage);
logger.log(`
New ${hintPackage.isMulti ? 'package' : 'hint'} ${hintPackage.name} created in ${hintPackage.destination}
--------------------------------------
---- How to use ----
--------------------------------------`);
if (hintPackage.official) {
logger.log(`1. Run 'yarn' to install the dependencies.
2. Go to the folder 'packages/hint-${hintPackage.normalizedName}'.
3. Run 'yarn build' to build the project.
4. Go to the folder 'packages/hint'.
5. Add your hint to '.hintrc'.
6. Run 'yarn hint https://YourUrl' to analyze your site.`);
} else {
logger.log(`1. Go to the folder 'hint-${hintPackage.normalizedName}'.
2. Run 'npm run init' to install all the dependencies and build the project.
3. Run 'npm run hint -- https://YourUrl' to analyze you site.`);
}
return true;
} catch (e) {
/* istanbul ignore next */{ // eslint-disable-line no-lone-blocks
logger.error('Error trying to create new hint');
logger.error(e);
return false;
}
}
}; | the_stack |
import * as React from "react"
import { scaleThreshold, scaleLinear, ScaleLinear } from "d3-scale"
import { interpolateLab } from "d3-interpolate"
import classnames from "classnames"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faInfoCircle } from "@fortawesome/free-solid-svg-icons/faInfoCircle"
import { faExclamationCircle } from "@fortawesome/free-solid-svg-icons/faExclamationCircle"
import { faCheckCircle } from "@fortawesome/free-regular-svg-icons/faCheckCircle"
import { Tippy } from "../../grapher/chart/Tippy"
import {
CovidTableHeaderCell as HeaderCell,
CovidTableHeaderCellProps,
} from "./CovidTableHeaderCell"
import {
CovidSortKey,
CovidCountryDatum,
CovidDatum,
NounGenerator,
CovidDoublingRange,
} from "./CovidTypes"
import { formatDate, formatInt } from "./CovidUtils"
import { nouns } from "./CovidConstants"
import { CovidDoublingTooltip } from "./CovidDoublingTooltip"
import { SparkBarTimeSeriesValue } from "../../grapher/sparkBars/SparkBarTimeSeriesValue"
import { SparkBars, SparkBarsProps } from "../../grapher/sparkBars/SparkBars"
export enum CovidTableColumnKey {
location = "location",
locationTests = "locationTests",
totalCases = "totalCases",
newCases = "newCases",
totalDeaths = "totalDeaths",
newDeaths = "newDeaths",
daysToDoubleCases = "daysToDoubleCases",
daysToDoubleDeaths = "daysToDoubleDeaths",
totalTests = "totalTests",
testDate = "testDate",
testSource = "testSource",
}
export type CovidTableHeaderSpec = Omit<
CovidTableHeaderCellProps,
"children" | "sortKey"
> & {
isMobile: boolean
lastUpdated: Date | undefined
}
export interface CovidTableCellSpec {
datum: CovidCountryDatum
isMobile: boolean
bars: Pick<
SparkBarsProps<CovidDatum>,
"data" | "xDomain" | "x" | "currentX" | "highlightedX" | "onHover"
>
totalTestsBarScale: ScaleLinear<number, number>
countryColors: Map<string, string>
baseRowSpan: number
}
export interface CovidTableColumnSpec {
sortKey?: CovidSortKey
header: (props: CovidTableHeaderSpec) => JSX.Element
cell: (props: CovidTableCellSpec) => JSX.Element
}
type IntAccessor = (d: CovidDatum) => number | undefined
type RangeAccessor = (d: CovidCountryDatum) => CovidDoublingRange | undefined
// Deaths color scales
const deathsDoubingTextColorScale = scaleThreshold<number, string>()
.domain([12])
.range(["white", "rgba(0,0,0,0.5)"])
const deathsDoubingBackgColorScale = scaleLinear<string>()
.domain([1, 3, 13])
.range(["#8a0000", "#bf0000", "#eee"])
.interpolate(interpolateLab)
.clamp(true)
// Cases color scales
const casesDoubingTextColorScale = scaleThreshold<number, string>()
.domain([12])
.range(["white", "rgba(0,0,0,0.5)"])
const casesDoubingBackgColorScale = scaleLinear<string>()
.domain([1, 3, 13])
.range(["#b11c5b", "#CA3A77", "#eee"])
.interpolate(interpolateLab)
.clamp(true)
const daysToDoubleGenerator =
(
accessorDatum: IntAccessor,
accessorRange: RangeAccessor,
noun: NounGenerator,
doubingBackgColorScale: (n: number) => string,
doubingTextColorScale: (n: number) => string
) =>
(props: CovidTableCellSpec) => {
const { datum, bars, isMobile } = props
const range = accessorRange(datum)
return (
<React.Fragment>
<td className="doubling-days" rowSpan={props.baseRowSpan}>
{range !== undefined ? (
<>
<span>
<span className="label">doubled in</span> <br />
<span
className="days"
style={{
backgroundColor: doubingBackgColorScale(
range.length
),
color: doubingTextColorScale(
range.length
),
}}
>
{range.length}
{nouns.days(range.length)}
<Tippy
content={
<CovidDoublingTooltip
doublingRange={range}
noun={noun}
accessor={accessorDatum}
/>
}
maxWidth={260}
>
<span className="info-icon">
<FontAwesomeIcon
icon={faInfoCircle}
/>
</span>
</Tippy>
</span>
</span>
</>
) : (
<span className="no-data">
Not enough data available
</span>
)}
</td>
{isMobile && (
<td
className={`plot-cell measure--${noun()}`}
rowSpan={props.baseRowSpan}
>
<div className="trend">
<div className="plot">
<SparkBars<CovidDatum>
className="spark-bars covid-bars"
{...bars}
y={accessorDatum}
highlightedX={
range !== undefined
? bars.x(range.halfDay)
: undefined
}
/>
</div>
</div>
</td>
)}
</React.Fragment>
)
}
const totalGenerator =
(accessor: IntAccessor, noun: NounGenerator) =>
(props: CovidTableCellSpec) => {
const { bars, datum } = props
return (
<td
className={`plot-cell measure--${noun()}`}
rowSpan={props.baseRowSpan}
>
<div className="trend">
<div className="plot">
<SparkBars<CovidDatum>
className="spark-bars covid-bars"
{...bars}
y={accessor}
renderValue={(d) =>
d && accessor(d) !== undefined ? (
<SparkBarTimeSeriesValue
className="highlighted"
value={formatInt(accessor(d))}
displayDate={formatDate(d.date)}
/>
) : undefined
}
/>
</div>
<div className="value">
{datum.latest &&
accessor(datum.latest) !== undefined && (
<SparkBarTimeSeriesValue
className="current"
value={`${formatInt(
accessor(datum.latest)
)} total`}
displayDate={formatDate(datum.latest.date)}
latest={true}
/>
)}
</div>
</div>
</td>
)
}
const newGenerator =
(accessor: IntAccessor, noun: NounGenerator) =>
(props: CovidTableCellSpec) => {
const { bars, datum } = props
return (
<td
className={`plot-cell measure--${noun()}`}
rowSpan={props.baseRowSpan}
>
<div className="trend">
<div className="plot">
<SparkBars<CovidDatum>
className="spark-bars covid-bars"
{...bars}
y={accessor}
renderValue={(d) =>
d && accessor(d) !== undefined ? (
<SparkBarTimeSeriesValue
className="highlighted"
value={formatInt(accessor(d), "", {
showPlus: true,
})}
displayDate={d && formatDate(d.date)}
/>
) : undefined
}
/>
</div>
<div className="value">
{datum.latest && accessor(datum.latest) !== undefined && (
<SparkBarTimeSeriesValue
className="current"
value={`${formatInt(
accessor(datum.latest),
"",
{
showPlus: true,
}
)} new`}
displayDate={formatDate(datum.latest.date)}
latest={true}
/>
)}
</div>
</div>
</td>
)
}
// TODO
// There can be columns you cannot sort by, therefore don't have accessors (accessors return undefined is best to implement)
// There can be sorting that doesn't have a column
export const columns: Record<CovidTableColumnKey, CovidTableColumnSpec> = {
location: {
sortKey: CovidSortKey.location,
header: (props) => (
<HeaderCell
{...props}
className="location"
sortKey={CovidSortKey.location}
>
<strong>Location</strong>
</HeaderCell>
),
cell: (props) => (
<td className="location" rowSpan={props.baseRowSpan}>
{props.datum.location}
</td>
),
},
locationTests: {
sortKey: CovidSortKey.location,
header: (props) => (
<HeaderCell
{...props}
className="location-tests"
sortKey={CovidSortKey.location}
>
<strong>Location</strong>
</HeaderCell>
),
cell: (props) => (
<td className="location-tests" rowSpan={props.baseRowSpan}>
{props.datum.location}
</td>
),
},
daysToDoubleCases: {
sortKey: CovidSortKey.daysToDoubleCases,
header: (props) => (
<HeaderCell
{...props}
className={`measure--${nouns.cases()}`}
sortKey={CovidSortKey.daysToDoubleCases}
colSpan={props.isMobile ? 2 : 1}
>
How long did it take for the number of{" "}
<strong>
total confirmed <span className="measure">cases</span> to
double
</strong>
?
</HeaderCell>
),
cell: daysToDoubleGenerator(
(d) => d.totalCases,
(d) => d.caseDoublingRange,
nouns.cases,
casesDoubingBackgColorScale,
casesDoubingTextColorScale
),
},
daysToDoubleDeaths: {
sortKey: CovidSortKey.daysToDoubleDeaths,
header: (props) => (
<HeaderCell
{...props}
className={`measure--${nouns.deaths()}`}
sortKey={CovidSortKey.daysToDoubleDeaths}
colSpan={props.isMobile ? 2 : 1}
>
How long did it take for the number of{" "}
<strong>
total confirmed <span className="measure">deaths</span> to
double
</strong>
?
</HeaderCell>
),
cell: daysToDoubleGenerator(
(d) => d.totalDeaths,
(d) => d.deathDoublingRange,
nouns.deaths,
deathsDoubingBackgColorScale,
deathsDoubingTextColorScale
),
},
totalCases: {
sortKey: CovidSortKey.totalCases,
header: (props) => (
<HeaderCell
{...props}
className={`measure--${nouns.cases()}`}
sortKey={CovidSortKey.totalCases}
>
<strong>
Total confirmed <span className="measure">cases</span>
</strong>{" "}
<br />
<span className="note">
JHU data.{" "}
{props.lastUpdated !== undefined ? (
<>
Up to date for 10 AM (CET) on{" "}
{formatDate(props.lastUpdated)}.
</>
) : undefined}
</span>
</HeaderCell>
),
cell: totalGenerator((d) => d.totalCases, nouns.cases),
},
totalDeaths: {
sortKey: CovidSortKey.totalDeaths,
header: (props) => (
<HeaderCell
{...props}
className={`measure--${nouns.deaths()}`}
sortKey={CovidSortKey.totalDeaths}
>
<strong>
Total confirmed <span className="measure">deaths</span>
</strong>{" "}
<br />
<span className="note">
JHU data.{" "}
{props.lastUpdated !== undefined ? (
<>
Up to date for 10 AM (CET) on{" "}
{formatDate(props.lastUpdated)}.
</>
) : undefined}
</span>
</HeaderCell>
),
cell: totalGenerator((d) => d.totalDeaths, nouns.deaths),
},
newCases: {
sortKey: CovidSortKey.newCases,
header: (props) => (
<HeaderCell
{...props}
className={`measure--${nouns.cases()}`}
sortKey={CovidSortKey.newCases}
>
<strong>
Daily new confirmed <span className="measure">cases</span>
</strong>{" "}
<br />
<span className="note">
JHU data.{" "}
{props.lastUpdated !== undefined ? (
<>
Up to date for 10 AM (CET) on{" "}
{formatDate(props.lastUpdated)}.
</>
) : undefined}
</span>
</HeaderCell>
),
cell: newGenerator((d) => d.newCases, nouns.cases),
},
newDeaths: {
sortKey: CovidSortKey.newDeaths,
header: (props) => (
<HeaderCell
{...props}
className={`measure--${nouns.deaths()}`}
sortKey={CovidSortKey.newDeaths}
>
<strong>
Daily new confirmed <span className="measure">deaths</span>
</strong>{" "}
<br />
<span className="note">
JHU data.{" "}
{props.lastUpdated !== undefined ? (
<>
Up to date for 10 AM (CET) on{" "}
{formatDate(props.lastUpdated)}.
</>
) : undefined}
</span>
</HeaderCell>
),
cell: newGenerator((d) => d.newDeaths, nouns.deaths),
},
totalTests: {
sortKey: CovidSortKey.totalTests,
header: (props) => (
<HeaderCell
{...props}
className={`measure--${nouns.tests()}`}
sortKey={CovidSortKey.totalTests}
colSpan={2}
>
<strong>
Total <span className="measure">tests</span>
</strong>
</HeaderCell>
),
cell: (props) => (
<React.Fragment>
<td
className={`measure--${nouns.tests()} total-tests`}
rowSpan={1}
>
{formatInt(
props.datum.latestWithTests?.tests?.totalTests,
""
)}
</td>
<td
className={`measure--${nouns.tests()} total-tests-bar`}
rowSpan={1}
>
{props.datum.latestWithTests?.tests?.totalTests !==
undefined && (
<div
className="bar"
style={{
backgroundColor: props.countryColors.get(
props.datum.location
),
width: `${
props.totalTestsBarScale(
props.datum.latestWithTests.tests
.totalTests
) * 100
}%`,
}}
/>
)}
</td>
</React.Fragment>
),
},
testDate: {
sortKey: CovidSortKey.testDate,
header: (props) => (
<HeaderCell
{...props}
className={`measure--${nouns.tests()}`}
sortKey={CovidSortKey.testDate}
>
<strong>Date</strong>
</HeaderCell>
),
cell: (props) => (
<td className="date" rowSpan={1}>
{formatDate(props.datum.latestWithTests?.date, "")}
</td>
),
},
testSource: {
header: (props) => (
<HeaderCell {...props} className={`measure--${nouns.tests()}`}>
<strong>Source</strong>
</HeaderCell>
),
cell: (props) => {
if (props.datum.latestWithTests?.tests === undefined)
return <td></td>
const { date, tests } = props.datum.latestWithTests
const {
sourceURL,
sourceLabel,
publicationDate,
remarks,
nonOfficial,
} = tests
return (
<td className="testing-notes">
<span
className={classnames("official", {
"is-official": !nonOfficial,
})}
>
<Tippy
content={
<div className="covid-tooltip">
<a href={sourceURL}>{sourceLabel}</a>
<br />
Refers to: {formatDate(date)}
<br />
Published: {formatDate(publicationDate)}
<br />
Remarks: {remarks}
</div>
}
>
<span>
{nonOfficial ? (
<FontAwesomeIcon
icon={faExclamationCircle}
/>
) : (
<FontAwesomeIcon icon={faCheckCircle} />
)}
</span>
</Tippy>
</span>
</td>
)
},
},
} | the_stack |
import {
calcBasePosition,
calcStartPosition,
getFontSize,
} from "../internal/canvases";
import type { ColorDef } from "../ts-types";
import type { PaddingOption } from "../internal/canvases";
const { ceil, PI } = Math;
export function strokeColorsRect(
ctx: CanvasRenderingContext2D,
borderColors: [
ColorDef | null,
ColorDef | null,
ColorDef | null,
ColorDef | null
],
left: number,
top: number,
width: number,
height: number
): void {
type Position = { x: number; y: number };
function strokeRectLines(
positions: [Position, Position, Position, Position, Position]
): void {
for (let i = 0; i < borderColors.length; i++) {
const color = borderColors[i];
const preColor = borderColors[i - 1];
if (color) {
if (preColor !== color) {
if (preColor) {
ctx.strokeStyle = preColor;
ctx.stroke();
}
const pos1 = positions[i];
ctx.beginPath();
ctx.moveTo(pos1.x, pos1.y);
}
const pos2 = positions[i + 1];
ctx.lineTo(pos2.x, pos2.y);
} else {
if (preColor) {
ctx.strokeStyle = preColor;
ctx.stroke();
}
}
}
const preColor = borderColors[borderColors.length - 1];
if (preColor) {
ctx.strokeStyle = preColor;
ctx.stroke();
}
}
if (
borderColors[0] === borderColors[1] &&
borderColors[0] === borderColors[2] &&
borderColors[0] === borderColors[3]
) {
if (borderColors[0]) {
ctx.strokeStyle = borderColors[0];
ctx.strokeRect(left, top, width, height);
}
} else {
strokeRectLines([
{ x: left, y: top },
{ x: left + width, y: top },
{ x: left + width, y: top + height },
{ x: left, y: top + height },
{ x: left, y: top },
]);
}
}
export function roundRect(
ctx: CanvasRenderingContext2D,
left: number,
top: number,
width: number,
height: number,
radius: number
): void {
ctx.beginPath();
ctx.arc(left + radius, top + radius, radius, -PI, -0.5 * PI, false);
ctx.arc(left + width - radius, top + radius, radius, -0.5 * PI, 0, false);
ctx.arc(
left + width - radius,
top + height - radius,
radius,
0,
0.5 * PI,
false
);
ctx.arc(left + radius, top + height - radius, radius, 0.5 * PI, PI, false);
ctx.closePath();
}
export function fillRoundRect(
ctx: CanvasRenderingContext2D,
left: number,
top: number,
width: number,
height: number,
radius: number
): void {
roundRect(ctx, left, top, width, height, radius);
ctx.fill();
}
export function strokeRoundRect(
ctx: CanvasRenderingContext2D,
left: number,
top: number,
width: number,
height: number,
radius: number
): void {
roundRect(ctx, left, top, width, height, radius);
ctx.stroke();
}
export function fillCircle(
ctx: CanvasRenderingContext2D,
left: number,
top: number,
width: number,
height: number
): void {
const min = Math.min(width, height) / 2;
ctx.beginPath();
ctx.arc(left + min, top + min, min, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
}
export function strokeCircle(
ctx: CanvasRenderingContext2D,
left: number,
top: number,
width: number,
height: number
): void {
const min = Math.min(width, height) / 2;
ctx.beginPath();
ctx.arc(left + min, top + min, min, 0, 2 * Math.PI);
ctx.closePath();
ctx.stroke();
}
export type FillTextRectOption = {
offset?: number;
padding?: PaddingOption;
};
export function fillTextRect(
ctx: CanvasRenderingContext2D,
text: string,
left: number,
top: number,
width: number,
height: number,
{ offset = 2, padding }: FillTextRectOption = {}
): void {
const rect = {
left,
top,
width,
height,
right: left + width,
bottom: top + height,
};
ctx.save();
try {
ctx.beginPath();
ctx.rect(rect.left, rect.top, rect.width, rect.height);
//clip
ctx.clip();
//文字描画
const pos = calcBasePosition(ctx, rect, {
offset,
padding,
});
ctx.fillText(text, pos.x, pos.y);
} finally {
ctx.restore();
}
}
export type DrawInlineImageRectOption = {
offset?: number;
padding?: PaddingOption;
};
export function drawInlineImageRect(
ctx: CanvasRenderingContext2D,
image: CanvasImageSource,
srcLeft: number,
srcTop: number,
srcWidth: number,
srcHeight: number,
destWidth: number,
destHeight: number,
left: number,
top: number,
width: number,
height: number,
{ offset = 2, padding }: DrawInlineImageRectOption = {}
): void {
const rect = {
left,
top,
width,
height,
right: left + width,
bottom: top + height,
};
ctx.save();
try {
ctx.beginPath();
ctx.rect(rect.left, rect.top, rect.width, rect.height);
//clip
ctx.clip();
//文字描画
const pos = calcStartPosition(ctx, rect, destWidth, destHeight, {
offset,
padding,
});
ctx.drawImage(
image,
srcLeft,
srcTop,
srcWidth,
srcHeight,
pos.x,
pos.y,
destWidth,
destHeight
);
} finally {
ctx.restore();
}
}
/**
* Returns an object containing the width of the checkbox.
* @param {CanvasRenderingContext2D} ctx canvas context
* @return {Object} Object containing the width of the checkbox
* @memberof cheetahGrid.tools.canvashelper
*/
export function measureCheckbox(ctx: CanvasRenderingContext2D): {
width: number;
} {
return {
width: getFontSize(ctx, null).width,
};
}
/**
* Returns an object containing the width of the radio button.
* @param {CanvasRenderingContext2D} ctx canvas context
* @return {Object} Object containing the width of the radio button
* @memberof cheetahGrid.tools.canvashelper
*/
export function measureRadioButton(ctx: CanvasRenderingContext2D): {
width: number;
} {
return {
width: getFontSize(ctx, null).width,
};
}
export type DrawCheckboxOption = {
uncheckBgColor?: ColorDef;
checkBgColor?: ColorDef;
borderColor?: ColorDef;
boxSize?: number;
};
/**
* draw Checkbox
* @param {CanvasRenderingContext2D} ctx canvas context
* @param {number} x The x coordinate where to start drawing the checkbox (relative to the canvas)
* @param {number} y The y coordinate where to start drawing the checkbox (relative to the canvas)
* @param {boolean|number} check checkbox check status
* @param {object} option option
* @return {void}
* @memberof cheetahGrid.tools.canvashelper
*/
export function drawCheckbox(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
check: number | boolean,
{
uncheckBgColor = "#FFF",
checkBgColor = "rgb(76, 73, 72)",
borderColor = "#000",
boxSize = measureCheckbox(ctx).width,
}: DrawCheckboxOption = {}
): void {
const checkPoint = typeof check === "number" ? (check > 1 ? 1 : check) : 1;
ctx.save();
try {
ctx.fillStyle = check ? checkBgColor : uncheckBgColor;
const leftX = ceil(x);
const topY = ceil(y);
const size = ceil(boxSize);
fillRoundRect(ctx, leftX - 1, topY - 1, size + 1, size + 1, boxSize / 5);
ctx.lineWidth = 1;
ctx.strokeStyle = borderColor;
strokeRoundRect(ctx, leftX - 0.5, topY - 0.5, size, size, boxSize / 5);
if (check) {
ctx.lineWidth = ceil(boxSize / 10);
ctx.strokeStyle = uncheckBgColor;
let leftWidth = boxSize / 4;
let rightWidth = (boxSize / 2) * 0.9;
const leftLeftPos = x + boxSize * 0.2;
const leftTopPos = y + boxSize / 2;
if (checkPoint < 0.5) {
leftWidth *= checkPoint * 2;
}
ctx.beginPath();
ctx.moveTo(leftLeftPos, leftTopPos);
ctx.lineTo(leftLeftPos + leftWidth, leftTopPos + leftWidth);
if (checkPoint > 0.5) {
if (checkPoint < 1) {
rightWidth *= (checkPoint - 0.5) * 2;
}
ctx.lineTo(
leftLeftPos + leftWidth + rightWidth,
leftTopPos + leftWidth - rightWidth
);
}
ctx.stroke();
}
} finally {
ctx.restore();
}
}
export type DrawRadioButtonOption = {
checkColor?: ColorDef;
borderColor?: ColorDef;
bgColor?: ColorDef;
boxSize?: number;
};
/**
* draw Radio button
* @param {CanvasRenderingContext2D} ctx canvas context
* @param {number} x The x coordinate where to start drawing the radio button (relative to the canvas)
* @param {number} y The y coordinate where to start drawing the radio button (relative to the canvas)
* @param {boolean|number} check radio button check status
* @param {object} option option
* @return {void}
* @memberof cheetahGrid.tools.canvashelper
*/
export function drawRadioButton(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
check: number | boolean,
{
checkColor = "rgb(76, 73, 72)",
borderColor = "#000",
bgColor = "#FFF",
boxSize = measureRadioButton(ctx).width,
}: DrawRadioButtonOption = {}
): void {
const ratio = typeof check === "number" ? (check > 1 ? 1 : check) : 1;
ctx.save();
try {
ctx.fillStyle = bgColor;
const leftX = ceil(x);
const topY = ceil(y);
const size = ceil(boxSize);
fillCircle(ctx, leftX - 1, topY - 1, size + 1, size + 1);
ctx.lineWidth = 1;
ctx.strokeStyle = borderColor;
strokeCircle(ctx, leftX - 0.5, topY - 0.5, size, size);
if (check) {
const checkSize = (size * ratio) / 2;
const padding = (size - checkSize) / 2;
ctx.fillStyle = checkColor;
fillCircle(
ctx,
ceil((leftX - 0.5 + padding) * 100) / 100,
ceil((topY - 0.5 + padding) * 100) / 100,
ceil(checkSize * 100) / 100,
ceil(checkSize * 100) / 100
);
}
} finally {
ctx.restore();
}
}
export type DrawButtonOption = {
backgroundColor?: ColorDef;
bgColor?: ColorDef;
radius?: number;
shadow?: {
color?: string;
blur?: number;
offsetX?: number;
offsetY?: number;
offset?: { x?: number; y?: number };
};
};
/**
* draw Button
*/
export function drawButton(
ctx: CanvasRenderingContext2D,
left: number,
top: number,
width: number,
height: number,
option: DrawButtonOption = {}
): void {
const {
backgroundColor = "#FFF",
bgColor = backgroundColor,
radius = 4,
shadow = {},
} = option;
ctx.save();
try {
ctx.fillStyle = bgColor;
if (shadow) {
const {
color = "rgba(0, 0, 0, 0.24)",
blur = 1,
offsetX = 0,
offsetY = 2,
offset: { x: ox = offsetX, y: oy = offsetY } = {},
} = shadow;
ctx.shadowColor = color;
ctx.shadowBlur = blur; //ぼかし
ctx.shadowOffsetX = ox;
ctx.shadowOffsetY = oy;
}
fillRoundRect(
ctx,
ceil(left),
ceil(top),
ceil(width),
ceil(height),
radius
);
} finally {
ctx.restore();
}
}
export type Canvashelper = {
roundRect: typeof roundRect;
fillRoundRect: typeof fillRoundRect;
strokeRoundRect: typeof strokeRoundRect;
drawCheckbox: typeof drawCheckbox;
measureCheckbox: typeof measureCheckbox;
fillTextRect: typeof fillTextRect;
drawButton: typeof drawButton;
drawInlineImageRect: typeof drawInlineImageRect;
strokeColorsRect: typeof strokeColorsRect;
}; | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace FormSocial_Profile {
interface Header extends DevKit.Controls.IHeader {
/** Identifies where the social profile originated from, such as Twitter, or Facebook. */
Community: DevKit.Controls.OptionSet;
/** Shows the score that determines the online social influence of the social profile. */
InfluenceScore: DevKit.Controls.Double;
/** Shows the user or team that is assigned to manage the record. This field is updated every time the record is assigned to a different user. */
OwnerId: DevKit.Controls.Lookup;
}
interface Tabs {
}
interface Body {
/** Identifies if the social profile has been blocked. */
Blocked: DevKit.Controls.Boolean;
/** Identifies where the social profile originated from, such as Twitter, or Facebook. */
Community: DevKit.Controls.OptionSet;
/** Shows the customer that this social profile belongs to. */
CustomerId: DevKit.Controls.Lookup;
/** Customer's Followers on the Social channel. */
msdyn_ocfollowercount: DevKit.Controls.Integer;
/** Customer's followings on the Social channel */
msdyn_ocfollowingcount: DevKit.Controls.Integer;
/** Customer's Friend count on the Social Channel */
msdyn_ocfriendcount: DevKit.Controls.Integer;
/** The phone number of the social profile. */
msdyn_phonenumber: DevKit.Controls.String;
/** Link to the Customer's Social Channel Profile image. */
msdyn_profileimagelink: DevKit.Controls.String;
/** Shows the display name of the customer on this social profile. */
ProfileFullName: DevKit.Controls.String;
/** Shows the customer that this social profile belongs to. */
ProfileLink: DevKit.Controls.String;
/** Shows the name of the social profile on the corresponding social channel. */
ProfileName: DevKit.Controls.String;
}
interface quickForm_related_sp_Body {
}
interface quickForm_related_sp extends DevKit.Controls.IQuickView {
Body: quickForm_related_sp_Body;
}
interface QuickForm {
related_sp: quickForm_related_sp;
}
}
class FormSocial_Profile extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Social_Profile
* @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 Social_Profile */
Body: DevKit.FormSocial_Profile.Body;
/** The Header section of form Social_Profile */
Header: DevKit.FormSocial_Profile.Header;
/** The QuickForm of form Social_Profile */
QuickForm: DevKit.FormSocial_Profile.QuickForm;
}
namespace FormSocial_Profile_for_Interactive_experience {
interface Header extends DevKit.Controls.IHeader {
/** Identifies where the social profile originated from, such as Twitter, or Facebook. */
Community: DevKit.Controls.OptionSet;
/** Shows the score that determines the online social influence of the social profile. */
InfluenceScore: DevKit.Controls.Double;
/** Shows the user or team that is assigned to manage the record. This field is updated every time the record is assigned to a different user. */
OwnerId: DevKit.Controls.Lookup;
}
interface tab_tab_2_Sections {
tab_2_section_1: DevKit.Controls.Section;
tab_2_section_2: DevKit.Controls.Section;
tab_2_section_3: DevKit.Controls.Section;
tab_2_section_4: DevKit.Controls.Section;
}
interface tab_tab_2 extends DevKit.Controls.ITab {
Section: tab_tab_2_Sections;
}
interface Tabs {
tab_2: tab_tab_2;
}
interface Body {
Tab: Tabs;
/** Identifies if the social profile has been blocked. */
Blocked: DevKit.Controls.Boolean;
/** Identifies where the social profile originated from, such as Twitter, or Facebook. */
Community: DevKit.Controls.OptionSet;
/** Shows the customer that this social profile belongs to. */
CustomerId: DevKit.Controls.Lookup;
/** Customer's Followers on the Social channel. */
msdyn_ocfollowercount: DevKit.Controls.Integer;
/** Customer's followings on the Social channel */
msdyn_ocfollowingcount: DevKit.Controls.Integer;
/** Customer's Friend count on the Social Channel */
msdyn_ocfriendcount: DevKit.Controls.Integer;
/** The phone number of the social profile. */
msdyn_phonenumber: DevKit.Controls.String;
/** Link to the Customer's Social Channel Profile image. */
msdyn_profileimagelink: DevKit.Controls.String;
/** Shows the display name of the customer on this social profile. */
ProfileFullName: DevKit.Controls.String;
/** Shows the customer that this social profile belongs to. */
ProfileLink: DevKit.Controls.String;
/** Shows the name of the social profile on the corresponding social channel. */
ProfileName: DevKit.Controls.String;
}
interface quickForm_customer_qfc_Body {
EMailAddress1: DevKit.Controls.QuickView;
Name: DevKit.Controls.QuickView;
Telephone1: DevKit.Controls.QuickView;
}
interface quickForm_related_sp_Body {
}
interface quickForm_customer_qfc extends DevKit.Controls.IQuickView {
Body: quickForm_customer_qfc_Body;
}
interface quickForm_related_sp extends DevKit.Controls.IQuickView {
Body: quickForm_related_sp_Body;
}
interface QuickForm {
customer_qfc: quickForm_customer_qfc;
related_sp: quickForm_related_sp;
}
}
class FormSocial_Profile_for_Interactive_experience extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Social_Profile_for_Interactive_experience
* @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 Social_Profile_for_Interactive_experience */
Body: DevKit.FormSocial_Profile_for_Interactive_experience.Body;
/** The Header section of form Social_Profile_for_Interactive_experience */
Header: DevKit.FormSocial_Profile_for_Interactive_experience.Header;
/** The QuickForm of form Social_Profile_for_Interactive_experience */
QuickForm: DevKit.FormSocial_Profile_for_Interactive_experience.QuickForm;
}
class SocialProfileApi {
/**
* DynamicsCrm.DevKit SocialProfileApi
* @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;
/** Identifies if the social profile has been blocked. */
Blocked: DevKit.WebApi.BooleanValue;
/** Identifies where the social profile originated from, such as Twitter, or Facebook. */
Community: DevKit.WebApi.OptionSetValue;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
customerid_account: DevKit.WebApi.LookupValue;
customerid_contact: DevKit.WebApi.LookupValue;
/** Select the parent account or parent contact for the contact */
CustomerIdYomiName: DevKit.WebApi.StringValue;
/** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Unique identifier of the data import or data migration that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Shows the score that determines the online social influence of the social profile. */
InfluenceScore: DevKit.WebApi.DoubleValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Customer's Followers on the Social channel. */
msdyn_ocfollowercount: DevKit.WebApi.IntegerValue;
/** Customer's followings on the Social channel */
msdyn_ocfollowingcount: DevKit.WebApi.IntegerValue;
/** Customer's Friend count on the Social Channel */
msdyn_ocfriendcount: DevKit.WebApi.IntegerValue;
/** Lookup for Twitter Handle entity. */
msdyn_octwitterhandleid: DevKit.WebApi.LookupValue;
/** The phone number of the social profile. */
msdyn_phonenumber: DevKit.WebApi.StringValue;
/** Link to the Customer's Social Channel Profile image. */
msdyn_profileimagelink: DevKit.WebApi.StringValue;
/** 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 of the team who owns the contact. */
OwningTeam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the user who owns the contact. */
OwningUser: DevKit.WebApi.LookupValueReadonly;
/** Shows the display name of the customer on this social profile. */
ProfileFullName: DevKit.WebApi.StringValue;
/** Shows the customer that this social profile belongs to. */
ProfileLink: DevKit.WebApi.StringValue;
/** Shows the name of the social profile on the corresponding social channel. */
ProfileName: DevKit.WebApi.StringValue;
/** Unique Identifier of the social profile name. */
SocialProfileId: DevKit.WebApi.GuidValue;
/** Status of the Social Profile */
StateCode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Social Profile */
StatusCode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Choose the local currency for the record to make sure budgets are reported in the correct currency. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** Unique ID of the Profile ID */
UniqueProfileID: DevKit.WebApi.StringValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version number of the social profile. */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace SocialProfile {
enum Community {
/** 5 */
Cortana,
/** 6 */
Direct_Line,
/** 8 */
Direct_Line_Speech,
/** 9 */
Email,
/** 1 */
Facebook,
/** 10 */
GroupMe,
/** 11 */
Kik,
/** 3 */
Line,
/** 7 */
Microsoft_Teams,
/** 0 */
Other,
/** 13 */
Skype,
/** 14 */
Slack,
/** 12 */
Telegram,
/** 2 */
Twitter,
/** 4 */
Wechat,
/** 15 */
WhatsApp
}
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':['Social Profile','Social Profile for Interactive experience'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { AxiosRequestConfig } from 'axios';
import BigNumber from 'bignumber.js';
import { tronBroadcast } from '../blockchain';
import { axios, validateBody } from '../connector/tatum';
import { TATUM_API_URL } from '../constants';
import { listing } from '../contracts/marketplace';
import abi from '../contracts/trc20/token_abi';
import bytecode from '../contracts/trc20/token_bytecode';
import trc721_abi from '../contracts/trc721/trc721_abi';
import trc721_bytecode from '../contracts/trc721/trc721_bytecode';
import {
CreateTronTrc10,
CreateTronTrc20,
Currency,
DeployTronMarketplaceListing,
FreezeTron,
GenerateTronCustodialAddress,
SmartContractMethodInvocation,
TransactionKMS,
TransferTron,
TransferTronTrc10,
TransferTronTrc20,
TronBurnTrc721,
TronDeployTrc721,
TronMintMultipleTrc721,
TronMintTrc721,
TronTransferTrc721,
TronUpdateCashbackTrc721
} from '../model';
import { obtainCustodialAddressType } from '../wallet';
// tslint:disable-next-line:no-var-requires
const TronWeb = require('tronweb');
const prepareTronWeb = (testnet: boolean, provider?: string) => {
const HttpProvider = TronWeb.providers.HttpProvider;
const url = provider || `${process.env.TATUM_API_URL || TATUM_API_URL}/v3/tron/node/${process.env.TATUM_API_KEY}`;
const fullNode = new HttpProvider(url);
const solidityNode = new HttpProvider(url);
const eventServer = new HttpProvider(url);
const tronWeb = new TronWeb(fullNode, solidityNode, eventServer)
tronWeb.setHeader({'TRON-PRO-API-KEY': process.env.TRON_PRO_API_KEY})
return tronWeb
}
/**
* Send Tron transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronTransaction = async (testnet: boolean, body: TransferTron) => {
return tronBroadcast(await prepareTronSignedTransaction(testnet, body), body.signatureId)
}
/**
* Send Tron Freeze balance transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const freezeTronTransaction = async (testnet: boolean, body: FreezeTron) => {
return tronBroadcast(await prepareTronFreezeTransaction(testnet, body), body.signatureId)
}
/**
* Send Tron TRC10 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronTrc10Transaction = async (testnet: boolean, body: TransferTronTrc10) => {
return tronBroadcast(await prepareTronTrc10SignedTransaction(testnet, body), body.signatureId)
}
/**
* Send Tron TRC20 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronTrc20Transaction = async (testnet: boolean, body: TransferTronTrc20) => {
return tronBroadcast(await prepareTronTrc20SignedTransaction(testnet, body), body.signatureId)
}
/**
* Create Tron TRC10 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const createTronTrc10Transaction = async (testnet: boolean, body: CreateTronTrc10) => {
return tronBroadcast(await prepareTronCreateTrc10SignedTransaction(testnet, body), body.signatureId)
}
/**
* Create Tron TRC20 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const createTronTrc20Transaction = async (testnet: boolean, body: CreateTronTrc20) => {
return tronBroadcast(await prepareTronCreateTrc20SignedTransaction(testnet, body), body.signatureId)
}
/**
* Sign Tron pending transaction from Tatum KMS
* @param tx pending transaction from KMS
* @param fromPrivateKey private key to sign transaction with.
* @param testnet mainnet or testnet version
* @returns transaction data to be broadcast to blockchain.
*/
export const signTronKMSTransaction = async (tx: TransactionKMS, fromPrivateKey: string, testnet: boolean) => {
if (tx.chain !== Currency.TRON) {
throw Error('Unsupported chain.')
}
const tronWeb = prepareTronWeb(testnet)
const transactionConfig = JSON.parse(tx.serializedTransaction)
return JSON.stringify(await tronWeb.trx.sign(transactionConfig, fromPrivateKey))
}
export const convertAddressFromHex = (address: string) => TronWeb.address.fromHex(address)
export const convertAddressToHex = (address: string) => TronWeb.address.toHex(address)
/**
* Send Tron deploy trc721 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronDeployTrc721SignedTransaction = async (testnet: boolean, body: TronDeployTrc721) =>
await tronBroadcast(await prepareTronDeployTrc721SignedTransaction(testnet, body), body.signatureId)
/**
* Send Tron generate custodial wallet transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronGenerateCustodialWalletSignedTransaction = async (testnet: boolean, body: GenerateTronCustodialAddress, provider?: string) =>
await tronBroadcast(await prepareTronGenerateCustodialWalletSignedTransaction(testnet, body, provider), body.signatureId)
/**
* Deploy new smart contract for NFT marketplace logic. Smart contract enables marketplace operator to create new listing for NFT (ERC-721/1155).
* @param testnet chain to work with
* @param body request data
* @param provider optional provider to enter. if not present, Tatum provider will be used.
* @returns {txId: string} Transaction ID of the operation, or signatureID in case of Tatum KMS
*/
export const sendTronDeployMarketplaceListingSignedTransaction = async (testnet: boolean, body: DeployTronMarketplaceListing, provider?: string) =>
await tronBroadcast(await prepareTronDeployMarketplaceListingSignedTransaction(testnet, body, provider), body.signatureId)
/**
* Send Tron mint cashback trc721 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronMintCashbackTrc721SignedTransaction = async (testnet: boolean, body: TronMintTrc721) =>
await tronBroadcast(await prepareTronMintCashbackTrc721SignedTransaction(testnet, body), body.signatureId)
/**
* Send Tron mint trc721 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronMintTrc721SignedTransaction = async (testnet: boolean, body: TronMintTrc721) =>
await tronBroadcast(await prepareTronMintTrc721SignedTransaction(testnet, body), body.signatureId)
/**
* Send Tron transfer trc721 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronTransferTrc721SignedTransaction = async (testnet: boolean, body: TronTransferTrc721) =>
await tronBroadcast(await prepareTronTransferTrc721SignedTransaction(testnet, body), body.signatureId)
/**
* Send Tron burn trc721 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronBurnTrc721SignedTransaction = async (testnet: boolean, body: TronBurnTrc721) =>
await tronBroadcast(await prepareTronBurnTrc721SignedTransaction(testnet, body), body.signatureId)
/**
* Send Tron mint multiple trc721 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronMintMultipleTrc721SignedTransaction = async (testnet: boolean, body: TronMintMultipleTrc721) =>
await tronBroadcast(await prepareTronMintMultipleTrc721SignedTransaction(testnet, body), body.signatureId)
/**
* Send Tron update cashback for author trc721 transaction to the blockchain. This method broadcasts signed transaction to the blockchain.
* This operation is irreversible.
* @param testnet
* @param body content of the transaction to broadcast
* @returns transaction id of the transaction in the blockchain
*/
export const sendTronUpdateCashbackForAuthorTrc721SignedTransaction = async (testnet: boolean, body: TronUpdateCashbackTrc721) =>
await tronBroadcast(await prepareTronUpdateCashbackForAuthorTrc721SignedTransaction(testnet, body), body.signatureId)
/**
* Sign Tron transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronSignedTransaction = async (testnet: boolean, body: TransferTron, provider?: string) => {
await validateBody(body, TransferTron)
const {
fromPrivateKey,
to,
amount,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.sendTrx(
to,
tronWeb.toSun(amount),
tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey)))
return JSON.stringify(await tronWeb.trx.sign(tx, fromPrivateKey))
}
/**
* Sign Tron Freeze balance transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider optional provider to enter. if not present, Tatum provider will be used.
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronFreezeTransaction = async (testnet: boolean, body: FreezeTron, provider?: string) => {
await validateBody(body, FreezeTron)
const {
fromPrivateKey,
receiver,
amount,
resource,
duration,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.freezeBalance(
tronWeb.toSun(parseFloat(amount)),
duration,
resource,
tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey)),
receiver,
)
return JSON.stringify(await tronWeb.trx.sign(tx, fromPrivateKey))
}
/**
* Sign Tron TRC10 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param precision
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronTrc10SignedTransaction = async (testnet: boolean, body: TransferTronTrc10, precision?: number, provider?: string) => {
await validateBody(body, TransferTronTrc10)
const {
fromPrivateKey,
to,
tokenId,
amount,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.sendToken(
to,
new BigNumber(amount).multipliedBy(new BigNumber(10).pow(precision || await getTrc10Precision(testnet, tokenId))),
tokenId,
tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey)))
return JSON.stringify(await tronWeb.trx.sign(tx, fromPrivateKey))
}
/**
* Get TRC20 balance for the given tron address.
* @param testnet mainnet or testnet version
* @param address the address whose balance is returned
* @param contractAddress the TRC20 contract address
* @param provider
*/
export const tronGetAccountTrc20Address = async (
testnet: boolean,
address: string,
contractAddress: string,
provider?: string,
) => {
if (!contractAddress) {
throw new Error('Contract address not set.');
}
const tronWeb = prepareTronWeb(testnet, provider);
tronWeb.setAddress(contractAddress);
const contractInstance = await tronWeb.contract().at(contractAddress);
return await contractInstance.balanceOf(address).call();
};
export const getTronTrc20ContractDecimals = async (testnet: boolean, contractAddress: string, provider?: string) => {
if (!contractAddress) {
throw new Error('Contract address not set.')
}
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(contractAddress)
const contractInstance = await tronWeb.contract().at(contractAddress)
return await contractInstance.decimals().call()
}
/**
* Sign Tron custodial transfer transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param feeLimit
* @param from
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronSmartContractInvocation = async (testnet: boolean, body: SmartContractMethodInvocation, feeLimit: number, from?: string, provider?: string) => {
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(body.contractAddress)
const sender = from || tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(body.fromPrivateKey))
const {transaction} = await tronWeb.transactionBuilder.triggerSmartContract(
tronWeb.address.toHex(body.contractAddress),
body.methodName,
{
feeLimit: tronWeb.toSun(feeLimit),
from: sender,
callValue: tronWeb.toSun(body.amount || 0),
},
body.params,
sender
)
if (body.signatureId) {
return JSON.stringify(transaction)
}
return JSON.stringify(await tronWeb.trx.sign(transaction, body.fromPrivateKey))
}
/**
* Sign Tron custodial transfer batch transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param feeLimit
* @param from
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronCustodialTransferBatch = async (testnet: boolean, body: SmartContractMethodInvocation, feeLimit: number, from?: string, provider?: string) => {
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(body.contractAddress)
const sender = from || tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(body.fromPrivateKey))
const {transaction} = await tronWeb.transactionBuilder.triggerSmartContract(
tronWeb.address.toHex(body.contractAddress),
'transferBatch(address[],uint256[],address[],uint256[],uint256[])',
{
feeLimit: tronWeb.toSun(feeLimit),
from: sender
},
[
{type: 'address[]', value: body.params[0].map(tronWeb.address.toHex)},
{type: 'uint256[]', value: body.params[1]},
{type: 'address[]', value: body.params[2].map(tronWeb.address.toHex)},
{type: 'uint256[]', value: body.params[3]},
{type: 'uint256[]', value: body.params[4]},
],
sender
)
if (body.signatureId) {
return JSON.stringify(transaction)
}
return JSON.stringify(await tronWeb.trx.sign(transaction, body.fromPrivateKey))
}
/**
* Sign Tron TRC20 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronTrc20SignedTransaction = async (testnet: boolean, body: TransferTronTrc20, provider?: string) => {
await validateBody(body, TransferTronTrc20)
const {
fromPrivateKey,
to,
tokenAddress,
amount,
feeLimit,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(tokenAddress)
const contractInstance = await tronWeb.contract().at(tokenAddress)
const decimals = await contractInstance.decimals().call()
const {transaction} = await tronWeb.transactionBuilder.triggerSmartContract(
tronWeb.address.toHex(tokenAddress),
'transfer(address,uint256)',
{
feeLimit: tronWeb.toSun(feeLimit),
from: tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey))
},
[{type: 'address', value: tronWeb.address.toHex(to)}, {
type: 'uint256',
value: `0x${new BigNumber(amount).multipliedBy(new BigNumber(10).pow(decimals)).toString(16)}`
}],
tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey))
)
return JSON.stringify(await tronWeb.trx.sign(transaction, fromPrivateKey))
}
/**
* Sign create Tron TRC10 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronCreateTrc10SignedTransaction = async (testnet: boolean, body: CreateTronTrc10, provider?: string) => {
await validateBody(body, CreateTronTrc10)
const {
fromPrivateKey,
name,
abbreviation,
description,
url,
totalSupply,
decimals,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.createToken({
name,
abbreviation,
description,
url,
totalSupply: new BigNumber(totalSupply).multipliedBy(new BigNumber(10).pow(decimals)),
trxRatio: 1,
tokenRatio: 1,
saleStart: Date.now() + 60000,
saleEnd: Date.now() + 100000,
freeBandwidth: 0,
freeBandwidthLimit: 0,
frozenAmount: 0,
frozenDuration: 0,
precision: decimals,
}, tronWeb.address.fromPrivateKey(fromPrivateKey))
return JSON.stringify(await tronWeb.trx.sign(tx, fromPrivateKey))
}
/**
* Sign create Tron TRC20 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronCreateTrc20SignedTransaction = async (testnet: boolean, body: CreateTronTrc20, provider?: string) => {
await validateBody(body, CreateTronTrc20)
const {
fromPrivateKey,
name,
decimals,
recipient,
symbol,
totalSupply,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.createSmartContract({
feeLimit: 1000000000,
callValue: 0,
userFeePercentage: 100,
originEnergyLimit: 1,
abi: JSON.stringify(abi),
bytecode,
parameters: [
name,
symbol,
decimals,
tronWeb.address.toHex(recipient),
totalSupply,
],
name,
}, tronWeb.address.fromPrivateKey(fromPrivateKey))
return JSON.stringify(await tronWeb.trx.sign(tx, fromPrivateKey))
}
/**
* Prepare Tron transaction for KMS. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronSignedKMSTransaction = async (testnet: boolean, body: TransferTron, provider?: string) => {
await validateBody(body, TransferTron)
const {
from,
to,
amount,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.sendTrx(
to,
tronWeb.toSun(amount),
from)
return JSON.stringify(tx)
}
/**
* Prepare Tron Freeze balance transaction for KMS. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronFreezeKMSTransaction = async (testnet: boolean, body: FreezeTron, provider?: string) => {
await validateBody(body, FreezeTron)
const {
from,
receiver,
amount,
resource,
duration,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.freezeBalance(
tronWeb.toSun(parseFloat(amount)),
duration,
resource,
from,
receiver,
)
return JSON.stringify(tx)
}
/**
* Prepare Tron TRC10 transaction for KMS. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param precision
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronTrc10SignedKMSTransaction = async (testnet: boolean, body: TransferTronTrc10, precision?: number, provider?: string) => {
await validateBody(body, TransferTronTrc10)
const {
from,
to,
tokenId,
amount,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.sendToken(
to,
new BigNumber(amount).multipliedBy(new BigNumber(10).pow(precision || await getTrc10Precision(testnet, tokenId))),
tokenId,
from)
return JSON.stringify(tx)
}
/**
* Prepare Tron TRC20 transaction for KMS. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronTrc20SignedKMSTransaction = async (testnet: boolean, body: TransferTronTrc20, provider?: string) => {
await validateBody(body, TransferTronTrc20)
const {
from,
to,
tokenAddress,
amount,
feeLimit,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(tokenAddress)
const contractInstance = await tronWeb.contract().at(tokenAddress)
const decimals = await contractInstance.decimals().call()
const {transaction} = await tronWeb.transactionBuilder.triggerSmartContract(
tronWeb.address.toHex(tokenAddress),
'transfer(address,uint256)',
{
feeLimit: tronWeb.toSun(feeLimit),
from
},
[{type: 'address', value: tronWeb.address.toHex(to)}, {
type: 'uint256',
value: `0x${new BigNumber(amount).multipliedBy(new BigNumber(10).pow(decimals)).toString(16)}`
}],
from
)
return JSON.stringify(transaction)
}
/**
* Prepare create Tron TRC10 transaction for KMS. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronCreateTrc10SignedKMSTransaction = async (testnet: boolean, body: CreateTronTrc10, provider?: string) => {
await validateBody(body, CreateTronTrc10)
const {
from,
name,
abbreviation,
description,
url,
totalSupply,
decimals,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.createToken({
name,
abbreviation,
description,
url,
totalSupply: new BigNumber(totalSupply).multipliedBy(new BigNumber(10).pow(decimals)),
trxRatio: 1,
tokenRatio: 1,
saleStart: Date.now() + 60000,
saleEnd: Date.now() + 100000,
freeBandwidth: 0,
freeBandwidthLimit: 0,
frozenAmount: 0,
frozenDuration: 0,
precision: decimals,
}, from)
return JSON.stringify(tx)
}
/**
* Prepare create Tron TRC20 transaction for KMS. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronCreateTrc20SignedKMSTransaction = async (testnet: boolean, body: CreateTronTrc20, provider?: string) => {
await validateBody(body, CreateTronTrc20)
const {
from,
name,
decimals,
recipient,
symbol,
totalSupply,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.createSmartContract({
feeLimit: 1000000000,
callValue: 0,
userFeePercentage: 100,
originEnergyLimit: 1,
abi: JSON.stringify(abi),
bytecode,
parameters: [
name,
symbol,
decimals,
tronWeb.address.toHex(recipient),
totalSupply,
],
name,
}, from)
return JSON.stringify(tx)
}
/**
* Sign Tron deploy trc721 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronDeployTrc721SignedTransaction = async (testnet: boolean, body: TronDeployTrc721, provider?: string) => {
await validateBody(body, TronDeployTrc721)
const {
fromPrivateKey,
name,
symbol,
feeLimit,
signatureId,
from,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.createSmartContract({
feeLimit: tronWeb.toSun(feeLimit),
callValue: 0,
userFeePercentage: 100,
originEnergyLimit: 1,
abi: JSON.stringify(trc721_abi),
bytecode: trc721_bytecode,
parameters: [
name,
symbol,
],
name,
}, from || tronWeb.address.fromPrivateKey(fromPrivateKey))
if (signatureId) {
return JSON.stringify(tx)
}
return JSON.stringify(await tronWeb.trx.sign(tx, fromPrivateKey))
}
/**
* Sign Tron generate custodial wallet transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronGenerateCustodialWalletSignedTransaction = async (testnet: boolean, body: GenerateTronCustodialAddress, provider?: string) => {
await validateBody(body, GenerateTronCustodialAddress)
const tronWeb = prepareTronWeb(testnet, provider)
const {abi, code} = obtainCustodialAddressType(body)
const tx = await tronWeb.transactionBuilder.createSmartContract({
feeLimit: tronWeb.toSun(body.feeLimit || 100),
callValue: 0,
userFeePercentage: 100,
originEnergyLimit: 1,
abi: JSON.stringify(abi),
bytecode: code,
parameters: [],
name: 'CustodialWallet',
}, body.from || tronWeb.address.fromPrivateKey(body.fromPrivateKey))
if (body.signatureId) {
return JSON.stringify(tx)
}
return JSON.stringify(await tronWeb.trx.sign(tx, body.fromPrivateKey))
}
/**
* Sign TRON deploy new smart contract for NFT marketplace transaction. Smart contract enables marketplace operator to create new listing for NFT (ERC-721/1155).
* @param testnet chain to work with
* @param body request data
* @param provider optional provider to enter. if not present, Tatum provider will be used.
* @returns {txId: string} Transaction ID of the operation, or signatureID in case of Tatum KMS
*/
export const prepareTronDeployMarketplaceListingSignedTransaction = async (testnet: boolean, body: DeployTronMarketplaceListing, provider?: string) => {
await validateBody(body, DeployTronMarketplaceListing)
const tronWeb = prepareTronWeb(testnet, provider)
const tx = await tronWeb.transactionBuilder.createSmartContract({
feeLimit: tronWeb.toSun(body.feeLimit || 300),
callValue: 0,
userFeePercentage: 100,
originEnergyLimit: 1,
abi: JSON.stringify(listing.abi),
bytecode: listing.data,
parameters: [
body.marketplaceFee,
body.feeRecipient,
],
name: 'CustodialWallet',
}, body.from || tronWeb.address.fromPrivateKey(body.fromPrivateKey))
if (body.signatureId) {
return JSON.stringify(tx)
}
return JSON.stringify(await tronWeb.trx.sign(tx, body.fromPrivateKey))
}
/**
* Sign Tron deploy trc721 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronMintCashbackTrc721SignedTransaction = async (testnet: boolean, body: TronMintTrc721, provider?: string) => {
await validateBody(body, TronMintTrc721)
const {
fromPrivateKey,
url,
to,
tokenId,
contractAddress,
feeLimit,
from,
signatureId,
authorAddresses,
cashbackValues
} = body
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(contractAddress)
const sender = from || tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey))
const cb: string[] = []
for (const c of cashbackValues!) {
cb.push(`0x${new BigNumber(c).multipliedBy(1e6).toString(16)}`)
}
const {transaction} = await tronWeb.transactionBuilder.triggerSmartContract(
tronWeb.address.toHex(contractAddress),
'mintWithCashback(address,uint256,string,address[],uint256[])',
{
feeLimit: tronWeb.toSun(feeLimit),
from: sender
},
[{type: 'address', value: tronWeb.address.toHex(to)},
{
type: 'uint256',
value: `0x${new BigNumber(tokenId).toString(16)}`
},
{
type: 'string',
value: url,
},
{
type: 'address[]',
value: authorAddresses?.map(a => tronWeb.address.toHex(a)),
},
{
type: 'uint256[]',
value: cb,
}],
sender,
)
return JSON.stringify(signatureId ? transaction : await tronWeb.trx.sign(transaction, fromPrivateKey))
}
/**
* Sign Tron mint trc721 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronMintTrc721SignedTransaction = async (testnet: boolean, body: TronMintTrc721, provider?: string) => {
await validateBody(body, TronMintTrc721)
const {
fromPrivateKey,
url,
to,
tokenId,
contractAddress,
from,
feeLimit,
signatureId,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(contractAddress)
const sender = from || tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey))
const {transaction} = await tronWeb.transactionBuilder.triggerSmartContract(
tronWeb.address.toHex(contractAddress),
'mintWithTokenURI(address,uint256,string)',
{
feeLimit: tronWeb.toSun(feeLimit),
from: sender
},
[{type: 'address', value: tronWeb.address.toHex(to)},
{
type: 'uint256',
value: `0x${new BigNumber(tokenId).toString(16)}`
},
{
type: 'string',
value: url,
}],
sender,
)
return JSON.stringify(signatureId ? transaction : await tronWeb.trx.sign(transaction, fromPrivateKey))
}
/**
* Sign Tron transfer trc721 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronTransferTrc721SignedTransaction = async (testnet: boolean, body: TronTransferTrc721, provider?: string) => {
await validateBody(body, TronTransferTrc721)
const {
fromPrivateKey,
to,
tokenId,
contractAddress,
feeLimit,
from,
signatureId,
value
} = body
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(contractAddress)
const sender = from || tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey))
const {transaction} = await tronWeb.transactionBuilder.triggerSmartContract(
tronWeb.address.toHex(contractAddress),
'safeTransfer(address,uint256)',
{
feeLimit: tronWeb.toSun(feeLimit),
from: sender,
callValue: value ? `0x${new BigNumber(value).multipliedBy(1e6).toString(16)}` : 0,
},
[{type: 'address', value: tronWeb.address.toHex(to)},
{
type: 'uint256',
value: `0x${new BigNumber(tokenId).toString(16)}`
}],
sender,
)
return JSON.stringify(signatureId ? transaction : await tronWeb.trx.sign(transaction, fromPrivateKey))
}
/**
* Sign Tron burn trc721 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronBurnTrc721SignedTransaction = async (testnet: boolean, body: TronBurnTrc721, provider?: string) => {
await validateBody(body, TronBurnTrc721)
const {
fromPrivateKey,
tokenId,
contractAddress,
feeLimit,
from,
signatureId,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(contractAddress)
const sender = from || tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey))
const {transaction} = await tronWeb.transactionBuilder.triggerSmartContract(
tronWeb.address.toHex(contractAddress),
'burn(uint256)',
{
feeLimit: tronWeb.toSun(feeLimit),
from: sender,
},
[{
type: 'uint256',
value: `0x${new BigNumber(tokenId).toString(16)}`
}],
sender,
)
return JSON.stringify(signatureId ? transaction : await tronWeb.trx.sign(transaction, fromPrivateKey))
}
/**
* Sign Tron mint multiple trc721 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronMintMultipleTrc721SignedTransaction = async (testnet: boolean, body: TronMintMultipleTrc721, provider?: string) => {
await validateBody(body, TronMintMultipleTrc721)
const {
fromPrivateKey,
to,
tokenId,
contractAddress,
url,
feeLimit,
from,
signatureId,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(contractAddress)
const sender = from || tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey))
const {transaction} = await tronWeb.transactionBuilder.triggerSmartContract(
tronWeb.address.toHex(contractAddress),
'mintMultiple(address[],uint256[],string[])',
{
feeLimit: tronWeb.toSun(feeLimit),
from: sender
},
[{
type: 'address[]',
value: to.map(a => tronWeb.address.toHex(a)),
},
{
type: 'uint256[]',
value: tokenId.map(t => `0x${new BigNumber(t).toString(16)}`)
},
{
type: 'string[]',
value: url,
}],
sender,
)
return JSON.stringify(signatureId ? transaction : await tronWeb.trx.sign(transaction, fromPrivateKey))
}
/**
* Sign Tron update cashback for author trc721 transaction with private keys locally. Nothing is broadcast to the blockchain.
* @param testnet mainnet or testnet version
* @param body content of the transaction to broadcast
* @param provider
* @returns transaction data to be broadcast to blockchain.
*/
export const prepareTronUpdateCashbackForAuthorTrc721SignedTransaction = async (testnet: boolean, body: TronUpdateCashbackTrc721, provider?: string) => {
await validateBody(body, TronUpdateCashbackTrc721)
const {
fromPrivateKey,
cashbackValue,
tokenId,
contractAddress,
feeLimit,
from,
signatureId,
} = body
const tronWeb = prepareTronWeb(testnet, provider)
tronWeb.setAddress(contractAddress)
const sender = from || tronWeb.address.fromHex(tronWeb.address.fromPrivateKey(fromPrivateKey))
const {transaction} = await tronWeb.transactionBuilder.triggerSmartContract(
tronWeb.address.toHex(contractAddress),
'updateCashbackForAuthor(uint256,uint256)',
{
feeLimit: tronWeb.toSun(feeLimit),
from: sender
},
[{
type: 'uint256',
value: `0x${new BigNumber(tokenId).toString(16)}`
},
{
type: 'uint256',
value: `0x${new BigNumber(cashbackValue).multipliedBy(1e6).toString(16)}`
}],
sender,
)
return JSON.stringify(signatureId ? transaction : await tronWeb.trx.sign(transaction, fromPrivateKey))
}
/**
* Sign Tron pending transaction from Tatum KMS
* @param tx pending transaction from KMS
* @param fromPrivateKey private key to sign transaction with.
* @param testnet mainnet or testnet version
* @returns transaction data to be broadcast to blockchain.
*/
export const signTrxKMSTransaction = async (tx: TransactionKMS, fromPrivateKey: string, testnet: boolean) => {
if (tx.chain !== Currency.TRON) {
throw Error('Unsupported chain.')
}
const transactionConfig = JSON.parse(tx.serializedTransaction)
const tronWeb = prepareTronWeb(testnet)
return JSON.stringify(await tronWeb.trx.sign(transactionConfig, fromPrivateKey))
}
export const transferHexToBase58Address = (address: string) => TronWeb.address.fromHex(address)
const getTrc10Precision = async (testnet: boolean, tokenId: string): Promise<number> => {
const config = {
method: 'GET',
url: `/v1/assets/${tokenId}`,
baseURL: `${testnet ? 'https://api.shasta.trongrid.io' : 'https://api.trongrid.io'}`,
headers: {
'content-type': 'application/json',
'TRON-PRO-API-KEY': process.env.TRON_PRO_API_KEY,
},
}
const { data } = (await axios.request(config as AxiosRequestConfig)).data
if (!data?.length) {
throw new Error('No such asset.')
}
return data[0].precision
throw new Error('Get TRC10 precision error.')
} | the_stack |
import RadioProvider from "../../../generated/joynr/vehicle/RadioProvider";
import RadioStation from "../../../generated/joynr/vehicle/radiotypes/RadioStation";
import Country from "../../../generated/joynr/datatypes/exampleTypes/Country";
import ProviderOperation from "../../../../main/js/joynr/provider/ProviderOperation";
import ProviderEvent from "../../../../main/js/joynr/provider/ProviderEvent";
import TestWithVersionProvider from "../../../generated/joynr/tests/TestWithVersionProvider";
import TestWithoutVersionProvider from "../../../generated/joynr/tests/TestWithoutVersionProvider";
describe("libjoynr-js.joynr.provider.Provider", () => {
let implementation: any = null;
beforeEach(() => {
implementation = {
isOn: {
value: false,
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
StartWithCapitalLetter: {
value: false,
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
numberOfStations: {
value: 0,
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
mixedSubscriptions: {
value: "testvalue",
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
enumAttribute: {
value: Country.GERMANY,
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
enumArrayAttribute: {
value: [Country.GERMANY],
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
byteBufferAttribute: {
value: [],
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
stringMapAttribute: {
value: {},
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
complexStructMapAttribute: {
value: {},
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
failingSyncAttribute: {
value: 0,
get() {
return this.value;
}
},
failingAsyncAttribute: {
value: 0,
get() {
return this.value;
}
},
attrProvidedImpl: {
value: "testValue2",
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
attributeTestingProviderInterface: {
get() {
return undefined;
}
},
typeDefForStruct: {
value: new RadioStation({
name: "radioStation",
byteBuffer: []
}),
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
typeDefForPrimitive: {
value: 0,
get() {
return this.value;
},
set(newValue: any) {
this.value = newValue;
}
},
addFavoriteStation: jest.fn(),
methodFireAndForgetWithoutParams: jest.fn(),
methodFireAndForget: jest.fn(),
weakSignal: jest.fn(),
triggerBroadcasts: jest.fn(),
triggerBroadcastsWithPartitions: jest.fn(),
methodProvidedImpl: jest.fn(),
methodWithByteBuffer: jest.fn(),
methodWithTypeDef: jest.fn(),
methodWithComplexMap: jest.fn(),
operationWithEnumsAsInputAndOutput: jest.fn(),
operationWithMultipleOutputParameters: jest.fn(),
operationWithEnumsAsInputAndEnumArrayAsOutput: jest.fn(),
methodWithSingleArrayParameters: jest.fn(),
broadcastWithEnum: jest.fn()
};
});
it("version is set correctly", () => {
expect(TestWithVersionProvider.MAJOR_VERSION).toBeDefined();
expect(TestWithVersionProvider.MAJOR_VERSION).toEqual(47);
expect(TestWithVersionProvider.MINOR_VERSION).toBeDefined();
expect(TestWithVersionProvider.MINOR_VERSION).toEqual(11);
});
it("default version is set correctly", () => {
expect(TestWithoutVersionProvider.MAJOR_VERSION).toBeDefined();
expect(TestWithoutVersionProvider.MAJOR_VERSION).toEqual(0);
expect(TestWithoutVersionProvider.MINOR_VERSION).toBeDefined();
expect(TestWithoutVersionProvider.MINOR_VERSION).toEqual(0);
});
it("RadioProvider does not throw when instantiated with different implementations", () => {
expect(() => new RadioProvider({} as any)).not.toThrow();
expect(() => new RadioProvider({ isOn: {} } as any)).not.toThrow();
expect(() => new RadioProvider({ isOn: { get: () => false } } as any)).not.toThrow();
expect(() => new RadioProvider({ isOn: { set: () => {} } } as any)).not.toThrow();
expect(() => new RadioProvider({ isOn: { get: () => false, set: () => {} } } as any)).not.toThrow();
expect(() => new RadioProvider({ addFavoriteStation: () => true } as any)).not.toThrow();
});
it("RadioProvider is instantiable", () => {
const radioProvider = new RadioProvider({} as any);
expect(radioProvider).toBeDefined();
expect(radioProvider).not.toBeNull();
expect(typeof radioProvider === "object").toBeTruthy();
expect(radioProvider instanceof RadioProvider).toBeTruthy();
});
it("RadioProvider has all members", () => {
const radioProvider = new RadioProvider({} as any);
expect(radioProvider.isOn).toBeDefined();
expect(radioProvider.enumAttribute).toBeDefined();
expect(radioProvider.enumArrayAttribute).toBeDefined();
expect(radioProvider.addFavoriteStation).toBeDefined();
expect(radioProvider.addFavoriteStation instanceof ProviderOperation).toBeTruthy();
expect(radioProvider.operationWithEnumsAsInputAndOutput).toBeDefined();
expect(radioProvider.operationWithEnumsAsInputAndOutput instanceof ProviderOperation).toBeTruthy();
expect(radioProvider.operationWithEnumsAsInputAndEnumArrayAsOutput).toBeDefined();
expect(radioProvider.operationWithEnumsAsInputAndEnumArrayAsOutput instanceof ProviderOperation).toBeTruthy();
expect(radioProvider.weakSignal).toBeDefined();
expect(radioProvider.weakSignal instanceof ProviderEvent).toBeTruthy();
expect(radioProvider.broadcastWithEnum).toBeDefined();
expect(radioProvider.broadcastWithEnum instanceof ProviderEvent).toBeTruthy();
expect(radioProvider.interfaceName).toBeDefined();
expect(typeof radioProvider.interfaceName).toEqual("string");
});
it("RadioProvider recognizes a correct implementation", () => {
const radioProvider = new RadioProvider(implementation);
expect(radioProvider.checkImplementation).toBeDefined();
expect(radioProvider.checkImplementation()).toBeTruthy();
expect(radioProvider.checkImplementation().length).toEqual(0);
});
it("RadioProvider recognizes an incorrect implementation", () => {
delete implementation.addFavoriteStation;
const radioProvider = new RadioProvider(implementation);
expect(radioProvider.checkImplementation).toBeDefined();
expect(radioProvider.checkImplementation()).toBeTruthy();
expect(radioProvider.checkImplementation().length).toEqual(1);
});
it("RadioProvider recognizes a missing getter", () => {
delete implementation.isOn.get;
const radioProvider = new RadioProvider(implementation);
expect(radioProvider.checkImplementation).toBeDefined();
expect(radioProvider.checkImplementation()).toBeTruthy();
expect(radioProvider.checkImplementation().length).toEqual(1);
});
it("RadioProvider recognizes a missing setter", () => {
delete implementation.isOn.set;
const radioProvider = new RadioProvider(implementation);
expect(radioProvider.checkImplementation).toBeDefined();
expect(radioProvider.checkImplementation()).toBeTruthy();
expect(radioProvider.checkImplementation().length).toEqual(1);
});
it("RadioProvider recognizes multiple missing implementation functions", () => {
delete implementation.isOn.get;
delete implementation.addFavoriteStation;
const radioProvider = new RadioProvider(implementation);
expect(radioProvider.checkImplementation).toBeDefined();
expect(radioProvider.checkImplementation()).toBeTruthy();
expect(radioProvider.checkImplementation().length).toEqual(2);
});
}); | the_stack |
'use strict';
import * as assert from 'assert';
import {BinaryKeybindings, KeyCode, KeyMod} from 'vs/base/common/keyCodes';
import {IOSupport, KeybindingResolver, NormalizedKeybindingItem} from 'vs/platform/keybinding/common/keybindingResolver';
import {IKeybindingItem} from 'vs/platform/keybinding/common/keybinding';
import {ContextKeyAndExpr, ContextKeyExpr} from 'vs/platform/contextkey/common/contextkey';
suite('Keybinding Service', () => {
test('resolve key', function() {
let keybinding = KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_Z;
let contextRules = ContextKeyExpr.equals('bar', 'baz');
let keybindingItem: IKeybindingItem = {
command: 'yes',
when: contextRules,
keybinding: keybinding,
weight1: 0,
weight2: 0
};
assert.equal(KeybindingResolver.contextMatchesRules({ bar: 'baz' }, contextRules), true);
assert.equal(KeybindingResolver.contextMatchesRules({ bar: 'bz' }, contextRules), false);
let resolver = new KeybindingResolver([keybindingItem], []);
assert.equal(resolver.resolve({ bar: 'baz' }, 0, keybinding).commandId, 'yes');
assert.equal(resolver.resolve({ bar: 'bz' }, 0, keybinding), null);
});
test('KbAndExpression.equals', function() {
let a = ContextKeyExpr.and(
ContextKeyExpr.has('a1'),
ContextKeyExpr.and(ContextKeyExpr.has('and.a')),
ContextKeyExpr.has('a2'),
ContextKeyExpr.equals('b1', 'bb1'),
ContextKeyExpr.equals('b2', 'bb2'),
ContextKeyExpr.notEquals('c1', 'cc1'),
ContextKeyExpr.notEquals('c2', 'cc2'),
ContextKeyExpr.not('d1'),
ContextKeyExpr.not('d2')
);
let b = ContextKeyExpr.and(
ContextKeyExpr.equals('b2', 'bb2'),
ContextKeyExpr.notEquals('c1', 'cc1'),
ContextKeyExpr.not('d1'),
ContextKeyExpr.notEquals('c2', 'cc2'),
ContextKeyExpr.has('a2'),
ContextKeyExpr.equals('b1', 'bb1'),
ContextKeyExpr.has('a1'),
ContextKeyExpr.and(ContextKeyExpr.equals('and.a', true)),
ContextKeyExpr.not('d2')
);
assert(a.equals(b), 'expressions should be equal');
});
test('KeybindingResolver.combine simple 1', function() {
let defaults:IKeybindingItem[] = [{
command: 'yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}];
let overrides:IKeybindingItem[] = [{
command: 'yes2',
when: ContextKeyExpr.equals('2', 'b'),
keybinding: KeyCode.KEY_B,
weight1: 0,
weight2: 0
}];
let actual = KeybindingResolver.combine(defaults, overrides);
assert.deepEqual(actual, [
new NormalizedKeybindingItem(KeyCode.KEY_A, 'yes1', ContextKeyExpr.equals('1', 'a'), true),
new NormalizedKeybindingItem(KeyCode.KEY_B, 'yes2', ContextKeyExpr.equals('2', 'b'), false),
]);
});
test('KeybindingResolver.combine simple 2', function() {
let defaults:IKeybindingItem[] = [{
command: 'yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}, {
command: 'yes2',
when: ContextKeyExpr.equals('2', 'b'),
keybinding: KeyCode.KEY_B,
weight1: 0,
weight2: 0
}];
let overrides:IKeybindingItem[] = [{
command: 'yes3',
when: ContextKeyExpr.equals('3', 'c'),
keybinding: KeyCode.KEY_C,
weight1: 0,
weight2: 0
}];
let actual = KeybindingResolver.combine(defaults, overrides);
assert.deepEqual(actual, [
new NormalizedKeybindingItem(KeyCode.KEY_A, 'yes1', ContextKeyExpr.equals('1', 'a'), true),
new NormalizedKeybindingItem(KeyCode.KEY_B, 'yes2', ContextKeyExpr.equals('2', 'b'), true),
new NormalizedKeybindingItem(KeyCode.KEY_C, 'yes3', ContextKeyExpr.equals('3', 'c'), false),
]);
});
test('KeybindingResolver.combine removal with not matching when', function() {
let defaults:IKeybindingItem[] = [{
command: 'yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}, {
command: 'yes2',
when: ContextKeyExpr.equals('2', 'b'),
keybinding: KeyCode.KEY_B,
weight1: 0,
weight2: 0
}];
let overrides:IKeybindingItem[] = [{
command: '-yes1',
when: ContextKeyExpr.equals('1', 'b'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}];
let actual = KeybindingResolver.combine(defaults, overrides);
assert.deepEqual(actual, [
new NormalizedKeybindingItem(KeyCode.KEY_A, 'yes1', ContextKeyExpr.equals('1', 'a'), true),
new NormalizedKeybindingItem(KeyCode.KEY_B, 'yes2', ContextKeyExpr.equals('2', 'b'), true)
]);
});
test('KeybindingResolver.combine removal with not matching keybinding', function() {
let defaults:IKeybindingItem[] = [{
command: 'yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}, {
command: 'yes2',
when: ContextKeyExpr.equals('2', 'b'),
keybinding: KeyCode.KEY_B,
weight1: 0,
weight2: 0
}];
let overrides:IKeybindingItem[] = [{
command: '-yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_B,
weight1: 0,
weight2: 0
}];
let actual = KeybindingResolver.combine(defaults, overrides);
assert.deepEqual(actual, [
new NormalizedKeybindingItem(KeyCode.KEY_A, 'yes1', ContextKeyExpr.equals('1', 'a'), true),
new NormalizedKeybindingItem(KeyCode.KEY_B, 'yes2', ContextKeyExpr.equals('2', 'b'), true)
]);
});
test('KeybindingResolver.combine removal with matching keybinding and when', function() {
let defaults:IKeybindingItem[] = [{
command: 'yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}, {
command: 'yes2',
when: ContextKeyExpr.equals('2', 'b'),
keybinding: KeyCode.KEY_B,
weight1: 0,
weight2: 0
}];
let overrides:IKeybindingItem[] = [{
command: '-yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}];
let actual = KeybindingResolver.combine(defaults, overrides);
assert.deepEqual(actual, [
new NormalizedKeybindingItem(KeyCode.KEY_B, 'yes2', ContextKeyExpr.equals('2', 'b'), true)
]);
});
test('KeybindingResolver.combine removal with unspecified keybinding', function() {
let defaults:IKeybindingItem[] = [{
command: 'yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}, {
command: 'yes2',
when: ContextKeyExpr.equals('2', 'b'),
keybinding: KeyCode.KEY_B,
weight1: 0,
weight2: 0
}];
let overrides:IKeybindingItem[] = [{
command: '-yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: 0,
weight1: 0,
weight2: 0
}];
let actual = KeybindingResolver.combine(defaults, overrides);
assert.deepEqual(actual, [
new NormalizedKeybindingItem(KeyCode.KEY_B, 'yes2', ContextKeyExpr.equals('2', 'b'), true)
]);
});
test('KeybindingResolver.combine removal with unspecified when', function() {
let defaults:IKeybindingItem[] = [{
command: 'yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}, {
command: 'yes2',
when: ContextKeyExpr.equals('2', 'b'),
keybinding: KeyCode.KEY_B,
weight1: 0,
weight2: 0
}];
let overrides:IKeybindingItem[] = [{
command: '-yes1',
when: null,
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}];
let actual = KeybindingResolver.combine(defaults, overrides);
assert.deepEqual(actual, [
new NormalizedKeybindingItem(KeyCode.KEY_B, 'yes2', ContextKeyExpr.equals('2', 'b'), true)
]);
});
test('KeybindingResolver.combine removal with unspecified when and unspecified keybinding', function() {
let defaults:IKeybindingItem[] = [{
command: 'yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}, {
command: 'yes2',
when: ContextKeyExpr.equals('2', 'b'),
keybinding: KeyCode.KEY_B,
weight1: 0,
weight2: 0
}];
let overrides:IKeybindingItem[] = [{
command: '-yes1',
when: null,
keybinding: 0,
weight1: 0,
weight2: 0
}];
let actual = KeybindingResolver.combine(defaults, overrides);
assert.deepEqual(actual, [
new NormalizedKeybindingItem(KeyCode.KEY_B, 'yes2', ContextKeyExpr.equals('2', 'b'), true)
]);
});
test('issue #612#issuecomment-222109084 cannot remove keybindings for commands with ^', function() {
let defaults:IKeybindingItem[] = [{
command: '^yes1',
when: ContextKeyExpr.equals('1', 'a'),
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}, {
command: 'yes2',
when: ContextKeyExpr.equals('2', 'b'),
keybinding: KeyCode.KEY_B,
weight1: 0,
weight2: 0
}];
let overrides:IKeybindingItem[] = [{
command: '-yes1',
when: null,
keybinding: KeyCode.KEY_A,
weight1: 0,
weight2: 0
}];
let actual = KeybindingResolver.combine(defaults, overrides);
assert.deepEqual(actual, [
new NormalizedKeybindingItem(KeyCode.KEY_B, 'yes2', ContextKeyExpr.equals('2', 'b'), true)
]);
});
test('normalizeRule', function() {
let key1IsTrue = ContextKeyExpr.equals('key1', true);
let key1IsNotFalse = ContextKeyExpr.notEquals('key1', false);
let key1IsFalse = ContextKeyExpr.equals('key1', false);
let key1IsNotTrue = ContextKeyExpr.notEquals('key1', true);
assert.ok(key1IsTrue.normalize().equals(ContextKeyExpr.has('key1')));
assert.ok(key1IsNotFalse.normalize().equals(ContextKeyExpr.has('key1')));
assert.ok(key1IsFalse.normalize().equals(ContextKeyExpr.not('key1')));
assert.ok(key1IsNotTrue.normalize().equals(ContextKeyExpr.not('key1')));
});
test('contextIsEntirelyIncluded', function() {
let assertIsIncluded = (a: ContextKeyExpr[], b: ContextKeyExpr[]) => {
assert.equal(KeybindingResolver.whenIsEntirelyIncluded(false, new ContextKeyAndExpr(a), new ContextKeyAndExpr(b)), true);
};
let assertIsNotIncluded = (a: ContextKeyExpr[], b: ContextKeyExpr[]) => {
assert.equal(KeybindingResolver.whenIsEntirelyIncluded(false, new ContextKeyAndExpr(a), new ContextKeyAndExpr(b)), false);
};
let key1IsTrue = ContextKeyExpr.equals('key1', true);
let key1IsNotFalse = ContextKeyExpr.notEquals('key1', false);
let key1IsFalse = ContextKeyExpr.equals('key1', false);
let key1IsNotTrue = ContextKeyExpr.notEquals('key1', true);
let key2IsTrue = ContextKeyExpr.equals('key2', true);
let key2IsNotFalse = ContextKeyExpr.notEquals('key2', false);
let key3IsTrue = ContextKeyExpr.equals('key3', true);
let key4IsTrue = ContextKeyExpr.equals('key4', true);
assertIsIncluded([key1IsTrue], null);
assertIsIncluded([key1IsTrue], []);
assertIsIncluded([key1IsTrue], [key1IsTrue]);
assertIsIncluded([key1IsTrue], [key1IsNotFalse]);
assertIsIncluded([key1IsFalse], []);
assertIsIncluded([key1IsFalse], [key1IsFalse]);
assertIsIncluded([key1IsFalse], [key1IsNotTrue]);
assertIsIncluded([key2IsNotFalse], []);
assertIsIncluded([key2IsNotFalse], [key2IsNotFalse]);
assertIsIncluded([key2IsNotFalse], [key2IsTrue]);
assertIsIncluded([key1IsTrue, key2IsNotFalse], [key2IsTrue]);
assertIsIncluded([key1IsTrue, key2IsNotFalse], [key2IsNotFalse]);
assertIsIncluded([key1IsTrue, key2IsNotFalse], [key1IsTrue]);
assertIsIncluded([key1IsTrue, key2IsNotFalse], [key1IsNotFalse]);
assertIsIncluded([key1IsTrue, key2IsNotFalse], []);
assertIsNotIncluded([key1IsTrue], [key1IsFalse]);
assertIsNotIncluded([key1IsTrue], [key1IsNotTrue]);
assertIsNotIncluded([key1IsNotFalse], [key1IsFalse]);
assertIsNotIncluded([key1IsNotFalse], [key1IsNotTrue]);
assertIsNotIncluded([key1IsFalse], [key1IsTrue]);
assertIsNotIncluded([key1IsFalse], [key1IsNotFalse]);
assertIsNotIncluded([key1IsNotTrue], [key1IsTrue]);
assertIsNotIncluded([key1IsNotTrue], [key1IsNotFalse]);
assertIsNotIncluded([key1IsTrue, key2IsNotFalse], [key3IsTrue]);
assertIsNotIncluded([key1IsTrue, key2IsNotFalse], [key4IsTrue]);
assertIsNotIncluded([key1IsTrue], [key2IsTrue]);
assertIsNotIncluded([], [key2IsTrue]);
assertIsNotIncluded(null, [key2IsTrue]);
});
test('resolve command', function() {
let items: IKeybindingItem[] = [
// This one will never match because its "when" is always overwritten by another one
{
keybinding: KeyCode.KEY_X,
when: ContextKeyExpr.and(
ContextKeyExpr.equals('key1', true),
ContextKeyExpr.notEquals('key2', false)
),
command: 'first',
weight1: 1,
weight2: 0
},
// This one always overwrites first
{
keybinding: KeyCode.KEY_X,
when: ContextKeyExpr.equals('key2', true),
command: 'second',
weight1: 2,
weight2: 0
},
// This one is a secondary mapping for `second`
{
keybinding: KeyCode.KEY_Z,
when: null,
command: 'second',
weight1: 2.5,
weight2: 0
},
// This one sometimes overwrites first
{
keybinding: KeyCode.KEY_X,
when: ContextKeyExpr.equals('key3', true),
command: 'third',
weight1: 3,
weight2: 0
},
// This one is always overwritten by another one
{
keybinding: KeyMod.CtrlCmd | KeyCode.KEY_Y,
when: ContextKeyExpr.equals('key4', true),
command: 'fourth',
weight1: 4,
weight2: 0
},
// This one overwrites with a chord the previous one
{
keybinding: KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_Y, KeyCode.KEY_Z),
when: null,
command: 'fifth',
weight1: 5,
weight2: 0
},
// This one has no keybinding
{
keybinding: 0,
when: null,
command: 'sixth',
weight1: 6,
weight2: 0
},
{
keybinding: KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_U),
when: null,
command: 'seventh',
weight1: 6.5,
weight2: 0
},
{
keybinding: KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_K),
when: null,
command: 'seventh',
weight1: 6.5,
weight2: 0
},
{
keybinding: KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_U),
when: null,
command: 'uncomment lines',
weight1: 7,
weight2: 0
},
{
keybinding: KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_C),
when: null,
command: 'comment lines',
weight1: 8,
weight2: 0
},
{
keybinding: KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_G, KeyMod.CtrlCmd | KeyCode.KEY_C),
when: null,
command: 'unreachablechord',
weight1: 10,
weight2: 0
},
{
keybinding: KeyMod.CtrlCmd | KeyCode.KEY_G,
when: null,
command: 'eleven',
weight1: 11,
weight2: 0
}
];
let resolver = new KeybindingResolver(items, [], false);
let testKey = (commandId: string, expectedKeys: number[]) => {
// Test lookup
let lookupResult = resolver.lookupKeybinding(commandId);
assert.equal(lookupResult.length, expectedKeys.length, 'Length mismatch @ commandId ' + commandId + '; GOT: ' + JSON.stringify(lookupResult, null, '\t'));
for (let i = 0, len = lookupResult.length; i < len; i++) {
assert.equal(lookupResult[i].value, expectedKeys[i]);
}
};
let testResolve = (ctx: any, expectedKey: number, commandId: string) => {
if (BinaryKeybindings.hasChord(expectedKey)) {
let firstPart = BinaryKeybindings.extractFirstPart(expectedKey);
let chordPart = BinaryKeybindings.extractChordPart(expectedKey);
let result = resolver.resolve(ctx, 0, firstPart);
assert.ok(result !== null, 'Enters chord for ' + commandId);
assert.equal(result.commandId, null, 'Enters chord for ' + commandId);
assert.equal(result.enterChord, firstPart, 'Enters chord for ' + commandId);
result = resolver.resolve(ctx, firstPart, chordPart);
assert.ok(result !== null, 'Enters chord for ' + commandId);
assert.equal(result.commandId, commandId, 'Finds chorded command ' + commandId);
assert.equal(result.enterChord, 0, 'Finds chorded command ' + commandId);
} else {
let result = resolver.resolve(ctx, 0, expectedKey);
assert.ok(result !== null, 'Finds command ' + commandId);
assert.equal(result.commandId, commandId, 'Finds command ' + commandId);
assert.equal(result.enterChord, 0, 'Finds command ' + commandId);
}
};
testKey('first', []);
testKey('second', [KeyCode.KEY_Z, KeyCode.KEY_X]);
testResolve({ key2: true }, KeyCode.KEY_X, 'second');
testResolve({}, KeyCode.KEY_Z, 'second');
testKey('third', [KeyCode.KEY_X]);
testResolve({ key3: true }, KeyCode.KEY_X, 'third');
testKey('fourth', []);
testKey('fifth', [KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_Y, KeyCode.KEY_Z)]);
testResolve({}, KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_Y, KeyCode.KEY_Z), 'fifth');
testKey('seventh', [KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_K)]);
testResolve({}, KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_K), 'seventh');
testKey('uncomment lines', [KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_U)]);
testResolve({}, KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_U), 'uncomment lines');
testKey('comment lines', [KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_C)]);
testResolve({}, KeyMod.chord(KeyMod.CtrlCmd | KeyCode.KEY_K, KeyMod.CtrlCmd | KeyCode.KEY_C), 'comment lines');
testKey('unreachablechord', []);
testKey('eleven', [KeyMod.CtrlCmd | KeyCode.KEY_G]);
testResolve({}, KeyMod.CtrlCmd | KeyCode.KEY_G, 'eleven');
testKey('sixth', []);
});
test('contextMatchesRules', function() {
/* tslint:disable:triple-equals */
let context = {
'a': true,
'b': false,
'c': '5'
};
function testExpression(expr: string, expected: boolean): void {
let rules = IOSupport.readKeybindingWhen(expr);
assert.equal(KeybindingResolver.contextMatchesRules(context, rules), expected, expr);
}
function testBatch(expr: string, value: any): void {
testExpression(expr, !!value);
testExpression(expr + ' == true', !!value);
testExpression(expr + ' != true', !value);
testExpression(expr + ' == false', !value);
testExpression(expr + ' != false', !!value);
testExpression(expr + ' == 5', value == <any>'5');
testExpression(expr + ' != 5', value != <any>'5');
testExpression('!' + expr, !value);
}
testExpression('', true);
testBatch('a', true);
testBatch('b', false);
testBatch('c', '5');
testBatch('z', undefined);
testExpression('a && !b', true && !false);
testExpression('a && b', true && false);
testExpression('a && !b && c == 5', true && !false && '5' == '5');
/* tslint:enable:triple-equals */
});
}); | the_stack |
import type {
SortComparator,
QueryMatcher
} from 'event-reduce-js';
import type {
BulkWriteLocalRow,
BulkWriteRow,
ChangeStreamEvent,
ChangeStreamOnceOptions,
PreparedQuery,
RxDocumentData,
RxLocalDocumentData,
RxLocalStorageBulkWriteResponse,
RxStorageBulkWriteResponse,
RxStorageChangeEvent,
RxStorageInstanceCreationParams,
RxStorageQueryResult
} from './rx-storage';
import type {
BlobBuffer,
MangoQuery,
RxJsonSchema
} from './';
import type {
Observable
} from 'rxjs';
/**
* TODO WORK IN PROGRESS! Might change without breaking change.
* This is an interface that abstracts the storage engine.
* At the moment we only have PouchDB as storage but
* in the future we want to create many more of them.
*
* Also see
* @link https://github.com/pubkey/rxdb/issues/1636
*
*
*/
/**
* A RxStorage is a module that acts
* as a factory that can create multiple RxStorageInstance
* objects.
*/
export interface RxStorage<Internals, InstanceCreationOptions> {
/**
* name of the storage engine
* used to detect if plugins do not work so we can throw propper errors.
*/
readonly name: string;
/**
* Returns a hash of the given value.
* Used to check equalness of attachments data and other stuff.
* Pouchdb uses md5 but we can use whatever we want as long as each
* storage class returns the same hash each time.
*/
hash(data: Buffer | Blob | string): Promise<string>;
/**
* creates a storage instance
* that can contain the internal database
* For example the PouchDB instance
*/
createStorageInstance<DocumentData>(
params: RxStorageInstanceCreationParams<DocumentData, InstanceCreationOptions>
): Promise<RxStorageInstance<DocumentData, Internals, InstanceCreationOptions>>;
/**
* Creates the internal storage instance
* that is only cappable of saving schemaless key-object relations.
*/
createKeyObjectStorageInstance(
databaseName: string,
collectionName: string,
options: InstanceCreationOptions
): Promise<RxStorageKeyObjectInstance<Internals, InstanceCreationOptions>>;
}
export interface RxStorageInstanceBase<Internals, InstanceCreationOptions> {
readonly databaseName: string;
/**
* Returns the internal data that is used by the storage engine.
* For example the pouchdb instance.
*/
readonly internals: Readonly<Internals>;
readonly options: Readonly<InstanceCreationOptions>;
/**
* Closes the storage instance so it cannot be used
* anymore and should clear all memory.
* The returned promise must resolve when everything is cleaned up.
*/
close(): Promise<void>;
/**
* Remove the database and
* deletes all of its data.
*/
remove(): Promise<void>;
}
/**
* A StorateInstance that is only capable of saving key-object relations,
* cannot be queried and has no schema.
* In the past we saved normal and local documents into the same instance of pouchdb.
* This was bad because it means that on migration or deletion, we always
* will remove the local documents. Now this is splitted into
* as separate RxStorageKeyObjectInstance that only stores the local documents
* aka key->object sets.
*/
export interface RxStorageKeyObjectInstance<Internals, InstanceCreationOptions>
extends RxStorageInstanceBase<Internals, InstanceCreationOptions> {
/**
* Writes multiple local documents to the storage instance.
* The write for each single document is atomic, there
* is not transaction arround all documents.
* It must be possible that some document writes succeed
* and others error.
* We need this to have a similar behavior as most NoSQL databases.
* Local documents always have _id as primary and cannot have attachments.
* They can only be queried directly by their primary _id.
*/
bulkWrite<D = any>(
documentWrites: BulkWriteLocalRow<D>[]
): Promise<
/**
* returns the response, splitted into success and error lists.
*/
RxLocalStorageBulkWriteResponse<D>
>;
/**
* Get Multiple local documents by their primary value.
*/
findLocalDocumentsById<D = any>(
/**
* List of primary values
* of the documents to find.
*/
ids: string[]
): Promise<Map<string, RxLocalDocumentData<D>>>;
/**
* Emits all changes to the local documents.
*/
changeStream(): Observable<RxStorageChangeEvent<RxLocalDocumentData>>;
}
export interface RxStorageInstance<
/**
* The type of the documents that can be stored in this instance.
* All documents in an instance must comply to the same schema.
*/
DocumentData,
Internals,
InstanceCreationOptions
>
extends RxStorageInstanceBase<Internals, InstanceCreationOptions> {
readonly schema: Readonly<RxJsonSchema<DocumentData>>;
readonly collectionName: string;
/**
* pouchdb and others have some bugs
* and behaviors that must be worked arround
* before querying the db.
* For performance reason this preparation
* runs in a single step so it can be cached
* when the query is used multiple times.
*
* If your custom storage engine is capable of running
* all valid mango queries properly, just return the
* mutateableQuery here.
*
*
* @returns a format of the query than can be used with the storage
*/
prepareQuery(
/**
* a query that can be mutated by the function without side effects.
*/
mutateableQuery: MangoQuery<DocumentData>
): PreparedQuery<DocumentData>;
/**
* Returns the sort-comparator,
* which is able to sort documents in the same way
* a query over the db would do.
*/
getSortComparator(
query: MangoQuery<DocumentData>
): SortComparator<DocumentData>;
/**
* Returns a function
* that can be used to check if a document
* matches the query.
*
*/
getQueryMatcher(
query: MangoQuery<DocumentData>
): QueryMatcher<DocumentData>;
/**
* Writes multiple non-local documents to the storage instance.
* The write for each single document is atomic, there
* is no transaction arround all documents.
* The written documents must be the newest revision of that documents data.
* If the previous document is not the current newest revision, a conflict error
* must be returned.
* It must be possible that some document writes succeed
* and others error. We need this to have a similar behavior as most NoSQL databases.
*/
bulkWrite(
documentWrites: BulkWriteRow<DocumentData>[]
): Promise<
/**
* returns the response, splitted into success and error lists.
*/
RxStorageBulkWriteResponse<DocumentData>
>;
/**
* Adds revisions of documents to the storage instance.
* The revisions do not have to be the newest ones but can also be past
* states of the documents.
* Adding revisions can never cause conflicts.
*
* Notice: When a revisions of a document is added and the storage instance
* decides that this is now the newest revision, the changeStream() must emit an event
* based on what the previous newest revision of the document was.
*/
bulkAddRevisions(
documents: RxDocumentData<DocumentData>[]
): Promise<void>;
/**
* Get Multiple documents by their primary value.
* This must also return deleted documents.
*/
findDocumentsById(
/**
* List of primary values
* of the documents to find.
*/
ids: string[],
/**
* If set to true, deleted documents will also be returned.
*/
deleted: boolean
): Promise<Map<string, RxDocumentData<DocumentData>>>;
/**
* Runs a NoSQL 'mango' query over the storage
* and returns the found documents data.
* Having all storage instances behave similar
* is likely the most difficult thing when creating a new
* rx-storage implementation. Atm we use the pouchdb-find plugin
* as reference to how NoSQL-queries must work.
* But the past has shown that pouchdb find can behave wrong,
* which must be fixed or at least documented.
*
* TODO should we have a way for streamed results
* or a way to cancel a running query?
*/
query(
/**
* Here we get the result of this.prepareQuery()
* instead of the plain mango query.
* This makes it easier to have good performance
* when transformations of the query must be done.
*/
preparedQuery: PreparedQuery<DocumentData>
): Promise<RxStorageQueryResult<DocumentData>>;
/**
* Returns the plain data of a single attachment.
*/
getAttachmentData(
documentId: string,
attachmentId: string
): Promise<BlobBuffer>;
/**
* Returns the ids of all documents that have been
* changed since the given startSequence.
*/
getChangedDocuments(
options: ChangeStreamOnceOptions
): Promise<{
changedDocuments: {
id: string;
sequence: number;
}[],
/**
* The last sequence number is returned in a separate field
* because the storage instance might have left out some events
* that it does not want to send out to the user.
* But still we need to know that they are there for a gapless pagination.
*/
lastSequence: number;
}>;
/**
* Returns an ongoing stream
* of all changes that happen to the
* storage instance.
* Do not forget to unsubscribe.
*/
changeStream(): Observable<RxStorageChangeEvent<RxDocumentData<DocumentData>>>;
} | the_stack |
export const enum FieldFlags {
// bottom 2 bits encode field type
Type = 3,
Property = 0,
Attribute = 1,
Ignore = 2,
Assign = 3
}
export type FieldData = [ string, string | null, FieldFlags ];
const
// pre-seed the caches with a few special cases, so we don't need to check for them in the common cases
htmlFieldCache = {
// special props
style : [ 'style' , null, FieldFlags.Assign ],
ref : [ 'ref' , null, FieldFlags.Ignore ],
fn : [ 'fn' , null, FieldFlags.Ignore ],
// attr compat
class : [ 'className' , null, FieldFlags.Property ],
for : [ 'htmlFor' , null, FieldFlags.Property ],
"accept-charset": [ 'acceptCharset' , null, FieldFlags.Property ],
"http-equiv" : [ 'httpEquiv' , null, FieldFlags.Property ],
// a few React oddities, mostly disagreeing about casing
onDoubleClick : [ 'ondblclick' , null, FieldFlags.Property ],
spellCheck : [ 'spellcheck' , null, FieldFlags.Property ],
allowFullScreen : [ 'allowFullscreen', null, FieldFlags.Property ],
autoCapitalize : [ 'autocapitalize' , null, FieldFlags.Property ],
autoFocus : [ 'autofocus' , null, FieldFlags.Property ],
autoPlay : [ 'autoplay' , null, FieldFlags.Property ],
// other
// role is part of the ARIA spec but not caught by the aria- attr filter
role : [ 'role' , null, FieldFlags.Attribute ]
} as { [ field : string ] : FieldData },
svgFieldCache = {
// special props
style : [ 'style' , null, FieldFlags.Assign ],
ref : [ 'ref' , null, FieldFlags.Ignore ],
fn : [ 'fn' , null, FieldFlags.Ignore ],
// property compat
className : [ 'class' , null, FieldFlags.Attribute ],
htmlFor : [ 'for' , null, FieldFlags.Attribute ],
tabIndex : [ 'tabindex' , null, FieldFlags.Attribute ],
// React compat
onDoubleClick: [ 'ondblclick' , null, FieldFlags.Property ],
// attributes with eccentric casing - some SVG attrs are snake-cased, some camelCased
allowReorder : [ 'allowReorder' , null, FieldFlags.Attribute ],
attributeName : [ 'attributeName' , null, FieldFlags.Attribute ],
attributeType : [ 'attributeType' , null, FieldFlags.Attribute ],
autoReverse : [ 'autoReverse' , null, FieldFlags.Attribute ],
baseFrequency : [ 'baseFrequency' , null, FieldFlags.Attribute ],
calcMode : [ 'calcMode' , null, FieldFlags.Attribute ],
clipPathUnits : [ 'clipPathUnits' , null, FieldFlags.Attribute ],
contentScriptType : [ 'contentScriptType' , null, FieldFlags.Attribute ],
contentStyleType : [ 'contentStyleType' , null, FieldFlags.Attribute ],
diffuseConstant : [ 'diffuseConstant' , null, FieldFlags.Attribute ],
edgeMode : [ 'edgeMode' , null, FieldFlags.Attribute ],
externalResourcesRequired: [ 'externalResourcesRequired', null, FieldFlags.Attribute ],
filterRes : [ 'filterRes' , null, FieldFlags.Attribute ],
filterUnits : [ 'filterUnits' , null, FieldFlags.Attribute ],
gradientTransform : [ 'gradientTransform' , null, FieldFlags.Attribute ],
gradientUnits : [ 'gradientUnits' , null, FieldFlags.Attribute ],
kernelMatrix : [ 'kernelMatrix' , null, FieldFlags.Attribute ],
kernelUnitLength : [ 'kernelUnitLength' , null, FieldFlags.Attribute ],
keyPoints : [ 'keyPoints' , null, FieldFlags.Attribute ],
keySplines : [ 'keySplines' , null, FieldFlags.Attribute ],
keyTimes : [ 'keyTimes' , null, FieldFlags.Attribute ],
lengthAdjust : [ 'lengthAdjust' , null, FieldFlags.Attribute ],
limitingConeAngle : [ 'limitingConeAngle' , null, FieldFlags.Attribute ],
markerHeight : [ 'markerHeight' , null, FieldFlags.Attribute ],
markerUnits : [ 'markerUnits' , null, FieldFlags.Attribute ],
maskContentUnits : [ 'maskContentUnits' , null, FieldFlags.Attribute ],
maskUnits : [ 'maskUnits' , null, FieldFlags.Attribute ],
numOctaves : [ 'numOctaves' , null, FieldFlags.Attribute ],
pathLength : [ 'pathLength' , null, FieldFlags.Attribute ],
patternContentUnits : [ 'patternContentUnits' , null, FieldFlags.Attribute ],
patternTransform : [ 'patternTransform' , null, FieldFlags.Attribute ],
patternUnits : [ 'patternUnits' , null, FieldFlags.Attribute ],
pointsAtX : [ 'pointsAtX' , null, FieldFlags.Attribute ],
pointsAtY : [ 'pointsAtY' , null, FieldFlags.Attribute ],
pointsAtZ : [ 'pointsAtZ' , null, FieldFlags.Attribute ],
preserveAlpha : [ 'preserveAlpha' , null, FieldFlags.Attribute ],
preserveAspectRatio : [ 'preserveAspectRatio' , null, FieldFlags.Attribute ],
primitiveUnits : [ 'primitiveUnits' , null, FieldFlags.Attribute ],
refX : [ 'refX' , null, FieldFlags.Attribute ],
refY : [ 'refY' , null, FieldFlags.Attribute ],
repeatCount : [ 'repeatCount' , null, FieldFlags.Attribute ],
repeatDur : [ 'repeatDur' , null, FieldFlags.Attribute ],
requiredExtensions : [ 'requiredExtensions' , null, FieldFlags.Attribute ],
requiredFeatures : [ 'requiredFeatures' , null, FieldFlags.Attribute ],
specularConstant : [ 'specularConstant' , null, FieldFlags.Attribute ],
specularExponent : [ 'specularExponent' , null, FieldFlags.Attribute ],
spreadMethod : [ 'spreadMethod' , null, FieldFlags.Attribute ],
startOffset : [ 'startOffset' , null, FieldFlags.Attribute ],
stdDeviation : [ 'stdDeviation' , null, FieldFlags.Attribute ],
stitchTiles : [ 'stitchTiles' , null, FieldFlags.Attribute ],
surfaceScale : [ 'surfaceScale' , null, FieldFlags.Attribute ],
systemLanguage : [ 'systemLanguage' , null, FieldFlags.Attribute ],
tableValues : [ 'tableValues' , null, FieldFlags.Attribute ],
targetX : [ 'targetX' , null, FieldFlags.Attribute ],
targetY : [ 'targetY' , null, FieldFlags.Attribute ],
textLength : [ 'textLength' , null, FieldFlags.Attribute ],
viewBox : [ 'viewBox' , null, FieldFlags.Attribute ],
viewTarget : [ 'viewTarget' , null, FieldFlags.Attribute ],
xChannelSelector : [ 'xChannelSelector' , null, FieldFlags.Attribute ],
yChannelSelector : [ 'yChannelSelector' , null, FieldFlags.Attribute ],
zoomAndPan : [ 'zoomAndPan' , null, FieldFlags.Attribute ],
} as { [ field : string ] : FieldData };
const
attributeOnlyRx = /-/,
deepAttrRx = /^style-/,
isAttrOnlyField = (field : string) => attributeOnlyRx.test(field) && !deepAttrRx.test(field),
propOnlyRx = /^(on|style)/,
isPropOnlyField = (field : string) => propOnlyRx.test(field),
propPartRx = /[a-z][A-Z]/g,
getAttrName = (field : string) => field.replace(propPartRx, m => m[0] + '-' + m[1]).toLowerCase(),
jsxEventPropRx = /^on[A-Z]/,
attrPartRx = /\-(?:[a-z]|$)/g,
getPropName = (field : string) => {
var prop = field.replace(attrPartRx, m => m.length === 1 ? '' : m[1].toUpperCase());
return jsxEventPropRx.test(prop) ? prop.toLowerCase() : prop;
},
deepPropRx = /^(style)([A-Z])/,
buildPropData = (prop : string) : FieldData => {
var m = deepPropRx.exec(prop);
return m ? [ m[2].toLowerCase() + prop.substr(m[0].length), m[1], FieldFlags.Property ] : [ prop, null, FieldFlags.Property ];
},
attrNamespaces = {
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace",
} as { [ name : string ] : string },
attrNamespaceRx = new RegExp(`^(${Object.keys(attrNamespaces).join('|')})-(.*)`),
buildAttrData = (attr : string) : FieldData => {
var m = attrNamespaceRx.exec(attr);
return m ? [ m[2], attrNamespaces[m[1]], FieldFlags.Attribute ] : [ attr, null, FieldFlags.Attribute ];
};
export const
getFieldData = (field : string, svg : boolean) : FieldData => {
let cache = svg ? svgFieldCache : htmlFieldCache,
cached = cache[field];
if (cached) return cached;
let attr = svg && !isPropOnlyField(field)
|| !svg && isAttrOnlyField(field),
name = attr ? getAttrName(field) : getPropName(field);
if (name !== field && (cached = cache[name])) return cached;
let data = attr ? buildAttrData(name) : buildPropData(name);
return cache[field] = data;
} | the_stack |
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output,
ViewEncapsulation
} from '@angular/core';
import { Observable, of as observableOf, Subscription } from 'rxjs';
import { HostWindowService } from '../host-window.service';
import { HostWindowState } from '../search/host-window.reducer';
import { PaginationComponentOptions } from './pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { hasValue } from '../empty.util';
import { PageInfo } from '../../core/shared/page-info.model';
import { PaginationService } from '../../core/pagination/pagination.service';
import { map } from 'rxjs/operators';
/**
* The default pagination controls component.
*/
@Component({
exportAs: 'paginationComponent',
selector: 'ds-pagination',
styleUrls: ['pagination.component.scss'],
templateUrl: 'pagination.component.html',
changeDetection: ChangeDetectionStrategy.Default,
encapsulation: ViewEncapsulation.Emulated
})
export class PaginationComponent implements OnDestroy, OnInit {
/**
* Number of items in collection.
*/
@Input() collectionSize: number;
/**
* Page state of a Remote paginated objects.
*/
@Input() pageInfoState: Observable<PageInfo> = undefined;
/**
* Configuration for the NgbPagination component.
*/
@Input() paginationOptions: PaginationComponentOptions;
/**
* Sort configuration for this component.
*/
@Input() sortOptions: SortOptions;
/**
* An event fired when the page is changed.
* Event's payload equals to the newly selected page.
*/
@Output() pageChange: EventEmitter<number> = new EventEmitter<number>();
/**
* An event fired when the page wsize is changed.
* Event's payload equals to the newly selected page size.
*/
@Output() pageSizeChange: EventEmitter<number> = new EventEmitter<number>();
/**
* An event fired when the sort direction is changed.
* Event's payload equals to the newly selected sort direction.
*/
@Output() sortDirectionChange: EventEmitter<SortDirection> = new EventEmitter<SortDirection>();
/**
* An event fired when the sort field is changed.
* Event's payload equals to the newly selected sort field.
*/
@Output() sortFieldChange: EventEmitter<string> = new EventEmitter<string>();
/**
* An event fired when the pagination is changed.
* Event's payload equals to the newly selected sort field.
*/
@Output() paginationChange: EventEmitter<any> = new EventEmitter<any>();
/**
* Option for hiding the pagination detail
*/
@Input() public hidePaginationDetail = false;
/**
* Option for hiding the gear
*/
@Input() public hideGear = false;
/**
* Option for hiding the pager when there is less than 2 pages
*/
@Input() public hidePagerWhenSinglePage = true;
/**
* Option for retaining the scroll position upon navigating to an url with updated params.
* After the page update the page will scroll back to the current pagination component.
*/
@Input() public retainScrollPosition = false;
/**
* Current page.
*/
public currentPage$;
/**
* Current page in the state of a Remote paginated objects.
*/
public currentPageState: number = undefined;
/**
* An observable of HostWindowState type
*/
public hostWindow: Observable<HostWindowState>;
/**
* ID for the pagination instance. This ID is used in the routing to retrieve the pagination options.
* This ID needs to be unique between different pagination components when more than one will be displayed on the same page.
*/
public id: string;
/**
* A boolean that indicate if is an extra small devices viewport.
*/
public isXs: boolean;
/**
* Number of items per page.
*/
public pageSize$;
/**
* Declare SortDirection enumeration to use it in the template
*/
public sortDirections = SortDirection;
/**
* A number array that represents options for a context pagination limit.
*/
public pageSizeOptions: number[];
/**
* Direction in which to sort: ascending or descending
*/
public sortDirection$: Observable<SortDirection>;
public defaultsortDirection: SortDirection = SortDirection.ASC;
/**
* Name of the field that's used to sort by
*/
public sortField$;
public defaultSortField = 'name';
/**
* Array to track all subscriptions and unsubscribe them onDestroy
* @type {Array}
*/
private subs: Subscription[] = [];
/**
* Method provided by Angular. Invoked after the constructor.
*/
ngOnInit() {
this.subs.push(this.hostWindowService.isXs()
.subscribe((status: boolean) => {
this.isXs = status;
this.cdRef.markForCheck();
}));
this.checkConfig(this.paginationOptions);
this.initializeConfig();
}
/**
* Method provided by Angular. Invoked when the instance is destroyed.
*/
ngOnDestroy() {
this.subs
.filter((sub) => hasValue(sub))
.forEach((sub) => sub.unsubscribe());
}
/**
* Initializes all default variables
*/
private initializeConfig() {
// Set initial values
this.id = this.paginationOptions.id || null;
this.pageSizeOptions = this.paginationOptions.pageSizeOptions;
this.currentPage$ = this.paginationService.getCurrentPagination(this.id, this.paginationOptions).pipe(
map((currentPagination) => currentPagination.currentPage)
);
this.pageSize$ = this.paginationService.getCurrentPagination(this.id, this.paginationOptions).pipe(
map((currentPagination) => currentPagination.pageSize)
);
let sortOptions;
if (this.sortOptions) {
sortOptions = this.sortOptions;
} else {
sortOptions = new SortOptions(this.defaultSortField, this.defaultsortDirection);
}
this.sortDirection$ = this.paginationService.getCurrentSort(this.id, sortOptions).pipe(
map((currentSort) => currentSort.direction)
);
this.sortField$ = this.paginationService.getCurrentSort(this.id, sortOptions).pipe(
map((currentSort) => currentSort.field)
);
}
/**
* @param cdRef
* ChangeDetectorRef is a singleton service provided by Angular.
* @param route
* Route is a singleton service provided by Angular.
* @param router
* Router is a singleton service provided by Angular.
* @param hostWindowService
* the HostWindowService singleton.
*/
constructor(private cdRef: ChangeDetectorRef,
private paginationService: PaginationService,
public hostWindowService: HostWindowService) {
}
/**
* Method to change the route to the given page
*
* @param page
* The page being navigated to.
*/
public doPageChange(page: number) {
this.updateParams({page: page.toString()});
this.emitPaginationChange();
}
/**
* Method to change the route to the given page size
*
* @param pageSize
* The page size being navigated to.
*/
public doPageSizeChange(pageSize: number) {
this.updateParams({ pageId: this.id, page: 1, pageSize: pageSize });
this.emitPaginationChange();
}
/**
* Method to change the route to the given sort direction
*
* @param sortDirection
* The sort direction being navigated to.
*/
public doSortDirectionChange(sortDirection: SortDirection) {
this.updateParams({ pageId: this.id, page: 1, sortDirection: sortDirection });
this.emitPaginationChange();
}
/**
* Method to change the route to the given sort field
*
* @param sortField
* The sort field being navigated to.
*/
public doSortFieldChange(field: string) {
this.updateParams({ pageId: this.id, page: 1, sortField: field });
this.emitPaginationChange();
}
/**
* Method to emit a general pagination change event
*/
private emitPaginationChange() {
this.paginationChange.emit();
}
/**
* Update the current query params and optionally update the route
* @param params
*/
private updateParams(params: {}) {
this.paginationService.updateRoute(this.id, params, {}, this.retainScrollPosition);
}
/**
* Method to get pagination details of the current viewed page.
*/
public getShowingDetails(collectionSize: number): Observable<any> {
let showingDetails = observableOf({ range: null + ' - ' + null, total: null });
if (collectionSize) {
showingDetails = this.paginationService.getCurrentPagination(this.id, this.paginationOptions).pipe(
map((currentPaginationOptions) => {
let firstItem;
let lastItem;
const pageMax = currentPaginationOptions.pageSize * currentPaginationOptions.currentPage;
firstItem = currentPaginationOptions.pageSize * (currentPaginationOptions.currentPage - 1) + 1;
if (collectionSize > pageMax) {
lastItem = pageMax;
} else {
lastItem = collectionSize;
}
return {range: firstItem + ' - ' + lastItem, total: collectionSize};
})
);
}
return showingDetails;
}
/**
* Method to ensure options passed contains the required properties.
*
* @param paginateOptions
* The paginate options object.
*/
private checkConfig(paginateOptions: any) {
const required = ['id', 'currentPage', 'pageSize', 'pageSizeOptions'];
const missing = required.filter((prop) => {
return !(prop in paginateOptions);
});
if (0 < missing.length) {
throw new Error('Paginate: Argument is missing the following required properties: ' + missing.join(', '));
}
}
/**
* Property to check whether the current pagination object has multiple pages
* @returns true if there are multiple pages, else returns false
*/
get hasMultiplePages(): Observable<boolean> {
return this.paginationService.getCurrentPagination(this.id, this.paginationOptions).pipe(
map((currentPaginationOptions) => this.collectionSize > currentPaginationOptions.pageSize)
);
}
/**
* Property to check whether the current pagination should show a bottom pages
* @returns true if a bottom pages should be shown, else returns false
*/
get shouldShowBottomPager(): Observable<boolean> {
return this.hasMultiplePages.pipe(
map((hasMultiplePages) => hasMultiplePages || !this.hidePagerWhenSinglePage)
);
}
} | the_stack |
import transform from 'lodash/transform';
import throttle from 'lodash/throttle';
import CodeMirror from 'codemirror';
import * as userAgent from '../../utils/userAgent';
import { EditorDirection } from '../../types';
function stripUnit(value: number | string): number {
if (typeof value !== 'string') return value;
const cssRegex = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/;
const matchedValue = value.match(cssRegex);
if (!matchedValue) {
throw new Error("Couldn't match unit in given string");
}
return parseFloat(value);
}
export function create(
host: HTMLElement,
options: {
direction: EditorDirection;
readOnly: boolean;
fixedHeight?: number | boolean;
height?: number | string;
}
) {
const { direction, fixedHeight, height, readOnly } = options || {};
// Set to true if `setValue()` has been called. This is to prevent
// undoing the initial content.
let initializedWithValue = false;
const LF = '\n';
const EDITOR_SIZE = {
min: height ? stripUnit(height) : 300,
max: 500,
shift: 50,
};
// eslint-disable-next-line
// @ts-ignore
const cm = CodeMirror(host, {
direction,
readOnly,
mode: 'markdown',
lineNumbers: false,
undoDepth: 200,
matchBrackets: true,
lineWrapping: true,
// When `lineSeparator === null` the document will be split
// on CRLFs as well as lone CRs and LFs. A single LF will
// be used as line separator in all output
lineSeparator: null,
theme: 'elegant',
tabSize: 2,
indentWithTabs: false,
indentUnit: 2,
autoRefresh: true
});
cm.setSize('100%', EDITOR_SIZE.min);
if (!fixedHeight) {
cm.on('change', throttle(assureHeight, 150));
}
cm.setOption('extraKeys', {
Tab: function () {
replaceSelectedText(getIndentation());
},
Enter: 'newlineAndIndentContinueMarkdownList',
Esc: () => {
cm.getInputField().blur();
},
});
/**
* @description
* Custom API for a CodeMirror instance.
*
* An instance wraps a CodeMirror instance and provides a custom interface
* on top of CodeMirror.
*/
return {
destroy,
disable,
enable,
attachEvent,
addKeyShortcuts,
setValue,
cmd,
moveToLineBeginning,
moveIfNotEmpty,
restoreCursor,
moveToLineEnd,
usePrimarySelection,
focus,
select,
selectBackwards,
selectAll: () => cm.execCommand('selectAll'),
extendSelectionBy,
insertAtCursor,
insertAtLineBeginning,
wrapSelection,
removeFromLineBeginning,
removeSelectedText,
replaceSelectedText,
getCursor,
setCursor,
getSelection,
getLine,
isLineEmpty,
getSelectedText,
getSelectionLength,
getCurrentLine,
getCurrentLineNumber,
getCurrentCharacter,
getCurrentLineLength,
lineStartsWith,
getIndentation,
getNl,
getValue,
getLinesCount,
getHistorySize,
setReadOnly: (value: boolean) => cm.setOption('readOnly', value),
getHistory: () => cm.getHistory(),
setHistory: (history: any) => cm.setHistory(history),
setFullsize: () => {
cm.setSize('100%', '100%');
cm.refresh();
},
refresh: () => cm.refresh(),
};
function destroy() {
// @ts-expect-error
cm.toTextArea();
}
function disable() {
cm.setOption('readOnly', 'nocursor');
}
function enable() {
cm.setOption('readOnly', false);
}
function assureHeight() {
const current = cm.heightAtLine(cm.lastLine(), 'local') + EDITOR_SIZE.shift;
let next = current;
if (current < EDITOR_SIZE.min) {
next = EDITOR_SIZE.min;
}
if (current > EDITOR_SIZE.max) {
next = EDITOR_SIZE.max;
}
cm.setSize('100%', next);
}
function attachEvent(name: string, fn: Function, throttleInterval: number) {
if (throttleInterval) {
fn = throttle(fn as any, throttleInterval);
}
cm.on(name, fn as any);
}
function addKeyShortcuts(map: any) {
const ctrlKey = userAgent.getCtrlKey();
cm.addKeyMap(
transform(
map,
(acc, value, key) => {
// eslint-disable-next-line
// @ts-ignore
acc[ctrlKey + '-' + key] = value;
},
{}
)
);
}
/**
* low-level editor manipulation functions
*/
/**
* @description
* Sets the content of the editor while preserving the cursor
* position.
*
* If called for the first time it will not record the change in
* the history.
*/
function setValue(value?: string) {
value = value || '';
if (getValue() === value) {
return;
}
// set value, but save cursor position first
// position will be restored, but w/o focus (third arg)
const line = getCurrentLineNumber();
const ch = getCurrentCharacter();
cm.setValue(value);
restoreCursor(ch, line, true);
// We do not want to record the initial population in the
// history. Otherwise it would always be possible to revert to
// the empty string.
if (!initializedWithValue) {
cm.clearHistory();
initializedWithValue = true;
}
}
function cmd(name: string) {
cm.execCommand(name);
cm.focus();
}
function moveToLineBeginning(lineNumber?: number) {
cm.setCursor({ line: defaultToCurrentLineNumber(lineNumber), ch: 0 });
cm.focus();
}
/**
* @description
* Insert a new line below the cursor and move to the beginning of
* that line.
*
* Only do this if the editor has content and we are not already on
* the last line.
*
* TODO rename this
*/
function moveIfNotEmpty() {
if (getCurrentLineLength() < 1) {
return;
}
const next = getCurrentLineNumber() + 1;
if (cm.lastLine() < next) {
moveToLineEnd();
insertAtCursor(getNl());
}
moveToLineBeginning(next);
}
function restoreCursor(character: number, lineNumber?: number, noFocus?: boolean) {
cm.setCursor(defaultToCurrentLineNumber(lineNumber), character, {
scroll: !noFocus,
});
if (!noFocus) {
cm.focus();
}
}
function moveToLineEnd(lineNumber?: number) {
cm.setCursor({
line: defaultToCurrentLineNumber(lineNumber),
ch: getCurrentLineLength(),
});
cm.focus();
}
function defaultToCurrentLineNumber(lineNumber?: number) {
if (lineNumber === 0 || (lineNumber !== undefined && lineNumber > 0)) {
return lineNumber;
}
return getCurrentLineNumber();
}
function usePrimarySelection() {
cmd('singleSelection');
}
function focus() {
cm.focus();
}
function select(from: CodeMirror.Position, to: CodeMirror.Position) {
cm.setSelection(from, to);
cm.focus();
}
function selectBackwards(skip: number, len: number) {
select(getPos(-skip - len), getPos(-skip));
function getPos(modifier: number) {
return {
line: getCurrentLineNumber(),
ch: getCurrentCharacter() + modifier,
};
}
}
function extendSelectionBy(modifier: number) {
select(getPos('anchor', 0), getPos('head', modifier));
function getPos(prop: 'anchor' | 'head', modifier: number): CodeMirror.Position {
const selection = getSelection();
if (!selection) {
return { line: 0, ch: 0 };
}
return { line: selection[prop].line, ch: selection[prop].ch + modifier };
}
}
function insertAtCursor(text: string) {
cm.replaceRange(text, cm.getCursor());
cm.focus();
}
function insertAtLineBeginning(text: string) {
const initialCh = getCurrentCharacter();
moveToLineBeginning();
insertAtCursor(text);
restoreCursor(initialCh + text.length);
cm.focus();
}
function wrapSelection(wrapper: string) {
const replacement = wrapper + getSelectedText() + wrapper;
const selection = getSelection();
if (selection) {
cm.replaceRange(replacement, selection.anchor, selection?.head);
cm.focus();
}
}
function removeFromLineBeginning(charCount: number) {
const lineNumber = getCurrentLineNumber();
cm.replaceRange('', { line: lineNumber, ch: 0 }, { line: lineNumber, ch: charCount });
cm.focus();
}
function removeSelectedText() {
cm.replaceSelection('');
cm.focus();
}
/**
* @description
* Replace the selected text with the given string.
*
* If nothing is selected it will insert the text at the current
* cursor position
*
* The optional `select` parameter controls what will be selected
* afters wards. By default the cursor will be at the end of the
* inserted text. You can pass 'around' to select the inserted
* text.
*/
function replaceSelectedText(replacement: string, select?: string) {
cm.replaceSelection(replacement, select);
cm.focus();
}
/**
* low-level editor get/check functions
*/
function getCursor() {
return cm.getCursor();
}
function setCursor(cursor: number | CodeMirror.Position) {
cm.setCursor(cursor);
}
function getSelection() {
const selections = cm.listSelections();
if (!cm.somethingSelected() || !selections || selections.length < 1) {
return null;
}
return selections[0];
}
function getLine(lineNumber: number) {
return cm.getLine(lineNumber) || '';
}
function isLineEmpty(lineNumber?: number) {
const n = defaultToCurrentLineNumber(lineNumber);
return n > -1 && getLine(n).length < 1 && n < cm.lineCount();
}
function getLinesCount() {
return cm.lineCount();
}
function getSelectedText() {
return getSelection() ? cm.getSelection() : '';
}
function getSelectionLength() {
return getSelectedText().length;
}
function getCurrentLine() {
return getLine(getCurrentLineNumber());
}
function getCurrentLineNumber() {
return cm.getCursor().line;
}
function getCurrentCharacter() {
return cm.getCursor().ch;
}
function getCurrentLineLength() {
return getCurrentLine().length;
}
function lineStartsWith(text: string) {
return getCurrentLine().startsWith(text);
}
function getIndentation() {
return repeat(' ', cm.getOption('indentUnit') ?? 0);
}
function getNl(n = 1) {
if (n < 1) {
return '';
}
return repeat(LF, n);
}
function getValue() {
return cm.getValue() || '';
}
function getHistorySize(which?: 'undo' | 'redo') {
const history = cm.historySize();
return which ? history[which] : history;
}
function repeat(what: string, n: number) {
return new Array(n + 1).join(what);
}
} | the_stack |
import { call, delay, put, select, takeEvery, takeLatest } from 'redux-saga/effects'
import { createIdentity } from 'eth-crypto'
import { Personal } from 'web3x/personal/personal'
import { Account } from 'web3x/account'
import { Authenticator } from 'dcl-crypto'
import { ENABLE_WEB3, ETHEREUM_NETWORK, PREVIEW, setNetwork, WORLD_EXPLORER } from 'config'
import { createLogger } from 'shared/logger'
import { initializeReferral, referUser } from 'shared/referral'
import {
createEth,
getEthConnector,
getProviderType,
getUserEthAccountIfAvailable,
isGuest,
isSessionExpired,
loginCompleted,
requestProvider as requestEthProvider
} from 'shared/ethereum/provider'
import { setLocalInformationForComms } from 'shared/comms/peers'
import { BringDownClientAndShowError, ErrorContext, ReportFatalError } from 'shared/loading/ReportFatalError'
import {
AUTH_ERROR_LOGGED_OUT,
AWAITING_USER_SIGNATURE,
setLoadingScreen,
setLoadingWaitTutorial
} from 'shared/loading/types'
import { identifyEmail, identifyUser, trackEvent } from 'shared/analytics'
import { checkTldVsWeb3Network, getAppNetwork } from 'shared/web3'
import { connection, Provider, ProviderType } from 'decentraland-connect'
import { getFromLocalStorage, saveToLocalStorage } from 'atomicHelpers/localStorage'
import {
getLastSessionByProvider,
getLastSessionWithoutWallet,
getStoredSession,
removeStoredSession,
Session,
setStoredSession
} from './index'
import { ExplorerIdentity, LoginStage, StoredSession } from './types'
import {
AUTHENTICATE,
AuthenticateAction,
changeLoginStage,
INIT_SESSION,
loginCompleted as loginCompletedAction,
LOGOUT,
REDIRECT_TO_SIGN_UP,
signInSetCurrentProvider,
signInSigning,
SIGNUP,
SIGNUP_CANCEL,
signUpClearData,
signUpSetIdentity,
signUpSetIsSignUp,
signUpSetProfile,
toggleWalletPrompt,
UPDATE_TOS,
updateTOS,
userAuthentified,
authenticate as authenticateAction
} from './actions'
import Html from '../Html'
import { fetchProfileLocally, doesProfileExist } from '../profiles/sagas'
import { generateRandomUserProfile } from '../profiles/generateRandomUserProfile'
import { unityInterface } from '../../unity-interface/UnityInterface'
import { getSignUpIdentity, getSignUpProfile } from './selectors'
import { ensureRealmInitialized } from '../dao/sagas'
import { saveProfileRequest } from '../profiles/actions'
import { Profile } from '../profiles/types'
import { ensureUnityInterface } from "../renderer"
import { refreshLoadingScreen } from "../../unity-interface/dcl"
const TOS_KEY = 'tos'
const logger = createLogger('session: ')
export function* sessionSaga(): any {
yield call(initialize)
yield call(initializeReferral)
yield takeEvery(UPDATE_TOS, updateTermOfService)
yield takeLatest(INIT_SESSION, initSession)
yield takeLatest(LOGOUT, logout)
yield takeLatest(REDIRECT_TO_SIGN_UP, redirectToSignUp)
yield takeLatest(SIGNUP, signUp)
yield takeLatest(SIGNUP_CANCEL, cancelSignUp)
yield takeLatest(AUTHENTICATE, authenticate)
yield takeLatest(AWAITING_USER_SIGNATURE, scheduleAwaitingSignaturePrompt)
}
function* initialize() {
const tosAgreed: boolean = !!getFromLocalStorage(TOS_KEY)
yield put(updateTOS(tosAgreed))
Html.initializeTos(tosAgreed)
}
function* updateTermOfService(action: any) {
return saveToLocalStorage(TOS_KEY, action.payload)
}
function* scheduleAwaitingSignaturePrompt() {
yield delay(10000)
const isStillWaiting: boolean = yield select((state) => !state.session?.initialized)
if (isStillWaiting) {
yield put(toggleWalletPrompt(true))
refreshLoadingScreen()
Html.showAwaitingSignaturePrompt(true)
}
}
function* initSession() {
yield ensureRealmInitialized()
yield checkConnector()
if (ENABLE_WEB3) {
yield checkPreviousSession()
Html.showEthLogin()
} else {
yield previewAutoSignIn()
}
yield put(changeLoginStage(LoginStage.SIGN_IN))
if (ENABLE_WEB3) {
const connecetor = getEthConnector()
if (connecetor.isConnected()) {
yield put(authenticateAction(connecetor.getType()))
return
}
}
Html.bindLoginEvent()
}
function* checkConnector() {
const connecetor = getEthConnector()
yield call(() => connecetor.restoreConnection())
}
function* checkPreviousSession() {
const connecetor = getEthConnector()
const session = getLastSessionWithoutWallet()
if (!isSessionExpired(session) && session) {
const identity = session.identity
if (identity && identity.provider) {
yield put(signInSetCurrentProvider(identity.provider))
}
} else {
try {
yield call(() => connecetor.disconnect())
} catch (e) {
logger.error(e)
}
removeStoredSession(session?.userId)
}
}
function* previewAutoSignIn() {
yield requestProvider(null)
const session: { userId: string; identity: ExplorerIdentity } = yield authorize()
yield signIn(session.userId, session.identity)
}
function* authenticate(action: AuthenticateAction) {
yield put(signInSigning(true))
const provider = yield requestProvider(action.payload.provider)
if (!provider) {
yield put(signInSigning(false))
return
}
const session = yield authorize()
let profileExists = yield doesProfileExist(session.userId)
if (profileExists || isGuestWithProfile(session) || PREVIEW) {
return yield signIn(session.userId, session.identity)
}
return yield startSignUp(session.userId, session.identity)
}
function isGuestWithProfile(session: StoredSession) {
const profile = fetchProfileLocally(session.userId)
return isGuest() && profile
}
function* startSignUp(userId: string, identity: ExplorerIdentity) {
yield ensureUnityInterface()
yield put(signUpSetIsSignUp(true))
let prevGuest = fetchProfileLocally(userId)
let profile: Profile = prevGuest ? prevGuest : yield generateRandomUserProfile(userId)
profile.userId = identity.address
profile.ethAddress = identity.rawAddress
profile.unclaimedName = '' // clean here to allow user complete in passport step
profile.hasClaimedName = false
profile.version = 0
yield put(signUpSetIdentity(userId, identity))
yield put(signUpSetProfile(profile))
if (prevGuest) {
return yield signUp()
}
yield showAvatarEditor()
}
function* showAvatarEditor() {
yield put(setLoadingScreen(true))
refreshLoadingScreen()
yield put(changeLoginStage(LoginStage.SIGN_UP))
const profile: Partial<Profile> = yield select(getSignUpProfile)
// TODO: Fix as any
unityInterface.LoadProfile(profile as any)
unityInterface.ShowAvatarEditorInSignIn()
yield put(setLoadingScreen(false))
refreshLoadingScreen()
Html.switchGameContainer(true)
}
function* requestProvider(providerType: ProviderType | null) {
const provider: Provider | null = yield requestEthProvider(providerType)
if (provider) {
if (WORLD_EXPLORER && (yield checkTldVsWeb3Network())) {
throw new Error('Network mismatch')
}
if (PREVIEW && ETHEREUM_NETWORK.MAINNET === (yield getAppNetwork())) {
Html.showNetworkWarning()
}
}
return provider
}
function* authorize() {
if (ENABLE_WEB3) {
try {
let userData: StoredSession | null = null
if (isGuest()) {
userData = getLastSessionByProvider(null)
} else {
const ethAddress: string | undefined = yield getUserEthAccountIfAvailable(true)
if (ethAddress) {
const address = ethAddress.toLocaleLowerCase()
userData = getStoredSession(address)
if (userData) {
// We save the raw ethereum address of the current user to avoid having to convert-back later after lowercasing it for the userId
userData.identity.rawAddress = ethAddress
}
}
}
// check that user data is stored & key is not expired
if (!userData || isSessionExpired(userData)) {
const identity: ExplorerIdentity = yield createAuthIdentity()
return {
userId: identity.address,
identity
}
}
return {
userId: userData.identity.address,
identity: userData.identity
}
} catch (e) {
logger.error(e)
ReportFatalError(e, ErrorContext.KERNEL_INIT)
BringDownClientAndShowError(AUTH_ERROR_LOGGED_OUT)
throw e
}
} else {
logger.log(`Using test user.`)
const identity: ExplorerIdentity = yield createAuthIdentity()
const session = { userId: identity.address, identity }
saveSession(session.userId, session.identity)
return session
}
}
function* signIn(userId: string, identity: ExplorerIdentity) {
logger.log(`User ${userId} logged in`)
yield put(changeLoginStage(LoginStage.COMPLETED))
saveSession(userId, identity)
if (identity.hasConnectedWeb3) {
identifyUser(userId)
referUser(identity)
}
yield put(signInSigning(false))
yield setUserAuthentified(userId, identity)
loginCompleted.resolve()
yield put(loginCompletedAction())
}
function* setUserAuthentified(userId: string, identity: ExplorerIdentity) {
let net: ETHEREUM_NETWORK = ETHEREUM_NETWORK.MAINNET
if (WORLD_EXPLORER) {
net = yield getAppNetwork()
// Load contracts from https://contracts.decentraland.org
yield setNetwork(net)
trackEvent('Use network', { net })
}
yield put(userAuthentified(userId, identity, net))
}
function* signUp() {
yield put(setLoadingScreen(true))
refreshLoadingScreen()
yield put(changeLoginStage(LoginStage.COMPLETED))
const session = yield select(getSignUpIdentity)
logger.log(`User ${session.userId} signed up`)
const profile = yield select(getSignUpProfile)
profile.userId = session.userId
profile.ethAddress = session.identity.rawAddress
profile.version = 0
profile.hasClaimedName = false
if (profile.email) {
identifyEmail(profile.email, isGuest() ? undefined : profile.userId)
profile.tutorialStep |= 128 // We use binary 256 for tutorial and 128 for email promp
}
delete profile.email // We don't deploy the email because it is public
yield put(setLoadingWaitTutorial(true))
refreshLoadingScreen()
yield signIn(session.userId, session.identity)
yield put(saveProfileRequest(profile, session.userId))
yield put(signUpClearData())
}
function* cancelSignUp() {
yield put(signUpClearData())
yield put(signInSigning(false))
yield put(signUpSetIsSignUp(false))
yield put(changeLoginStage(LoginStage.SIGN_IN))
}
function saveSession(userId: string, identity: ExplorerIdentity) {
setStoredSession({
userId,
identity
})
setLocalInformationForComms(userId, {
userId,
identity
})
}
async function createAuthIdentity(): Promise<ExplorerIdentity> {
const ephemeral = createIdentity()
let ephemeralLifespanMinutes = 7 * 24 * 60 // 1 week
let address
let signer
let provider: ProviderType | null
let hasConnectedWeb3 = false
if (ENABLE_WEB3 && !isGuest()) {
const eth = createEth()!
const account = (await eth.getAccounts())[0]
address = account.toJSON()
provider = getProviderType()
signer = async (message: string) => {
let result
while (!result) {
try {
result = await new Personal(eth.provider).sign(message, account, '')
} catch (e) {
if (e.message && e.message.includes('User denied message signature')) {
put(changeLoginStage(LoginStage.SIGN_ADVICE))
Html.showEthSignAdvice(true)
}
}
}
put(changeLoginStage(LoginStage.COMPLETED))
Html.showEthSignAdvice(false)
return result
}
hasConnectedWeb3 = true
} else {
const account: Account = Account.create()
provider = null
address = account.address.toJSON()
signer = async (message: string) => account.sign(message).signature
// If we are using a local profile, we don't want the identity to expire.
// Eventually, if a wallet gets created, we can migrate the profile to the wallet.
ephemeralLifespanMinutes = 365 * 24 * 60 * 99
}
const auth = await Authenticator.initializeAuthChain(address, ephemeral, ephemeralLifespanMinutes, signer)
return { ...auth, rawAddress: address, address: address.toLocaleLowerCase(), hasConnectedWeb3, provider }
}
function* logout() {
connection.disconnect()
Session.current.logout().catch((e) => logger.error('error while logging out', e))
}
function* redirectToSignUp() {
Session.current.redirectToSignUp().catch((e) => logger.error('error while redirecting to sign up', e))
} | the_stack |
import IndexedFormula from './store'
import { docpart } from './uri'
import Fetcher from './fetcher'
import Namespace from './namespace'
import Serializer from './serializer'
import { join as uriJoin } from './uri'
import { isStore, isBlankNode } from './utils/terms'
import * as Util from './utils-js'
import Statement from './statement'
import RDFlibNamedNode from './named-node'
import { termValue } from './utils/termValue'
import {
BlankNode,
NamedNode,
Quad_Graph,
Quad_Object,
Quad_Predicate,
Quad_Subject,
Quad,
Term,
} from './tf-types'
interface UpdateManagerFormula extends IndexedFormula {
fetcher: Fetcher
}
type CallBackFunction = (uri: string, ok: boolean, message: string, response: Error | Response) => {} | void
/**
* The UpdateManager is a helper object for a store.
* Just as a Fetcher provides the store with the ability to read and write,
* the Update Manager provides functionality for making small patches in real time,
* and also looking out for concurrent updates from other agents
*/
export default class UpdateManager {
store: UpdateManagerFormula
ifps: {}
fps: {}
/** Index of objects for coordinating incoming and outgoing patches */
patchControl: []
/** Object of namespaces */
ns: any
/**
* @param store - The quadstore to store data and metadata. Created if not passed.
*/
constructor (store?: IndexedFormula) {
store = store || new IndexedFormula()
if (store.updater) {
throw new Error("You can't have two UpdateManagers for the same store")
}
if (!(store as UpdateManagerFormula).fetcher) {
(store as UpdateManagerFormula).fetcher = new Fetcher(store)
}
this.store = store as UpdateManagerFormula
store.updater = this
this.ifps = {}
this.fps = {}
this.ns = {}
this.ns.link = Namespace('http://www.w3.org/2007/ont/link#')
this.ns.http = Namespace('http://www.w3.org/2007/ont/http#')
this.ns.httph = Namespace('http://www.w3.org/2007/ont/httph#')
this.ns.ldp = Namespace('http://www.w3.org/ns/ldp#')
this.ns.rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
this.ns.rdfs = Namespace('http://www.w3.org/2000/01/rdf-schema#')
this.ns.rdf = Namespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
this.ns.owl = Namespace('http://www.w3.org/2002/07/owl#')
this.patchControl = []
}
patchControlFor (doc: NamedNode) {
if (!this.patchControl[doc.value]) {
this.patchControl[doc.value] = []
}
return this.patchControl[doc.value]
}
isHttpUri(uri:string){
return( uri.slice(0,4) === 'http' )
}
/**
* Tests whether a file is editable.
* If the file has a specific annotation that it is machine written,
* for safety, it is editable (this doesn't actually check for write access)
* If the file has wac-allow and accept patch headers, those are respected.
* and local write access is determined by those headers.
* This version only looks at past HTTP requests, does not make new ones.
*
* @returns The method string SPARQL or DAV or
* LOCALFILE or false if known, undefined if not known.
*/
editable (uri: string | NamedNode, kb?: IndexedFormula): string | boolean | undefined {
if (!uri) {
return false // Eg subject is bnode, no known doc to write to
}
if (!kb) {
kb = this.store
}
uri = termValue(uri)
if ( !this.isHttpUri(uri as string) ) {
if (kb.holds(
this.store.rdfFactory.namedNode(uri),
this.store.rdfFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
this.store.rdfFactory.namedNode('http://www.w3.org/2007/ont/link#MachineEditableDocument'))) {
return 'LOCALFILE'
}
}
var request
var definitive = false
// @ts-ignore passes a string to kb.each, which expects a term. Should this work?
var requests = kb.each(undefined, this.ns.link('requestedURI'), docpart(uri))
var method: string
for (var r = 0; r < requests.length; r++) {
request = requests[r]
if (request !== undefined) {
var response = kb.any(request, this.ns.link('response')) as Quad_Subject
if (request !== undefined) {
var wacAllow = kb.anyValue(response, this.ns.httph('wac-allow'))
if (wacAllow) {
for (var bit of wacAllow.split(',')) {
var lr = bit.split('=')
if (lr[0].includes('user') && !lr[1].includes('write') && !lr[1].includes('append') ) {
// console.log(' editable? excluded by WAC-Allow: ', wacAllow)
return false
}
}
}
var acceptPatch = kb.each(response, this.ns.httph('accept-patch'))
if (acceptPatch.length) {
for (let i = 0; i < acceptPatch.length; i++) {
method = acceptPatch[i].value.trim()
if (method.indexOf('application/sparql-update') >= 0) return 'SPARQL'
if (method.indexOf('application/sparql-update-single-match') >= 0) return 'SPARQL'
}
}
var authorVia = kb.each(response, this.ns.httph('ms-author-via'))
if (authorVia.length) {
for (let i = 0; i < authorVia.length; i++) {
method = authorVia[i].value.trim()
if (method.indexOf('SPARQL') >= 0) {
return 'SPARQL'
}
if (method.indexOf('DAV') >= 0) {
return 'DAV'
}
}
}
if ( !this.isHttpUri(uri as string) ) {
if( !wacAllow ) return false;
else return 'LOCALFILE';
}
var status = kb.each(response, this.ns.http('status'))
if (status.length) {
for (let i = 0; i < status.length; i++) {
// @ts-ignore since statuses should be TFTerms, this should always be false
if (status[i] === 200 || status[i] === 404) {
definitive = true
// return false // A definitive answer
}
}
}
} else {
// console.log('UpdateManager.editable: No response for ' + uri + '\n')
}
}
}
if (requests.length === 0) {
// console.log('UpdateManager.editable: No request for ' + uri + '\n')
} else {
if (definitive) {
return false // We have got a request and it did NOT say editable => not editable
}
}
// console.log('UpdateManager.editable: inconclusive for ' + uri + '\n')
return undefined // We don't know (yet) as we haven't had a response (yet)
}
anonymize (obj) {
return (obj.toNT().substr(0, 2) === '_:' && this.mentioned(obj))
? '?' + obj.toNT().substr(2)
: obj.toNT()
}
anonymizeNT (stmt: Quad) {
return this.anonymize(stmt.subject) + ' ' +
this.anonymize(stmt.predicate) + ' ' +
this.anonymize(stmt.object) + ' .'
}
/**
* Returns a list of all bnodes occurring in a statement
* @private
*/
statementBnodes (st: Quad): BlankNode[] {
return [st.subject, st.predicate, st.object].filter(function (x) {
return isBlankNode(x)
}) as BlankNode[]
}
/**
* Returns a list of all bnodes occurring in a list of statements
* @private
*/
statementArrayBnodes (sts: Quad[]) {
var bnodes: BlankNode[] = []
for (let i = 0; i < sts.length; i++) {
bnodes = bnodes.concat(this.statementBnodes(sts[i]))
}
bnodes.sort() // in place sort - result may have duplicates
var bnodes2: BlankNode[] = []
for (let j = 0; j < bnodes.length; j++) {
if (j === 0 || !bnodes[j].equals(bnodes[j - 1])) {
bnodes2.push(bnodes[j])
}
}
return bnodes2
}
/**
* Makes a cached list of [Inverse-]Functional properties
* @private
*/
cacheIfps () {
this.ifps = {}
var a = this.store.each(undefined, this.ns.rdf('type'),
this.ns.owl('InverseFunctionalProperty'))
for (let i = 0; i < a.length; i++) {
this.ifps[a[i].value] = true
}
this.fps = {}
a = this.store.each(undefined, this.ns.rdf('type'), this.ns.owl('FunctionalProperty'))
for (let i = 0; i < a.length; i++) {
this.fps[a[i].value] = true
}
}
/**
* Returns a context to bind a given node, up to a given depth
* @private
*/
bnodeContext2 (x, source, depth) {
// Return a list of statements which indirectly identify a node
// Depth > 1 if try further indirection.
// Return array of statements (possibly empty), or null if failure
var sts = this.store.statementsMatching(undefined, undefined, x, source) // incoming links
var y
var res
for (let i = 0; i < sts.length; i++) {
if (this.fps[sts[i].predicate.value]) {
y = sts[i].subject
if (!y.isBlank) {
return [ sts[i] ]
}
if (depth) {
res = this.bnodeContext2(y, source, depth - 1)
if (res) {
return res.concat([ sts[i] ])
}
}
}
}
// outgoing links
sts = this.store.statementsMatching(x, undefined, undefined, source)
for (let i = 0; i < sts.length; i++) {
if (this.ifps[sts[i].predicate.value]) {
y = sts[i].object
if (!y.isBlank) {
return [ sts[i] ]
}
if (depth) {
res = this.bnodeContext2(y, source, depth - 1)
if (res) {
return res.concat([ sts[i] ])
}
}
}
}
return null // Failure
}
/**
* Returns the smallest context to bind a given single bnode
* @private
*/
bnodeContext1 (x, source) {
// Return a list of statements which indirectly identify a node
// Breadth-first
for (var depth = 0; depth < 3; depth++) { // Try simple first
var con = this.bnodeContext2(x, source, depth)
if (con !== null) return con
}
// If we can't guarantee unique with logic just send all info about node
return this.store.connectedStatements(x, source) // was:
// throw new Error('Unable to uniquely identify bnode: ' + x.toNT())
}
/**
* @private
*/
mentioned (x) {
return this.store.statementsMatching(x, null, null, null).length !== 0 || // Don't pin fresh bnodes
this.store.statementsMatching(null, x).length !== 0 ||
this.store.statementsMatching(null, null, x).length !== 0
}
/**
* @private
*/
bnodeContext (bnodes, doc) {
var context = []
if (bnodes.length) {
this.cacheIfps()
for (let i = 0; i < bnodes.length; i++) { // Does this occur in old graph?
var bnode = bnodes[i]
if (!this.mentioned(bnode)) continue
context = context.concat(this.bnodeContext1(bnode, doc))
}
}
return context
}
/**
* Returns the best context for a single statement
* @private
*/
statementContext (st: Quad) {
var bnodes = this.statementBnodes(st)
return this.bnodeContext(bnodes, st.graph)
}
/**
* @private
*/
contextWhere (context) {
var updater = this
return (!context || context.length === 0)
? ''
: 'WHERE { ' +
context.map(function (x) {
return updater.anonymizeNT(x)
}).join('\n') + ' }\n'
}
/**
* @private
*/
fire (
uri: string,
query: string,
callbackFunction: CallBackFunction
): Promise<void> {
return Promise.resolve()
.then(() => {
if (!uri) {
throw new Error('No URI given for remote editing operation: ' + query)
}
// console.log('UpdateManager: sending update to <' + uri + '>')
let options = {
noMeta: true,
contentType: 'application/sparql-update',
body: query
}
return this.store.fetcher.webOperation('PATCH', uri, options)
})
.then(response => {
if (!response.ok) {
let message = 'UpdateManager: update failed for <' + uri + '> status=' +
response.status + ', ' + response.statusText +
'\n for query: ' + query
// console.log(message)
throw new Error(message)
}
// console.log('UpdateManager: update Ok for <' + uri + '>')
callbackFunction(uri, response.ok, response.responseText as string, response)
})
.catch(err => {
callbackFunction(uri, false, err.message, err)
})
}
// ARE THESE THEE FUNCTIONS USED? DEPROCATE?
/** return a statemnet updating function
*
* This does NOT update the statement.
* It returns an object which includes
* function which can be used to change the object of the statement.
*/
update_statement (statement: Quad) {
if (statement && !statement.graph) {
return
}
var updater = this
var context = this.statementContext(statement)
return {
statement: statement ? [statement.subject, statement.predicate, statement.object, statement.graph] : undefined,
statementNT: statement ? this.anonymizeNT(statement) : undefined,
where: updater.contextWhere(context),
set_object: function (obj, callbackFunction) {
var query = this.where
query += 'DELETE DATA { ' + this.statementNT + ' } ;\n'
query += 'INSERT DATA { ' +
// @ts-ignore `this` might refer to the wrong scope. Does this work?
this.anonymize(this.statement[0]) + ' ' +
// @ts-ignore
this.anonymize(this.statement[1]) + ' ' +
// @ts-ignore
this.anonymize(obj) + ' ' + ' . }\n'
updater.fire((this.statement as [Quad_Subject, Quad_Predicate, Quad_Object, Quad_Graph])[3].value, query, callbackFunction)
}
}
}
insert_statement (st: Quad, callbackFunction: CallBackFunction): void {
var st0 = st instanceof Array ? st[0] : st
var query = this.contextWhere(this.statementContext(st0))
if (st instanceof Array) {
var stText = ''
for (let i = 0; i < st.length; i++) stText += st[i] + '\n'
query += 'INSERT DATA { ' + stText + ' }\n'
} else {
query += 'INSERT DATA { ' +
this.anonymize(st.subject) + ' ' +
this.anonymize(st.predicate) + ' ' +
this.anonymize(st.object) + ' ' + ' . }\n'
}
this.fire(st0.graph.value, query, callbackFunction)
}
delete_statement (st: Quad | Quad[], callbackFunction: CallBackFunction): void {
var st0 = st instanceof Array ? st[0] : st
var query = this.contextWhere(this.statementContext(st0))
if (st instanceof Array) {
var stText = ''
for (let i = 0; i < st.length; i++) stText += st[i] + '\n'
query += 'DELETE DATA { ' + stText + ' }\n'
} else {
query += 'DELETE DATA { ' +
this.anonymize(st.subject) + ' ' +
this.anonymize(st.predicate) + ' ' +
this.anonymize(st.object) + ' ' + ' . }\n'
}
this.fire(st0.graph.value, query, callbackFunction)
}
/// //////////////////////
/**
* Requests a now or future action to refresh changes coming downstream
* This is designed to allow the system to re-request the server version,
* when a websocket has pinged to say there are changes.
* If the websocket, by contrast, has sent a patch, then this may not be necessary.
*
* @param doc
* @param action
*/
requestDownstreamAction (doc: NamedNode, action): void {
var control = this.patchControlFor(doc)
if (!control.pendingUpstream) {
action(doc)
} else {
if (control.downstreamAction) {
if ('' + control.downstreamAction !== '' + action) { // Kludge compare
throw new Error("Can't wait for > 1 different downstream actions")
}
} else {
control.downstreamAction = action
}
}
}
/**
* We want to start counting websocket notifications
* to distinguish the ones from others from our own.
*/
clearUpstreamCount (doc: NamedNode): void {
var control = this.patchControlFor(doc)
control.upstreamCount = 0
}
getUpdatesVia (doc: NamedNode): string | null {
var linkHeaders = this.store.fetcher.getHeader(doc, 'updates-via')
if (!linkHeaders || !linkHeaders.length) return null
return linkHeaders[0].trim()
}
addDownstreamChangeListener (doc: NamedNode, listener): void {
var control = this.patchControlFor(doc)
if (!control.downstreamChangeListeners) { control.downstreamChangeListeners = [] }
control.downstreamChangeListeners.push(listener)
this.setRefreshHandler(doc, (doc: NamedNode) => {
this.reloadAndSync(doc)
})
}
reloadAndSync (doc: NamedNode): void {
var control = this.patchControlFor(doc)
var updater = this
if (control.reloading) {
// console.log(' Already reloading - note this load may be out of date')
control.outOfDate = true
return // once only needed @@ Not true, has changed again
}
control.reloading = true
var retryTimeout = 1000 // ms
var tryReload = function () {
// console.log('try reload - timeout = ' + retryTimeout)
updater.reload(updater.store, doc, function (ok, message, response) {
if (ok) {
if (control.downstreamChangeListeners) {
for (let i = 0; i < control.downstreamChangeListeners.length; i++) {
// console.log(' Calling downstream listener ' + i)
control.downstreamChangeListeners[i]()
}
}
control.reloading = false
if (control.outOfDate){
// console.log(' Extra reload because of extra update.')
control.outOfDate = false
tryReload()
}
} else {
control.reloading = false
if ((response as Response).status === 0) {
// console.log('Network error refreshing the data. Retrying in ' +
// retryTimeout / 1000)
control.reloading = true
retryTimeout = retryTimeout * 2
setTimeout(tryReload, retryTimeout)
} else {
// console.log('Error ' + (response as Response).status + 'refreshing the data:' +
// message + '. Stopped' + doc)
}
}
})
}
tryReload()
}
/**
* Sets up websocket to listen on
*
* There is coordination between upstream changes and downstream ones
* so that a reload is not done in the middle of an upstream patch.
* If you use this API then you get called when a change happens, and you
* have to reload the file yourself, and then refresh the UI.
* Alternative is addDownstreamChangeListener(), where you do not
* have to do the reload yourself. Do mot mix them.
*
* kb contains the HTTP metadata from previous operations
*
* @param doc
* @param handler
*
* @returns {boolean}
*/
setRefreshHandler (doc: NamedNode, handler): boolean {
let wssURI = this.getUpdatesVia(doc) // relative
// var kb = this.store
var theHandler = handler
var self = this
var updater = this
var retryTimeout = 1500 // *2 will be 3 Seconds, 6, 12, etc
var retries = 0
if (!wssURI) {
// console.log('Server does not support live updates through Updates-Via :-(')
return false
}
wssURI = uriJoin(wssURI, doc.value)
const validWssURI = wssURI.replace(/^http:/, 'ws:').replace(/^https:/, 'wss:')
// console.log('Web socket URI ' + wssURI)
var openWebsocket = function () {
// From https://github.com/solid/solid-spec#live-updates
var socket
if (typeof WebSocket !== 'undefined') {
socket = new WebSocket(validWssURI)
} else if (typeof window !== 'undefined' && window.WebSocket) {
socket = (window as any).WebSocket(validWssURI)
} else {
// console.log('Live update disabled, as WebSocket not supported by platform :-(')
return
}
socket.onopen = function () {
// console.log(' websocket open')
retryTimeout = 1500 // reset timeout to fast on success
this.send('sub ' + doc.value)
if (retries) {
// console.log('Web socket has been down, better check for any news.')
updater.requestDownstreamAction(doc, theHandler)
}
}
var control = self.patchControlFor(doc)
control.upstreamCount = 0
socket.onerror = function onerror (err: Error) {
// console.log('Error on Websocket:', err)
}
// https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
//
// 1000 CLOSE_NORMAL Normal closure; the connection successfully completed whatever purpose for which it was created.
// 1001 CLOSE_GOING_AWAY The endpoint is going away, either
// because of a server failure or because the browser is navigating away from the page that opened the connection.
// 1002 CLOSE_PROTOCOL_ERROR The endpoint is terminating the connection due to a protocol error.
// 1003 CLOSE_UNSUPPORTED The connection is being terminated because the endpoint
// received data of a type it cannot accept (for example, a text-only endpoint received binary data).
// 1004 Reserved. A meaning might be defined in the future.
// 1005 CLOSE_NO_STATUS Reserved. Indicates that no status code was provided even though one was expected.
// 1006 CLOSE_ABNORMAL Reserved. Used to indicate that a connection was closed abnormally (
//
//
socket.onclose = function (event: CloseEvent) {
// console.log('*** Websocket closed with code ' + event.code +
// ", reason '" + event.reason + "' clean = " + event.wasClean)
retryTimeout *= 2
retries += 1
// console.log('Retrying in ' + retryTimeout + 'ms') // (ask user?)
setTimeout(function () {
// console.log('Trying websocket again')
openWebsocket()
}, retryTimeout)
}
socket.onmessage = function (msg: MessageEvent) {
if (msg.data && msg.data.slice(0, 3) === 'pub') {
if ('upstreamCount' in control) {
control.upstreamCount -= 1
if (control.upstreamCount >= 0) {
// console.log('just an echo: ' + control.upstreamCount)
return // Just an echo
}
}
// console.log('Assume a real downstream change: ' + control.upstreamCount + ' -> 0')
control.upstreamCount = 0
self.requestDownstreamAction(doc, theHandler)
}
}
} // openWebsocket
openWebsocket()
return true
}
/**
* This high-level function updates the local store iff the web is changed successfully.
* Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause).
* The `why` property of each statement must be the give the web document to be updated.
* The statements to be deleted and inserted may span more than one web document.
* @param deletions - Statement or statements to be deleted.
* @param insertions - Statement or statements to be inserted.
* @returns a promise
*/
updateMany(
deletions: ReadonlyArray<Statement>,
insertions: ReadonlyArray<Statement> = []
): Promise<void[]> {
const docs = deletions.concat(insertions).map(st => st.why)
const thisUpdater = this
const uniqueDocs: Array<NamedNode> = []
docs.forEach(doc => {
if (!uniqueDocs.find(uniqueDoc => uniqueDoc.equals(doc))) uniqueDocs.push(doc as NamedNode)
})
const updates = uniqueDocs.map(doc =>
thisUpdater.update(deletions.filter(st => st.why.equals(doc)),
insertions.filter(st => st.why.equals(doc))))
if (updates.length > 1) {
console.log(`@@ updateMany to ${updates.length}: ${uniqueDocs}`)
}
return Promise.all(updates)
}
/**
* This high-level function updates the local store iff the web is changed successfully.
* Deletions, insertions may be undefined or single statements or lists or formulae (may contain bnodes which can be indirectly identified by a where clause).
* The `why` property of each statement must be the same and give the web document to be updated.
* @param deletions - Statement or statements to be deleted.
* @param insertions - Statement or statements to be inserted.
* @param callback - called as callbackFunction(uri, success, errorbody)
* OR returns a promise
*/
update(
deletions: ReadonlyArray<Statement>,
insertions: ReadonlyArray<Statement>,
callback?: (
uri: string | undefined | null,
success: boolean,
errorBody?: string,
response?: Response | Error
) => void,
secondTry?: boolean
): void | Promise<void> {
if (!callback) {
var thisUpdater = this
return new Promise(function (resolve, reject) { // Promise version
thisUpdater.update(deletions, insertions, function (uri, ok, errorBody) {
if (!ok) {
reject(new Error(errorBody))
} else {
resolve()
}
}) // callbackFunction
}) // promise
} // if
try {
var kb = this.store
var ds = !deletions ? []
: isStore(deletions) ? deletions.statements
: deletions instanceof Array ? deletions : [ deletions ]
var is = !insertions ? []
: isStore(insertions) ? insertions.statements
: insertions instanceof Array ? insertions : [ insertions ]
if (!(ds instanceof Array)) {
throw new Error('Type Error ' + (typeof ds) + ': ' + ds)
}
if (!(is instanceof Array)) {
throw new Error('Type Error ' + (typeof is) + ': ' + is)
}
if (ds.length === 0 && is.length === 0) {
return callback(null, true) // success -- nothing needed to be done.
}
var doc = ds.length ? ds[0].graph : is[0].graph
if (!doc) {
let message = 'Error patching: statement does not specify which document to patch:' + ds[0] + ', ' + is[0]
// console.log(message)
throw new Error(message)
}
var control = this.patchControlFor(doc)
var startTime = Date.now()
var props = ['subject', 'predicate', 'object', 'why']
var verbs = ['insert', 'delete']
var clauses = { 'delete': ds, 'insert': is }
verbs.map(function (verb) {
clauses[verb].map(function (st: Quad) {
if (!doc.equals(st.graph)) {
throw new Error('update: destination ' + doc +
' inconsistent with delete quad ' + st.graph)
}
props.map(function (prop) {
if (typeof st[prop] === 'undefined') {
throw new Error('update: undefined ' + prop + ' of statement.')
}
})
})
})
var protocol = this.editable(doc.value, kb)
if (protocol === false) {
throw new Error('Update: Can\'t make changes in uneditable ' + doc)
}
if (protocol === undefined) { // Not enough metadata
if (secondTry) {
throw new Error('Update: Loaded ' + doc + "but stil can't figure out what editing protcol it supports.")
}
// console.log(`Update: have not loaded ${doc} before: loading now...`);
(this.store.fetcher.load(doc) as Promise<Response>).then(response => {
this.update(deletions, insertions, callback, true)
}, err => {
if (err.response.status === 404) { // nonexistent files are fine
this.update(deletions, insertions, callback, true)
} else {
throw new Error(`Update: Can't get updatability status ${doc} before patching: ${err}`)
}
})
return
} else if ((protocol as string).indexOf('SPARQL') >= 0) {
var bnodes: BlankNode[] = []
if (ds.length) bnodes = this.statementArrayBnodes(ds)
if (is.length) bnodes = bnodes.concat(this.statementArrayBnodes(is))
var context = this.bnodeContext(bnodes, doc)
var whereClause = this.contextWhere(context)
var query = ''
if (whereClause.length) { // Is there a WHERE clause?
if (ds.length) {
query += 'DELETE { '
for (let i = 0; i < ds.length; i++) {
query += this.anonymizeNT(ds[i]) + '\n'
}
query += ' }\n'
}
if (is.length) {
query += 'INSERT { '
for (let i = 0; i < is.length; i++) {
query += this.anonymizeNT(is[i]) + '\n'
}
query += ' }\n'
}
query += whereClause
} else { // no where clause
if (ds.length) {
query += 'DELETE DATA { '
for (let i = 0; i < ds.length; i++) {
query += this.anonymizeNT(ds[i]) + '\n'
}
query += ' } \n'
}
if (is.length) {
if (ds.length) query += ' ; '
query += 'INSERT DATA { '
for (let i = 0; i < is.length; i++) {
query += this.anonymizeNT(is[i]) + '\n'
}
query += ' }\n'
}
}
// Track pending upstream patches until they have finished their callbackFunction
control.pendingUpstream = control.pendingUpstream ? control.pendingUpstream + 1 : 1
if ('upstreamCount' in control) {
control.upstreamCount += 1 // count changes we originated ourselves
// console.log('upstream count up to : ' + control.upstreamCount)
}
this.fire(doc.value, query, (uri, success, body, response) => {
(response as any).elapsedTimeMs = Date.now() - startTime
console.log(' UpdateManager: Return ' +
(success ? 'success ' : 'FAILURE ') + (response as Response).status +
' elapsed ' + (response as any).elapsedTimeMs + 'ms')
if (success) {
try {
kb.remove(ds)
} catch (e) {
success = false
body = 'Remote Ok BUT error deleting ' + ds.length + ' from store!!! ' + e
} // Add in any case -- help recover from weirdness??
for (let i = 0; i < is.length; i++) {
kb.add(is[i].subject, is[i].predicate, is[i].object, doc)
}
}
callback(uri, success, body, response)
control.pendingUpstream -= 1
// When upstream patches have been sent, reload state if downstream waiting
if (control.pendingUpstream === 0 && control.downstreamAction) {
var downstreamAction = control.downstreamAction
delete control.downstreamAction
// console.log('delayed downstream action:')
downstreamAction(doc)
}
})
} else if ((protocol as string).indexOf('DAV') >= 0) {
this.updateDav(doc, ds, is, callback)
} else {
if ((protocol as string).indexOf('LOCALFILE') >= 0) {
try {
this.updateLocalFile(doc, ds, is, callback)
} catch (e) {
callback(doc.value, false,
'Exception trying to write back file <' + doc.value + '>\n'
// + tabulator.Util.stackString(e))
)
}
} else {
throw new Error("Unhandled edit method: '" + protocol + "' for " + doc)
}
}
} catch (e) {
callback(undefined, false, 'Exception in update: ' + e + '\n' +
Util.stackString(e))
}
}
updateDav (
doc: Quad_Subject,
ds,
is,
callbackFunction
): null | Promise<void> {
let kb = this.store
// The code below is derived from Kenny's UpdateCenter.js
var request = kb.any(doc, this.ns.link('request'))
if (!request) {
throw new Error('No record of our HTTP GET request for document: ' +
doc)
} // should not happen
var response = kb.any(request as NamedNode, this.ns.link('response')) as Quad_Subject
if (!response) {
return null // throw "No record HTTP GET response for document: "+doc
}
var contentType = (kb.the(response, this.ns.httph('content-type'))as Term).value
// prepare contents of revised document
let newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice() // copy!
for (let i = 0; i < ds.length; i++) {
Util.RDFArrayRemove(newSts, ds[i])
}
for (let i = 0; i < is.length; i++) {
newSts.push(is[i])
}
const documentString = this.serialize(doc.value, newSts, contentType)
// Write the new version back
var candidateTarget = kb.the(response, this.ns.httph('content-location'))
var targetURI
if (candidateTarget) {
targetURI = uriJoin(candidateTarget.value, targetURI)
}
let options = {
contentType,
noMeta: true,
body: documentString
}
return kb.fetcher.webOperation('PUT', targetURI, options)
.then(response => {
if (!response.ok) {
throw new Error(response.error)
}
for (let i = 0; i < ds.length; i++) {
kb.remove(ds[i])
}
for (let i = 0; i < is.length; i++) {
kb.add(is[i].subject, is[i].predicate, is[i].object, doc)
}
callbackFunction(doc.value, response.ok, response.responseText, response)
})
.catch(err => {
callbackFunction(doc.value, false, err.message, err)
})
}
/**
* Likely deprecated, since this lib no longer deals with browser extension
*
* @param doc
* @param ds
* @param is
* @param callbackFunction
*/
updateLocalFile (doc: NamedNode, ds, is, callbackFunction): void {
const kb = this.store
// console.log('Writing back to local file\n')
// prepare contents of revised document
let newSts = kb.statementsMatching(undefined, undefined, undefined, doc).slice() // copy!
for (let i = 0; i < ds.length; i++) {
Util.RDFArrayRemove(newSts, ds[ i ])
}
for (let i = 0; i < is.length; i++) {
newSts.push(is[ i ])
}
// serialize to the appropriate format
var dot = doc.value.lastIndexOf('.')
if (dot < 1) {
throw new Error('Rewriting file: No filename extension: ' + doc.value)
}
var ext = doc.value.slice(dot + 1)
let contentType = Fetcher.CONTENT_TYPE_BY_EXT[ ext ]
if (!contentType) {
throw new Error('File extension .' + ext + ' not supported for data write')
}
const documentString = this.serialize(doc.value, newSts, contentType)
kb.fetcher.webOperation('PUT',doc.value,{
"body" : documentString,
contentType : contentType,
}).then( (response)=>{
if(!response.ok) return callbackFunction(doc.value,false,response.error)
for (let i = 0; i < ds.length; i++) {
kb.remove(ds[i]);
}
for (let i = 0; i < is.length; i++) {
kb.add(is[i].subject, is[i].predicate, is[i].object, doc);
}
callbackFunction(doc.value, true, '') // success!
})
}
/**
* @throws {Error} On unsupported content type
*
* @returns {string}
*/
serialize (uri: string, data: string | Quad[], contentType: string): string {
const kb = this.store
let documentString
if (typeof data === 'string') {
return data
}
// serialize to the appropriate format
var sz = Serializer(kb)
sz.suggestNamespaces(kb.namespaces)
sz.setBase(uri)
switch (contentType) {
case 'text/xml':
case 'application/rdf+xml':
documentString = sz.statementsToXML(data)
break
case 'text/n3':
case 'text/turtle':
case 'application/x-turtle': // Legacy
case 'application/n3': // Legacy
documentString = sz.statementsToN3(data)
break
default:
throw new Error('Content-type ' + contentType +
' not supported for data serialization')
}
return documentString
}
/**
* This is suitable for an initial creation of a document.
*/
put(
doc: RDFlibNamedNode,
data: string | Quad[],
contentType: string,
callback: (uri: string, ok: boolean, errorMessage?: string, response?: unknown) => void,
): Promise<void> {
const kb = this.store
let documentString: string
return Promise.resolve()
.then(() => {
documentString = this.serialize(doc.value, data, contentType)
return kb.fetcher
.webOperation('PUT', doc.value, { contentType, body: documentString })
})
.then(response => {
if (!response.ok) {
return callback(doc.value, response.ok, response.error, response)
}
delete kb.fetcher.nonexistent[doc.value]
delete kb.fetcher.requested[doc.value] // @@ could this mess with the requested state machine? if a fetch is in progress
if (typeof data !== 'string') {
data.map((st) => {
kb.addStatement(st)
})
}
callback(doc.value, response.ok, '', response)
})
.catch(err => {
callback(doc.value, false, err.message)
})
}
/**
* Reloads a document.
*
* Fast and cheap, no metadata. Measure times for the document.
* Load it provisionally.
* Don't delete the statements before the load, or it will leave a broken
* document in the meantime.
*
* @param kb
* @param doc {RDFlibNamedNode}
* @param callbackFunction
*/
reload (
kb: IndexedFormula,
doc: docReloadType,
callbackFunction: (ok: boolean, message?: string, response?: Error | Response) => {} | void
): void {
var startTime = Date.now()
// force sets no-cache and
const options = {
force: true,
noMeta: true,
clearPreviousData: true,
};
(kb as any).fetcher.nowOrWhenFetched(doc.value, options, function (ok: boolean, body: Body, response: Response) {
if (!ok) {
// console.log(' ERROR reloading data: ' + body)
callbackFunction(false, 'Error reloading data: ' + body, response)
//@ts-ignore Where does onErrorWasCalled come from?
} else if (response.onErrorWasCalled || response.status !== 200) {
// console.log(' Non-HTTP error reloading data! onErrorWasCalled=' +
//@ts-ignore Where does onErrorWasCalled come from?
// response.onErrorWasCalled + ' status: ' + response.status)
callbackFunction(false, 'Non-HTTP error reloading data: ' + body, response)
} else {
var elapsedTimeMs = Date.now() - startTime
if (!doc.reloadTimeTotal) doc.reloadTimeTotal = 0
if (!doc.reloadTimeCount) doc.reloadTimeCount = 0
doc.reloadTimeTotal += elapsedTimeMs
doc.reloadTimeCount += 1
// console.log(' Fetch took ' + elapsedTimeMs + 'ms, av. of ' +
// doc.reloadTimeCount + ' = ' +
// (doc.reloadTimeTotal / doc.reloadTimeCount) + 'ms.')
callbackFunction(true)
}
})
}
}
interface docReloadType extends NamedNode {
reloadTimeCount?: number
reloadTimeTotal?: number
} | the_stack |
import CancellationToken from "cancellationtoken";
import caught = require("caught");
import { EventEmitter } from "events";
import { Channel, ChannelClass } from "./Channel";
import { ChannelOptions } from "./ChannelOptions";
import { ControlCode } from "./ControlCode";
import { Deferred } from "./Deferred";
import { FrameHeader } from "./FrameHeader";
import { IChannelOfferEventArgs } from "./IChannelOfferEventArgs";
import { IDisposableObservable } from "./IDisposableObservable";
import "./MultiplexingStreamOptions";
import { MultiplexingStreamOptions } from "./MultiplexingStreamOptions";
import { removeFromQueue, throwIfDisposed } from "./Utilities";
import {
MultiplexingStreamFormatter,
MultiplexingStreamV1Formatter,
MultiplexingStreamV2Formatter,
MultiplexingStreamV3Formatter,
} from "./MultiplexingStreamFormatters";
import { OfferParameters } from "./OfferParameters";
import { Semaphore } from 'await-semaphore';
import { QualifiedChannelId, ChannelSource } from "./QualifiedChannelId";
export abstract class MultiplexingStream implements IDisposableObservable {
/**
* The maximum length of a frame's payload.
*/
static readonly framePayloadMaxLength = 20 * 1024;
private static readonly recommendedDefaultChannelReceivingWindowSize = 5 * MultiplexingStream.framePayloadMaxLength;
/** The default window size used for new channels that do not specify a value for ChannelOptions.ChannelReceivingWindowSize. */
readonly defaultChannelReceivingWindowSize: number;
protected readonly formatter: MultiplexingStreamFormatter;
protected get disposalToken() {
return this.disposalTokenSource.token;
}
/**
* Gets a promise that is resolved or rejected based on how this stream is disposed or fails.
*/
public get completion(): Promise<void> {
return this._completionSource.promise;
}
/**
* Gets a value indicating whether this instance has been disposed.
*/
public get isDisposed(): boolean {
return this.disposalTokenSource.token.isCancelled;
}
/**
* Initializes a new instance of the `MultiplexingStream` class.
* @param stream The duplex stream to read and write to.
* Use `FullDuplexStream.Splice` if you have distinct input/output streams.
* @param options Options to customize the behavior of the stream.
* @param cancellationToken A token whose cancellation aborts the handshake with the remote end.
* @returns The multiplexing stream, once the handshake is complete.
*/
public static async CreateAsync(
stream: NodeJS.ReadWriteStream,
options?: MultiplexingStreamOptions,
cancellationToken: CancellationToken = CancellationToken.CONTINUE): Promise<MultiplexingStream> {
if (!stream) {
throw new Error("stream must be specified.");
}
options = options || {};
options.protocolMajorVersion = options.protocolMajorVersion || 1;
options.defaultChannelReceivingWindowSize = options.defaultChannelReceivingWindowSize || MultiplexingStream.recommendedDefaultChannelReceivingWindowSize;
if (options.protocolMajorVersion < 3 && options.seededChannels && options.seededChannels.length > 0) {
throw new Error("Seeded channels require v3 of the protocol at least.");
}
// Send the protocol magic number, and a random 16-byte number to establish even/odd assignments.
const formatter: MultiplexingStreamFormatter | undefined =
options.protocolMajorVersion === 1 ? new MultiplexingStreamV1Formatter(stream) :
options.protocolMajorVersion === 2 ? new MultiplexingStreamV2Formatter(stream) :
options.protocolMajorVersion === 3 ? new MultiplexingStreamV3Formatter(stream) :
undefined;
if (!formatter) {
throw new Error(`Protocol major version ${options.protocolMajorVersion} is not supported.`);
}
const writeHandshakeData = await formatter.writeHandshakeAsync();
const handshakeResult = await formatter.readHandshakeAsync(writeHandshakeData, cancellationToken);
formatter.isOdd = handshakeResult.isOdd;
return new MultiplexingStreamClass(stream, handshakeResult.isOdd, options);
}
/**
* The options to use for channels we create in response to incoming offers.
* @description Whatever these settings are, they can be replaced when the channel is accepted.
*/
protected static readonly defaultChannelOptions: ChannelOptions = {};
/**
* The encoding used for characters in control frames.
*/
static readonly ControlFrameEncoding = "utf-8";
protected readonly _completionSource = new Deferred<void>();
/**
* A dictionary of channels that were seeded, keyed by their ID.
*/
protected readonly seededOpenChannels: { [id: number]: ChannelClass } = {};
/**
* A dictionary of channels that were offered locally, keyed by their ID.
*/
protected readonly locallyOfferedOpenChannels: { [id: number]: ChannelClass } = {};
/**
* A dictionary of channels that were offered remotely, keyed by their ID.
*/
protected readonly remotelyOfferedOpenChannels: { [id: number]: ChannelClass } = {};
/**
* The last number assigned to a channel.
* Each use of this should increment by two if isOdd is defined.
* It should never exceed uint32.MaxValue
*/
protected abstract lastOfferedChannelId: number;
/**
* A map of channel names to queues of channels waiting for local acceptance.
*/
protected readonly channelsOfferedByThemByName: { [name: string]: ChannelClass[] } = {};
/**
* A map of channel names to queues of Deferred<Channel> from waiting accepters.
*/
protected readonly acceptingChannels: { [name: string]: Deferred<ChannelClass>[] } = {};
/** The major version of the protocol being used for this connection. */
protected readonly protocolMajorVersion: number;
private readonly eventEmitter = new EventEmitter();
private disposalTokenSource = CancellationToken.create();
protected constructor(stream: NodeJS.ReadWriteStream, private readonly isOdd: boolean | undefined, options: MultiplexingStreamOptions) {
this.defaultChannelReceivingWindowSize = options.defaultChannelReceivingWindowSize ?? MultiplexingStream.recommendedDefaultChannelReceivingWindowSize;
this.protocolMajorVersion = options.protocolMajorVersion ?? 1;
const formatter: MultiplexingStreamFormatter | undefined =
options.protocolMajorVersion === 1 ? new MultiplexingStreamV1Formatter(stream) :
options.protocolMajorVersion === 2 ? new MultiplexingStreamV2Formatter(stream) :
options.protocolMajorVersion === 3 ? new MultiplexingStreamV3Formatter(stream) :
undefined;
if (formatter === undefined) {
throw new Error(`Unsupported major protocol version: ${options.protocolMajorVersion}`);
}
formatter.isOdd = isOdd;
this.formatter = formatter;
if (options.seededChannels) {
for (let i = 0; i < options.seededChannels.length; i++) {
const channelOptions = options.seededChannels[i];
const id = { id: i, source: ChannelSource.Seeded };
this.setOpenChannel(new ChannelClass(this as unknown as MultiplexingStreamClass, id, { name: '', remoteWindowSize: channelOptions.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize }));
}
}
}
/**
* Creates an anonymous channel that may be accepted by <see cref="AcceptChannel(int, ChannelOptions)"/>.
* Its existance must be communicated by other means (typically another, existing channel) to encourage acceptance.
* @param options A set of options that describe local treatment of this channel.
* @returns The anonymous channel.
* @description Note that while the channel is created immediately, any local write to that channel will be
* buffered locally until the remote party accepts the channel.
*/
public createChannel(options?: ChannelOptions): Channel {
const offerParameters: OfferParameters = {
name: "",
remoteWindowSize: options?.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize
};
const payload = this.formatter.serializeOfferParameters(offerParameters);
const channel = new ChannelClass(
this as any as MultiplexingStreamClass,
{ id: this.getUnusedChannelId(), source: ChannelSource.Local },
offerParameters);
this.setOpenChannel(channel);
this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.Offer, channel.qualifiedId), payload, this.disposalToken));
return channel;
}
/**
* Accepts a channel with a specific ID.
* @param id The id of the channel to accept.
* @param options A set of options that describe local treatment of this channel.
* @description This method can be used to accept anonymous channels created with <see cref="CreateChannel"/>.
* Unlike <see cref="AcceptChannelAsync(string, ChannelOptions, CancellationToken)"/> which will await
* for a channel offer if a matching one has not been made yet, this method only accepts an offer
* for a channel that has already been made.
*/
public acceptChannel(id: number, options?: ChannelOptions): Channel {
const channel = this.remotelyOfferedOpenChannels[id] || this.seededOpenChannels[id];
if (!channel) {
throw new Error("No channel with ID " + id);
}
this.removeChannelFromOfferedQueue(channel);
this.acceptChannelOrThrow(channel, options);
return channel;
}
/**
* Rejects an offer for the channel with a specified ID.
* @param id The ID of the channel whose offer should be rejected.
*/
public rejectChannel(id: number) {
const channel = this.remotelyOfferedOpenChannels[id];
if (channel) {
removeFromQueue(channel, this.channelsOfferedByThemByName[channel.name]);
} else {
throw new Error("No channel with that ID found.");
}
// Rejecting a channel rejects a couple promises that we don't want the caller to have to observe
// separately since they are explicitly stating they want to take this action now.
caught(channel.acceptance);
caught(channel.completion);
channel.dispose();
}
/**
* Offers a new, named channel to the remote party so they may accept it with
* [acceptChannelAsync](#acceptChannelAsync).
* @param name A name for the channel, which must be accepted on the remote end to complete creation.
* It need not be unique, and may be empty but must not be null.
* Any characters are allowed, and max length is determined by the maximum frame payload (based on UTF-8 encoding).
* @param options A set of options that describe local treatment of this channel.
* @param cancellationToken A cancellation token. Do NOT let this be a long-lived token
* or a memory leak will result since we add continuations to its promise.
* @returns A task that completes with the `Channel` if the offer is accepted on the remote end
* or faults with `MultiplexingProtocolException` if the remote end rejects the channel.
*/
public async offerChannelAsync(
name: string,
options?: ChannelOptions,
cancellationToken: CancellationToken = CancellationToken.CONTINUE): Promise<Channel> {
if (name == null) {
throw new Error("Name must be specified (but may be empty).");
}
cancellationToken.throwIfCancelled();
throwIfDisposed(this);
const offerParameters: OfferParameters = {
name,
remoteWindowSize: options?.channelReceivingWindowSize ?? this.defaultChannelReceivingWindowSize,
};
const payload = this.formatter.serializeOfferParameters(offerParameters);
const channel = new ChannelClass(
this as any as MultiplexingStreamClass,
{ id: this.getUnusedChannelId(), source: ChannelSource.Local },
offerParameters);
this.setOpenChannel(channel);
const header = new FrameHeader(ControlCode.Offer, channel.qualifiedId);
const unsubscribeFromCT = cancellationToken.onCancelled((reason) => this.offerChannelCanceled(channel, reason));
try {
// We *will* recognize rejection of this promise. But just in case sendFrameAsync completes synchronously,
// we want to signify that we *will* catch it first to avoid node.js emitting warnings or crashing.
caught(channel.acceptance);
await this.sendFrameAsync(header, payload, cancellationToken);
await channel.acceptance;
return channel;
} finally {
unsubscribeFromCT();
}
}
/**
* Accepts a channel that the remote end has attempted or may attempt to create.
* @param name The name of the channel to accept.
* @param options A set of options that describe local treatment of this channel.
* @param cancellationToken A token to indicate lost interest in accepting the channel.
* Do NOT let this be a long-lived token
* or a memory leak will result since we add continuations to its promise.
* @returns The `Channel`, after its offer has been received from the remote party and accepted.
* @description If multiple offers exist with the specified `name`, the first one received will be accepted.
*/
public async acceptChannelAsync(
name: string,
options?: ChannelOptions,
cancellationToken: CancellationToken = CancellationToken.CONTINUE): Promise<Channel> {
if (name == null) {
throw new Error("Name must be specified (but may be empty).");
}
cancellationToken.throwIfCancelled();
throwIfDisposed(this);
let channel: ChannelClass | undefined;
let pendingAcceptChannel: Deferred<ChannelClass>;
const channelsOfferedByThem = this.channelsOfferedByThemByName[name] as ChannelClass[];
if (channelsOfferedByThem) {
while (channel === undefined && channelsOfferedByThem.length > 0) {
channel = channelsOfferedByThem.shift()!;
if (channel.isAccepted || channel.isRejectedOrCanceled) {
channel = undefined;
continue;
}
}
}
if (channel === undefined) {
let acceptingChannels = this.acceptingChannels[name];
if (!acceptingChannels) {
this.acceptingChannels[name] = acceptingChannels = [];
}
pendingAcceptChannel = new Deferred<ChannelClass>(options);
acceptingChannels.push(pendingAcceptChannel);
}
if (channel !== undefined) {
this.acceptChannelOrThrow(channel, options);
return channel;
} else {
const unsubscribeFromCT = cancellationToken.onCancelled(
(reason) => this.acceptChannelCanceled(pendingAcceptChannel, name, reason));
try {
return await pendingAcceptChannel!.promise;
} finally {
unsubscribeFromCT();
}
}
}
/**
* Disposes the stream.
*/
public dispose() {
this.disposalTokenSource.cancel();
this._completionSource.resolve();
this.formatter.end();
[this.locallyOfferedOpenChannels, this.remotelyOfferedOpenChannels].forEach(cb => {
for (const channelId in cb) {
if (cb.hasOwnProperty(channelId)) {
const channel = cb[channelId];
// Acceptance gets rejected when a channel is disposed.
// Avoid a node.js crash or test failure for unobserved channels (e.g. offers for channels from the other party that no one cared to receive on this side).
caught(channel.acceptance);
channel.dispose();
}
}
});
}
public on(event: "channelOffered", listener: (args: IChannelOfferEventArgs) => void) {
this.eventEmitter.on(event, listener);
}
public off(event: "channelOffered", listener: (args: IChannelOfferEventArgs) => void) {
this.eventEmitter.off(event, listener);
}
public once(event: "channelOffered", listener: (args: IChannelOfferEventArgs) => void) {
this.eventEmitter.once(event, listener);
}
protected raiseChannelOffered(id: number, name: string, isAccepted: boolean) {
const args: IChannelOfferEventArgs = {
id,
isAccepted,
name,
};
try {
this.eventEmitter.emit("channelOffered", args);
} catch (err) {
this._completionSource.reject(err);
}
}
protected abstract sendFrameAsync(
header: FrameHeader,
payload: Buffer,
cancellationToken: CancellationToken): Promise<void>;
protected abstract sendFrame(code: ControlCode, channelId: QualifiedChannelId): Promise<void>;
protected acceptChannelOrThrow(channel: ChannelClass, options?: ChannelOptions) {
if (channel.tryAcceptOffer(options)) {
const acceptanceParameters = {
remoteWindowSize: options?.channelReceivingWindowSize ?? channel.localWindowSize ?? this.defaultChannelReceivingWindowSize,
};
if (acceptanceParameters.remoteWindowSize < this.defaultChannelReceivingWindowSize) {
acceptanceParameters.remoteWindowSize = this.defaultChannelReceivingWindowSize;
}
if (channel.qualifiedId.source !== ChannelSource.Seeded) {
const payload = this.formatter.serializeAcceptanceParameters(acceptanceParameters);
this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.OfferAccepted, channel.qualifiedId), payload, this.disposalToken));
}
} else if (channel.isAccepted) {
throw new Error("Channel is already accepted.");
} else if (channel.isRejectedOrCanceled) {
throw new Error("Channel is no longer available for acceptance.");
} else {
throw new Error("Channel could not be accepted.");
}
}
/**
* Disposes this instance if the specified promise is rejected.
* @param promise The promise to check for failures.
*/
protected async rejectOnFailure<T>(promise: Promise<T>) {
try {
await promise;
} catch (err) {
this._completionSource.reject(err);
}
}
protected removeChannelFromOfferedQueue(channel: ChannelClass) {
if (channel.name) {
removeFromQueue(channel, this.channelsOfferedByThemByName[channel.name]);
}
}
protected getOpenChannel(qualifiedId: QualifiedChannelId): ChannelClass | undefined {
return this.getChannelCollection(qualifiedId.source)[qualifiedId.id];
}
protected setOpenChannel(channel: ChannelClass) {
this.getChannelCollection(channel.qualifiedId.source)[channel.qualifiedId.id] = channel;
}
protected deleteOpenChannel(qualifiedId: QualifiedChannelId) {
delete this.getChannelCollection(qualifiedId.source)[qualifiedId.id];
}
private getChannelCollection(source: ChannelSource): { [id: number]: ChannelClass } {
switch (source) {
case ChannelSource.Local:
return this.locallyOfferedOpenChannels;
case ChannelSource.Remote:
return this.remotelyOfferedOpenChannels;
case ChannelSource.Seeded:
return this.seededOpenChannels;
}
}
/**
* Cancels a prior call to acceptChannelAsync
* @param channel The promise of a channel to be canceled.
* @param name The name of the channel the caller was accepting.
* @param reason The reason for cancellation.
*/
private acceptChannelCanceled(channel: Deferred<ChannelClass>, name: string, reason: any) {
if (channel.reject(new CancellationToken.CancellationError(reason))) {
removeFromQueue(channel, this.acceptingChannels[name]);
}
}
/**
* Responds to cancellation of a prior call to offerChannelAsync.
* @param channel The channel previously offered.
*/
private offerChannelCanceled(channel: ChannelClass, reason: any) {
channel.tryCancelOffer(reason);
}
/**
* Gets a unique number that can be used to represent a channel.
* @description The channel numbers increase by two in order to maintain odd or even numbers,
* since each party is allowed to create only one or the other.
*/
private getUnusedChannelId() {
return this.lastOfferedChannelId += this.isOdd !== undefined ? 2 : 1;
}
}
// tslint:disable-next-line:max-classes-per-file
export class MultiplexingStreamClass extends MultiplexingStream {
protected lastOfferedChannelId: number;
private readonly sendingSemaphore = new Semaphore(1);
constructor(stream: NodeJS.ReadWriteStream, isOdd: boolean | undefined, options: MultiplexingStreamOptions) {
super(stream, isOdd, options);
this.lastOfferedChannelId = isOdd ? -1 : 0; // the first channel created should be 1 or 2
this.lastOfferedChannelId += options.seededChannels?.length ?? 0;
// Initiate reading from the transport stream. This will not end until the stream does, or we're disposed.
// If reading the stream fails, we'll dispose ourselves.
this.readFromStream(this.disposalToken).catch((err) => this._completionSource.reject(err));
}
get backpressureSupportEnabled(): boolean {
return this.protocolMajorVersion > 1;
}
public async sendFrameAsync(
header: FrameHeader,
payload?: Buffer,
cancellationToken: CancellationToken = CancellationToken.CONTINUE): Promise<void> {
if (!header) {
throw new Error("Header is required.");
}
await this.sendingSemaphore.use(async () => {
cancellationToken.throwIfCancelled();
throwIfDisposed(this);
await this.formatter.writeFrameAsync(header, payload);
});
}
/**
* Transmits a frame over the stream.
* @param code The op code for the channel.
* @param channelId The ID of the channel to receive the frame.
* @description The promise returned from this function is always resolved (not rejected)
* since it is anticipated that callers may not be awaiting its result.
*/
public async sendFrame(code: ControlCode, channelId: QualifiedChannelId) {
try {
if (this._completionSource.isCompleted) {
// Any frames that come in after we're done are most likely frames just informing that channels are
// being terminated, which we do not need to communicate since the connection going down implies that.
return;
}
const header = new FrameHeader(code, channelId);
await this.sendFrameAsync(header);
} catch (error) {
// We mustn't throw back to our caller. So report the failure by disposing with failure.
this._completionSource.reject(error);
}
}
public onChannelWritingCompleted(channel: ChannelClass) {
// Only inform the remote side if this channel has not already been terminated.
if (!channel.isDisposed && this.getOpenChannel(channel.qualifiedId)) {
this.sendFrame(ControlCode.ContentWritingCompleted, channel.qualifiedId);
}
}
public onChannelDisposed(channel: ChannelClass) {
if (!this._completionSource.isCompleted) {
this.sendFrame(ControlCode.ChannelTerminated, channel.qualifiedId);
}
}
public localContentExamined(channel: ChannelClass, bytesConsumed: number) {
const payload = this.formatter.serializeContentProcessed(bytesConsumed);
this.rejectOnFailure(this.sendFrameAsync(new FrameHeader(ControlCode.ContentProcessed, channel.qualifiedId), payload));
}
private async readFromStream(cancellationToken: CancellationToken) {
while (!this.isDisposed) {
const frame = await this.formatter.readFrameAsync(cancellationToken);
if (frame === null) {
break;
}
frame.header.flipChannelPerspective();
switch (frame.header.code) {
case ControlCode.Offer:
this.onOffer(frame.header.requiredChannel, frame.payload);
break;
case ControlCode.OfferAccepted:
this.onOfferAccepted(frame.header.requiredChannel, frame.payload);
break;
case ControlCode.Content:
this.onContent(frame.header.requiredChannel, frame.payload);
break;
case ControlCode.ContentProcessed:
this.onContentProcessed(frame.header.requiredChannel, frame.payload);
break;
case ControlCode.ContentWritingCompleted:
this.onContentWritingCompleted(frame.header.requiredChannel);
break;
case ControlCode.ChannelTerminated:
this.onChannelTerminated(frame.header.requiredChannel);
break;
default:
break;
}
}
this.dispose();
}
private onOffer(channelId: QualifiedChannelId, payload: Buffer) {
const offerParameters = this.formatter.deserializeOfferParameters(payload);
const channel = new ChannelClass(this, channelId, offerParameters);
let acceptingChannelAlreadyPresent = false;
let options: ChannelOptions | undefined;
let acceptingChannels: Deferred<ChannelClass>[];
if ((acceptingChannels = this.acceptingChannels[offerParameters.name]) !== undefined) {
while (acceptingChannels.length > 0) {
const candidate = acceptingChannels.shift()!;
if (candidate.resolve(channel)) {
acceptingChannelAlreadyPresent = true;
options = candidate.state as ChannelOptions;
break;
}
}
}
if (!acceptingChannelAlreadyPresent) {
if (offerParameters.name != null) {
let offeredChannels: Channel[];
if (!(offeredChannels = this.channelsOfferedByThemByName[offerParameters.name])) {
this.channelsOfferedByThemByName[offerParameters.name] = offeredChannels = [];
}
offeredChannels.push(channel);
}
}
this.setOpenChannel(channel);
if (acceptingChannelAlreadyPresent) {
this.acceptChannelOrThrow(channel, options);
}
this.raiseChannelOffered(channel.id, channel.name, acceptingChannelAlreadyPresent);
}
private onOfferAccepted(channelId: QualifiedChannelId, payload: Buffer) {
if (channelId.source !== ChannelSource.Local) {
throw new Error("Remote party tried to accept a channel that they offered.");
}
const acceptanceParameter = this.formatter.deserializeAcceptanceParameters(payload);
const channel = this.getOpenChannel(channelId);
if (!channel) {
throw new Error(`Unexpected channel created with ID ${QualifiedChannelId.toString(channelId)}`);
}
if (!channel.onAccepted(acceptanceParameter)) {
// This may be an acceptance of a channel that we canceled an offer for, and a race condition
// led to our cancellation notification crossing in transit with their acceptance notification.
// In this case, do nothing since we already sent a channel termination message, and the remote side
// should notice it soon.
}
}
private onContent(channelId: QualifiedChannelId, payload: Buffer) {
const channel = this.getOpenChannel(channelId);
if (!channel) {
throw new Error(`No channel with id ${channelId} found.`);
}
channel.onContent(payload);
}
private onContentProcessed(channelId: QualifiedChannelId, payload: Buffer) {
const channel = this.getOpenChannel(channelId);
if (!channel) {
throw new Error(`No channel with id ${channelId} found.`);
}
const bytesProcessed = this.formatter.deserializeContentProcessed(payload);
channel.onContentProcessed(bytesProcessed);
}
private onContentWritingCompleted(channelId: QualifiedChannelId) {
const channel = this.getOpenChannel(channelId);
if (!channel) {
throw new Error(`No channel with id ${channelId} found.`);
}
channel.onContent(null); // signify that the remote is done writing.
}
/**
* Occurs when the remote party has terminated a channel (including canceling an offer).
* @param channelId The ID of the terminated channel.
*/
private onChannelTerminated(channelId: QualifiedChannelId) {
const channel = this.getOpenChannel(channelId);
if (channel) {
this.deleteOpenChannel(channelId);
this.removeChannelFromOfferedQueue(channel);
channel.dispose();
}
}
} | the_stack |
import _ = require("../index");
declare module "../index" {
interface LoDashStatic {
/**
* The opposite of _.before; this method creates a function that invokes func once it’s called n or more times.
*
* @param n The number of calls before func is invoked.
* @param func The function to restrict.
* @return Returns the new restricted function.
*/
after<TFunc extends (...args: any[]) => any>(n: number, func: TFunc): TFunc;
}
interface Primitive<T> {
/**
* @see _.after
*/
after<TFunc extends (...args: any[]) => any>(func: TFunc): Function<TFunc>;
}
interface PrimitiveChain<T> {
/**
* @see _.after
*/
after<TFunc extends (...args: any[]) => any>(func: TFunc): FunctionChain<TFunc>;
}
interface LoDashStatic {
/**
* Creates a function that accepts up to n arguments ignoring any additional arguments.
*
* @param func The function to cap arguments for.
* @param n The arity cap.
* @returns Returns the new function.
*/
ary(func: (...args: any[]) => any, n?: number): (...args: any[]) => any;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.ary
*/
ary(n?: number): Function<(...args: any[]) => any>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.ary
*/
ary(n?: number): FunctionChain<(...args: any[]) => any>;
}
interface LoDashStatic {
/**
* Creates a function that invokes func, with the this binding and arguments of the created function, while
* it’s called less than n times. Subsequent calls to the created function return the result of the last func
* invocation.
*
* @param n The number of calls at which func is no longer invoked.
* @param func The function to restrict.
* @return Returns the new restricted function.
*/
before<TFunc extends (...args: any[]) => any>(n: number, func: TFunc): TFunc;
}
interface Primitive<T> {
/**
* @see _.before
*/
before<TFunc extends (...args: any[]) => any>(func: TFunc): Function<TFunc>;
}
interface PrimitiveChain<T> {
/**
* @see _.before
*/
before<TFunc extends (...args: any[]) => any>(func: TFunc): FunctionChain<TFunc>;
}
interface FunctionBind {
/**
* @see _.placeholder
*/
placeholder: __;
(func: (...args: any[]) => any, thisArg: any, ...partials: any[]): (...args: any[]) => any;
}
interface LoDashStatic {
/**
* Creates a function that invokes func with the this binding of thisArg and prepends any additional _.bind
* arguments to those provided to the bound function.
*
* The _.bind.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder for
* partially applied arguments.
*
* Note: Unlike native Function#bind this method does not set the "length" property of bound functions.
*
* @param func The function to bind.
* @param thisArg The this binding of func.
* @param partials The arguments to be partially applied.
* @return Returns the new bound function.
*/
bind: FunctionBind;
}
interface LoDashImplicitWrapper<TValue> {
/**
* @see _.bind
*/
bind(thisArg: any, ...partials: any[]): Function<(...args: any[]) => any>;
}
interface LoDashExplicitWrapper<TValue> {
/**
* @see _.bind
*/
bind(thisArg: any, ...partials: any[]): FunctionChain<(...args: any[]) => any>;
}
interface FunctionBindKey {
placeholder: __;
(object: object, key: string, ...partials: any[]): (...args: any[]) => any;
}
interface LoDashStatic {
/**
* Creates a function that invokes the method at object[key] and prepends any additional _.bindKey arguments
* to those provided to the bound function.
*
* This method differs from _.bind by allowing bound functions to reference methods that may be redefined
* or don’t yet exist. See Peter Michaux’s article for more details.
*
* The _.bindKey.placeholder value, which defaults to _ in monolithic builds, may be used as a placeholder
* for partially applied arguments.
*
* @param object The object the method belongs to.
* @param key The key of the method.
* @param partials The arguments to be partially applied.
* @return Returns the new bound function.
*/
bindKey: FunctionBindKey;
}
interface LoDashImplicitWrapper<TValue> {
/**
* @see _.bindKey
*/
bindKey(key: string, ...partials: any[]): Function<(...args: any[]) => any>;
}
interface LoDashExplicitWrapper<TValue> {
/**
* @see _.bindKey
*/
bindKey(key: string, ...partials: any[]): FunctionChain<(...args: any[]) => any>;
}
interface Curry {
<T1, R>(func: (t1: T1) => R, arity?: number): CurriedFunction1<T1, R>;
<T1, T2, R>(func: (t1: T1, t2: T2) => R, arity?: number): CurriedFunction2<T1, T2, R>;
<T1, T2, T3, R>(func: (t1: T1, t2: T2, t3: T3) => R, arity?: number): CurriedFunction3<T1, T2, T3, R>;
<T1, T2, T3, T4, R>(func: (t1: T1, t2: T2, t3: T3, t4: T4) => R, arity?: number): CurriedFunction4<T1, T2, T3, T4, R>;
<T1, T2, T3, T4, T5, R>(func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R, arity?: number): CurriedFunction5<T1, T2, T3, T4, T5, R>;
(func: (...args: any[]) => any, arity?: number): (...args: any[]) => any;
placeholder: __;
}
interface LoDashStatic {
curry: Curry;
}
interface CurriedFunction1<T1, R> {
(): CurriedFunction1<T1, R>;
(t1: T1): R;
}
interface CurriedFunction2<T1, T2, R> {
(): CurriedFunction2<T1, T2, R>;
(t1: T1): CurriedFunction1<T2, R>;
(t1: __, t2: T2): CurriedFunction1<T1, R>;
(t1: T1, t2: T2): R;
}
interface CurriedFunction3<T1, T2, T3, R> {
(): CurriedFunction3<T1, T2, T3, R>;
(t1: T1): CurriedFunction2<T2, T3, R>;
(t1: __, t2: T2): CurriedFunction2<T1, T3, R>;
(t1: T1, t2: T2): CurriedFunction1<T3, R>;
(t1: __, t2: __, t3: T3): CurriedFunction2<T1, T2, R>;
(t1: T1, t2: __, t3: T3): CurriedFunction1<T2, R>;
(t1: __, t2: T2, t3: T3): CurriedFunction1<T1, R>;
(t1: T1, t2: T2, t3: T3): R;
}
interface CurriedFunction4<T1, T2, T3, T4, R> {
(): CurriedFunction4<T1, T2, T3, T4, R>;
(t1: T1): CurriedFunction3<T2, T3, T4, R>;
(t1: __, t2: T2): CurriedFunction3<T1, T3, T4, R>;
(t1: T1, t2: T2): CurriedFunction2<T3, T4, R>;
(t1: __, t2: __, t3: T3): CurriedFunction3<T1, T2, T4, R>;
(t1: __, t2: __, t3: T3): CurriedFunction2<T2, T4, R>;
(t1: __, t2: T2, t3: T3): CurriedFunction2<T1, T4, R>;
(t1: T1, t2: T2, t3: T3): CurriedFunction1<T4, R>;
(t1: __, t2: __, t3: __, t4: T4): CurriedFunction3<T1, T2, T3, R>;
(t1: T1, t2: __, t3: __, t4: T4): CurriedFunction2<T2, T3, R>;
(t1: __, t2: T2, t3: __, t4: T4): CurriedFunction2<T1, T3, R>;
(t1: __, t2: __, t3: T3, t4: T4): CurriedFunction2<T1, T2, R>;
(t1: T1, t2: T2, t3: __, t4: T4): CurriedFunction1<T3, R>;
(t1: T1, t2: __, t3: T3, t4: T4): CurriedFunction1<T2, R>;
(t1: __, t2: T2, t3: T3, t4: T4): CurriedFunction1<T1, R>;
(t1: T1, t2: T2, t3: T3, t4: T4): R;
}
interface CurriedFunction5<T1, T2, T3, T4, T5, R> {
(): CurriedFunction5<T1, T2, T3, T4, T5, R>;
(t1: T1): CurriedFunction4<T2, T3, T4, T5, R>;
(t1: __, t2: T2): CurriedFunction4<T1, T3, T4, T5, R>;
(t1: T1, t2: T2): CurriedFunction3<T3, T4, T5, R>;
(t1: __, t2: __, t3: T3): CurriedFunction4<T1, T2, T4, T5, R>;
(t1: T1, t2: __, t3: T3): CurriedFunction3<T2, T4, T5, R>;
(t1: __, t2: T2, t3: T3): CurriedFunction3<T1, T4, T5, R>;
(t1: T1, t2: T2, t3: T3): CurriedFunction2<T4, T5, R>;
(t1: __, t2: __, t3: __, t4: T4): CurriedFunction4<T1, T2, T3, T5, R>;
(t1: T1, t2: __, t3: __, t4: T4): CurriedFunction3<T2, T3, T5, R>;
(t1: __, t2: T2, t3: __, t4: T4): CurriedFunction3<T1, T3, T5, R>;
(t1: __, t2: __, t3: T3, t4: T4): CurriedFunction3<T1, T2, T5, R>;
(t1: T1, t2: T2, t3: __, t4: T4): CurriedFunction2<T3, T5, R>;
(t1: T1, t2: __, t3: T3, t4: T4): CurriedFunction2<T2, T5, R>;
(t1: __, t2: T2, t3: T3, t4: T4): CurriedFunction2<T1, T5, R>;
(t1: T1, t2: T2, t3: T3, t4: T4): CurriedFunction1<T5, R>;
(t1: __, t2: __, t3: __, t4: __, t5: T5): CurriedFunction4<T1, T2, T3, T4, R>;
(t1: T1, t2: __, t3: __, t4: __, t5: T5): CurriedFunction3<T2, T3, T4, R>;
(t1: __, t2: T2, t3: __, t4: __, t5: T5): CurriedFunction3<T1, T3, T4, R>;
(t1: __, t2: __, t3: T3, t4: __, t5: T5): CurriedFunction3<T1, T2, T4, R>;
(t1: __, t2: __, t3: __, t4: T4, t5: T5): CurriedFunction3<T1, T2, T3, R>;
(t1: T1, t2: T2, t3: __, t4: __, t5: T5): CurriedFunction2<T3, T4, R>;
(t1: T1, t2: __, t3: T3, t4: __, t5: T5): CurriedFunction2<T2, T4, R>;
(t1: T1, t2: __, t3: __, t4: T4, t5: T5): CurriedFunction2<T2, T3, R>;
(t1: __, t2: T2, t3: T3, t4: __, t5: T5): CurriedFunction2<T1, T4, R>;
(t1: __, t2: T2, t3: __, t4: T4, t5: T5): CurriedFunction2<T1, T3, R>;
(t1: __, t2: __, t3: T3, t4: T4, t5: T5): CurriedFunction2<T1, T2, R>;
(t1: T1, t2: T2, t3: T3, t4: __, t5: T5): CurriedFunction1<T4, R>;
(t1: T1, t2: T2, t3: __, t4: T4, t5: T5): CurriedFunction1<T3, R>;
(t1: T1, t2: __, t3: T3, t4: T4, t5: T5): CurriedFunction1<T2, R>;
(t1: __, t2: T2, t3: T3, t4: T4, t5: T5): CurriedFunction1<T1, R>;
(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R;
}
interface RightCurriedFunction1<T1, R> {
(): RightCurriedFunction1<T1, R>;
(t1: T1): R;
}
interface RightCurriedFunction2<T1, T2, R> {
(): RightCurriedFunction2<T1, T2, R>;
(t2: T2): RightCurriedFunction1<T1, R>;
(t1: T1, t2: __): RightCurriedFunction1<T2, R>;
(t1: T1, t2: T2): R;
}
interface RightCurriedFunction3<T1, T2, T3, R> {
(): RightCurriedFunction3<T1, T2, T3, R>;
(t3: T3): RightCurriedFunction2<T1, T2, R>;
(t2: T2, t3: __): RightCurriedFunction2<T1, T3, R>;
(t2: T2, t3: T3): RightCurriedFunction1<T1, R>;
(t1: T1, t2: __, t3: __): RightCurriedFunction2<T2, T3, R>;
(t1: T1, t2: T2, t3: __): RightCurriedFunction1<T3, R>;
(t1: T1, t2: __, t3: T3): RightCurriedFunction1<T2, R>;
(t1: T1, t2: T2, t3: T3): R;
}
interface RightCurriedFunction4<T1, T2, T3, T4, R> {
(): RightCurriedFunction4<T1, T2, T3, T4, R>;
(t4: T4): RightCurriedFunction3<T1, T2, T3, R>;
(t3: T3, t4: __): RightCurriedFunction3<T1, T2, T4, R>;
(t3: T3, t4: T4): RightCurriedFunction2<T1, T2, R>;
(t2: T2, t3: __, t4: __): RightCurriedFunction3<T1, T3, T4, R>;
(t2: T2, t3: T3, t4: __): RightCurriedFunction2<T1, T4, R>;
(t2: T2, t3: __, t4: T4): RightCurriedFunction2<T1, T3, R>;
(t2: T2, t3: T3, t4: T4): RightCurriedFunction1<T1, R>;
(t1: T1, t2: __, t3: __, t4: __): RightCurriedFunction3<T2, T3, T4, R>;
(t1: T1, t2: T2, t3: __, t4: __): RightCurriedFunction2<T3, T4, R>;
(t1: T1, t2: __, t3: T3, t4: __): RightCurriedFunction2<T2, T4, R>;
(t1: T1, t2: __, t3: __, t4: T4): RightCurriedFunction2<T2, T3, R>;
(t1: T1, t2: T2, t3: T3, t4: __): RightCurriedFunction1<T4, R>;
(t1: T1, t2: T2, t3: __, t4: T4): RightCurriedFunction1<T3, R>;
(t1: T1, t2: __, t3: T3, t4: T4): RightCurriedFunction1<T2, R>;
(t1: T1, t2: T2, t3: T3, t4: T4): R;
}
interface RightCurriedFunction5<T1, T2, T3, T4, T5, R> {
(): RightCurriedFunction5<T1, T2, T3, T4, T5, R>;
(t5: T5): RightCurriedFunction4<T1, T2, T3, T4, R>;
(t4: T4, t5: __): RightCurriedFunction4<T1, T2, T3, T5, R>;
(t4: T4, t5: T5): RightCurriedFunction3<T1, T2, T3, R>;
(t3: T3, t4: __, t5: __): RightCurriedFunction4<T1, T2, T4, T5, R>;
(t3: T3, t4: T4, t5: __): RightCurriedFunction3<T1, T2, T5, R>;
(t3: T3, t4: __, t5: T5): RightCurriedFunction3<T1, T2, T4, R>;
(t3: T3, t4: T4, t5: T5): RightCurriedFunction2<T1, T2, R>;
(t2: T2, t3: __, t4: __, t5: __): RightCurriedFunction4<T1, T3, T4, T5, R>;
(t2: T2, t3: T3, t4: __, t5: __): RightCurriedFunction3<T1, T4, T5, R>;
(t2: T2, t3: __, t4: T4, t5: __): RightCurriedFunction3<T1, T3, T5, R>;
(t2: T2, t3: __, t4: __, t5: T5): RightCurriedFunction3<T1, T3, T4, R>;
(t2: T2, t3: T3, t4: T4, t5: __): RightCurriedFunction2<T1, T5, R>;
(t2: T2, t3: T3, t4: __, t5: T5): RightCurriedFunction2<T1, T4, R>;
(t2: T2, t3: __, t4: T4, t5: T5): RightCurriedFunction2<T1, T3, R>;
(t2: T2, t3: T3, t4: T4, t5: T5): RightCurriedFunction1<T1, R>;
(t1: T1, t2: __, t3: __, t4: __, t5: __): RightCurriedFunction4<T2, T3, T4, T5, R>;
(t1: T1, t2: T2, t3: __, t4: __, t5: __): RightCurriedFunction3<T3, T4, T5, R>;
(t1: T1, t2: __, t3: T3, t4: __, t5: __): RightCurriedFunction3<T2, T4, T5, R>;
(t1: T1, t2: __, t3: __, t4: T4, t5: __): RightCurriedFunction3<T2, T3, T5, R>;
(t1: T1, t2: __, t3: __, t4: __, t5: T5): RightCurriedFunction3<T2, T3, T4, R>;
(t1: T1, t2: T2, t3: T3, t4: __, t5: __): RightCurriedFunction2<T4, T5, R>;
(t1: T1, t2: T2, t3: __, t4: T4, t5: __): RightCurriedFunction2<T3, T5, R>;
(t1: T1, t2: T2, t3: __, t4: __, t5: T5): RightCurriedFunction2<T3, T4, R>;
(t1: T1, t2: __, t3: T3, t4: T4, t5: __): RightCurriedFunction2<T2, T5, R>;
(t1: T1, t2: __, t3: T3, t4: __, t5: T5): RightCurriedFunction2<T2, T4, R>;
(t1: T1, t2: __, t3: __, t4: T4, t5: T5): RightCurriedFunction2<T2, T3, R>;
(t1: T1, t2: T2, t3: T3, t4: T4, t5: __): RightCurriedFunction1<T5, R>;
(t1: T1, t2: T2, t3: T3, t4: __, t5: T5): RightCurriedFunction1<T4, R>;
(t1: T1, t2: T2, t3: __, t4: T4, t5: T5): RightCurriedFunction1<T3, R>;
(t1: T1, t2: __, t3: T3, t4: T4, t5: T5): RightCurriedFunction1<T2, R>;
(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5): R;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.curry
*/
curry(arity?: number):
T extends (arg1: infer T1) => infer R ? Function<CurriedFunction1<T1, R>> :
T extends (arg1: infer T1, arg2: infer T2) => infer R ? Function<CurriedFunction2<T1, T2, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3) => infer R ? Function<CurriedFunction3<T1, T2, T3, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3, arg4: infer T4) => infer R ? Function<CurriedFunction4<T1, T2, T3, T4, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3, arg4: infer T4, arg5: infer T5) => infer R ? Function<CurriedFunction5<T1, T2, T3, T4, T5, R>> :
Function<(...args: any[]) => any>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.curry
*/
curry(arity?: number):
T extends (arg1: infer T1) => infer R ? FunctionChain<CurriedFunction1<T1, R>> :
T extends (arg1: infer T1, arg2: infer T2) => infer R ? FunctionChain<CurriedFunction2<T1, T2, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3) => infer R ? FunctionChain<CurriedFunction3<T1, T2, T3, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3, arg4: infer T4) => infer R ? FunctionChain<CurriedFunction4<T1, T2, T3, T4, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3, arg4: infer T4, arg5: infer T5) => infer R ? FunctionChain<CurriedFunction5<T1, T2, T3, T4, T5, R>> :
FunctionChain<(...args: any[]) => any>;
}
interface CurryRight {
<T1, R>(func: (t1: T1) => R, arity?: number): RightCurriedFunction1<T1, R>;
<T1, T2, R>(func: (t1: T1, t2: T2) => R, arity?: number): RightCurriedFunction2<T1, T2, R>;
<T1, T2, T3, R>(func: (t1: T1, t2: T2, t3: T3) => R, arity?: number): RightCurriedFunction3<T1, T2, T3, R>;
<T1, T2, T3, T4, R>(func: (t1: T1, t2: T2, t3: T3, t4: T4) => R, arity?: number): RightCurriedFunction4<T1, T2, T3, T4, R>;
<T1, T2, T3, T4, T5, R>(func: (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5) => R, arity?: number): RightCurriedFunction5<T1, T2, T3, T4, T5, R>;
(func: (...args: any[]) => any, arity?: number): (...args: any[]) => any;
placeholder: __;
}
interface LoDashStatic {
curryRight: CurryRight;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.curryRight
*/
curryRight(arity?: number):
T extends (arg1: infer T1) => infer R ? Function<RightCurriedFunction1<T1, R>> :
T extends (arg1: infer T1, arg2: infer T2) => infer R ? Function<RightCurriedFunction2<T1, T2, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3) => infer R ? Function<RightCurriedFunction3<T1, T2, T3, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3, arg4: infer T4) => infer R ? Function<RightCurriedFunction4<T1, T2, T3, T4, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3, arg4: infer T4, arg5: infer T5) => infer R ? Function<RightCurriedFunction5<T1, T2, T3, T4, T5, R>> :
Function<(...args: any[]) => any>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.curryRight
*/
curryRight(arity?: number):
T extends (arg1: infer T1) => infer R ? FunctionChain<RightCurriedFunction1<T1, R>> :
T extends (arg1: infer T1, arg2: infer T2) => infer R ? FunctionChain<RightCurriedFunction2<T1, T2, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3) => infer R ? FunctionChain<RightCurriedFunction3<T1, T2, T3, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3, arg4: infer T4) => infer R ? FunctionChain<RightCurriedFunction4<T1, T2, T3, T4, R>> :
T extends (arg1: infer T1, arg2: infer T2, arg3: infer T3, arg4: infer T4, arg5: infer T5) => infer R ? FunctionChain<RightCurriedFunction5<T1, T2, T3, T4, T5, R>> :
FunctionChain<(...args: any[]) => any>;
}
interface DebounceSettings {
/**
* @see _.leading
*/
leading?: boolean;
/**
* @see _.maxWait
*/
maxWait?: number;
/**
* @see _.trailing
*/
trailing?: boolean;
}
interface LoDashStatic {
/**
* Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since
* the last time the debounced function was invoked. The debounced function comes with a cancel method to
* cancel delayed invocations and a flush method to immediately invoke them. Provide an options object to
* indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent
* calls to the debounced function return the result of the last func invocation.
*
* Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only
* if the the debounced function is invoked more than once during the wait timeout.
*
* See David Corbacho’s article for details over the differences between _.debounce and _.throttle.
*
* @param func The function to debounce.
* @param wait The number of milliseconds to delay.
* @param options The options object.
* @param options.leading Specify invoking on the leading edge of the timeout.
* @param options.maxWait The maximum time func is allowed to be delayed before it’s invoked.
* @param options.trailing Specify invoking on the trailing edge of the timeout.
* @return Returns the new debounced function.
*/
debounce<T extends (...args: any) => any>(func: T, wait?: number, options?: DebounceSettings): T & Cancelable;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.debounce
*/
debounce(wait?: number, options?: DebounceSettings): Function<T & Cancelable>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.debounce
*/
debounce(wait?: number, options?: DebounceSettings): FunctionChain<T & Cancelable>;
}
interface LoDashStatic {
/**
* Defers invoking the func until the current call stack has cleared. Any additional arguments are provided to
* func when it’s invoked.
*
* @param func The function to defer.
* @param args The arguments to invoke the function with.
* @return Returns the timer id.
*/
defer(func: (...args: any[]) => any, ...args: any[]): number;
}
interface LoDashImplicitWrapper<TValue> {
/**
* @see _.defer
*/
defer(...args: any[]): Primitive<number>;
}
interface LoDashExplicitWrapper<TValue> {
/**
* @see _.defer
*/
defer(...args: any[]): PrimitiveChain<number>;
}
interface LoDashStatic {
/**
* Invokes func after wait milliseconds. Any additional arguments are provided to func when it’s invoked.
*
* @param func The function to delay.
* @param wait The number of milliseconds to delay invocation.
* @param args The arguments to invoke the function with.
* @return Returns the timer id.
*/
delay(func: (...args: any[]) => any, wait: number, ...args: any[]): number;
}
interface LoDashImplicitWrapper<TValue> {
/**
* @see _.delay
*/
delay(wait: number, ...args: any[]): Primitive<number>;
}
interface LoDashExplicitWrapper<TValue> {
/**
* @see _.delay
*/
delay(wait: number, ...args: any[]): PrimitiveChain<number>;
}
interface LoDashStatic {
/**
* Creates a function that invokes `func` with arguments reversed.
*
* @category Function
* @param func The function to flip arguments for.
* @returns Returns the new function.
* @example
*
* var flipped = _.flip(function() {
* return _.toArray(arguments);
* });
*
* flipped('a', 'b', 'c', 'd');
* // => ['d', 'c', 'b', 'a']
*/
flip<T extends (...args: any) => any>(func: T): T;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.flip
*/
flip(): this;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.flip
*/
flip(): this;
}
interface MemoizedFunction {
/**
* @see _.cache
*/
cache: MapCache;
}
interface LoDashStatic {
/**
* Creates a function that memoizes the result of func. If resolver is provided it determines the cache key for
* storing the result based on the arguments provided to the memoized function. By default, the first argument
* provided to the memoized function is coerced to a string and used as the cache key. The func is invoked with
* the this binding of the memoized function.
*
* @param func The function to have its output memoized.
* @param resolver The function to resolve the cache key.
* @return Returns the new memoizing function.
*/
memoize: {
<T extends (...args: any) => any>(func: T, resolver?: (...args: any[]) => any): T & MemoizedFunction;
Cache: MapCacheConstructor;
};
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.memoize
*/
memoize(resolver?: (...args: any[]) => any): Function<T & MemoizedFunction>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.memoize
*/
memoize(resolver?: (...args: any[]) => any): FunctionChain<T & MemoizedFunction>;
}
interface LoDashStatic {
/**
* Creates a function that negates the result of the predicate func. The func predicate is invoked with
* the this binding and arguments of the created function.
*
* @param predicate The predicate to negate.
* @return Returns the new function.
*/
negate<T extends any[]>(predicate: (...args: T) => boolean): (...args: T) => boolean;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.negate
*/
negate(): Function<(...args: Parameters<T>) => boolean>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.negate
*/
negate(): FunctionChain<(...args: Parameters<T>) => boolean>;
}
interface LoDashStatic {
/**
* Creates a function that is restricted to invoking func once. Repeat calls to the function return the value
* of the first call. The func is invoked with the this binding and arguments of the created function.
*
* @param func The function to restrict.
* @return Returns the new restricted function.
*/
once<T extends (...args: any) => any>(func: T): T;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.once
*/
once(): Function<T>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.once
*/
once(): FunctionChain<T>;
}
interface LoDashStatic {
/**
* Creates a function that runs each argument through a corresponding transform function.
*
* @param func The function to wrap.
* @param transforms The functions to transform arguments, specified as individual functions or arrays
* of functions.
* @return Returns the new function.
*/
overArgs(func: (...args: any[]) => any, ...transforms: Array<Many<(...args: any[]) => any>>): (...args: any[]) => any;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.overArgs
*/
overArgs(...transforms: Array<Many<(...args: any[]) => any>>): Function<(...args: any[]) => any>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.overArgs
*/
overArgs(...transforms: Array<Many<(...args: any[]) => any>>): FunctionChain<(...args: any[]) => any>;
}
interface LoDashStatic {
/**
* Creates a function that, when called, invokes func with any additional partial arguments
* prepended to those provided to the new function. This method is similar to _.bind except
* it does not alter the this binding.
* @param func The function to partially apply arguments to.
* @param args Arguments to be partially applied.
* @return The new partially applied function.
*/
partial: Partial;
}
type __ = LoDashStatic;
type Function0<R> = () => R;
type Function1<T1, R> = (t1: T1) => R;
type Function2<T1, T2, R> = (t1: T1, t2: T2) => R;
type Function3<T1, T2, T3, R> = (t1: T1, t2: T2, t3: T3) => R;
type Function4<T1, T2, T3, T4, R> = (t1: T1, t2: T2, t3: T3, t4: T4) => R;
interface Partial {
<T1, T2, R>(func: Function2<T1, T2, R>, plc1: __, arg2: T2): Function1<T1, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, plc1: __, arg2: T2): Function2<T1, T3, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, plc1: __, plc2: __, arg3: T3): Function2<T1, T2, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, plc2: __, arg3: T3): Function1<T2, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, plc1: __, arg2: T2, arg3: T3): Function1<T1, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: __, arg2: T2): Function3<T1, T3, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: __, plc2: __, arg3: T3): Function3<T1, T2, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: __, arg3: T3): Function2<T2, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: __, arg2: T2, arg3: T3): Function2<T1, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, arg3: T3): Function1<T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: __, plc2: __, plc3: __, arg4: T4): Function3<T1, T2, T3, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: __, plc3: __, arg4: T4): Function2<T2, T3, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: __, arg2: T2, plc3: __, arg4: T4): Function2<T1, T3, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, plc3: __, arg4: T4): Function1<T3, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: __, plc2: __, arg3: T3, arg4: T4): Function2<T1, T2, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: __, arg3: T3, arg4: T4): Function1<T2, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, plc1: __, arg2: T2, arg3: T3, arg4: T4): Function1<T1, R>;
<TS extends any[], R>(func: (...ts: TS) => R): (...ts: TS) => R;
<TS extends any[], T1, R>(func: (t1: T1, ...ts: TS) => R, arg1: T1): (...ts: TS) => R;
<TS extends any[], T1, T2, R>(func: (t1: T1, t2: T2, ...ts: TS) => R, t1: T1, t2: T2): (...ts: TS) => R;
<TS extends any[], T1, T2, T3, R>(func: (t1: T1, t2: T2, t3: T3, ...ts: TS) => R, t1: T1, t2: T2, t3: T3): (...ts: TS) => R;
<TS extends any[], T1, T2, T3, T4, R>(func: (t1: T1, t2: T2, t3: T3, t4: T4, ...ts: TS) => R, t1: T1, t2: T2, t3: T3, t4: T4): (...ts: TS) => R;
placeholder: __;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.partial
*/
partial<T2>(plc1: __, arg2: T2): Function<
T extends Function2<infer T1, T2, infer R> ? Function1<T1, R> :
T extends Function3<infer T1, T2, infer T3, infer R> ? Function2<T1, T3, R> :
T extends Function4<infer T1, T2, infer T3, infer T4, infer R> ? Function3<T1, T3, T4, R> :
any
>;
/**
* @see _.partial
*/
partial<T3>(plc1: __, plc2: __, arg3: T3): Function<
T extends Function3<infer T1, infer T2, T3, infer R> ? Function2<T1, T2, R> :
T extends Function4<infer T1, infer T2, T3, infer T4, infer R> ? Function3<T1, T2, T4, R> :
any
>;
/**
* @see _.partial
*/
partial<T1, T3>(arg1: T1, plc2: __, arg3: T3): Function<
T extends Function3<T1, infer T2, T3, infer R> ? Function1<T2, R> :
T extends Function4<T1, infer T2, T3, infer T4, infer R> ? Function2<T2, T4, R> :
any
>;
/**
* @see _.partial
*/
partial<T2, T3>(plc1: __, arg2: T2, arg3: T3): Function<
T extends Function3<infer T1, T2, T3, infer R> ? Function1<T1, R> :
T extends Function4<infer T1, T2, T3, infer T4, infer R> ? Function2<T1, T4, R> :
any
>;
/**
* @see _.partial
*/
partial<T3>(plc1: __, plc2: __, arg3: T3): Function<
T extends Function4<infer T1, infer T2, T3, infer T4, infer R> ? Function3<T1, T2, T4, R> :
any
>;
/**
* @see _.partial
*/
partial<T1, T4>(arg1: T1, plc2: __, plc3: __, arg4: T4): Function<
T extends Function4<T1, infer T2, infer T3, T4, infer R> ? Function2<T2, T3, R> :
any
>;
/**
* @see _.partial
*/
partial<T2, T4>(plc1: __, arg2: T2, plc3: __, arg4: T4): Function<
T extends Function4<infer T1, T2, infer T3, T4, infer R> ? Function2<T1, T3, R> :
any
>;
/**
* @see _.partial
*/
partial<T1, T2, T4>(arg1: T1, arg2: T2, plc3: __, arg4: T4): Function<
T extends Function4<T1, T2, infer T3, T4, infer R> ? Function1<T3, R> :
any
>;
/**
* @see _.partial
*/
partial<T3, T4>(plc1: __, plc2: __, arg3: T3, arg4: T4): Function<
T extends Function4<infer T1, infer T2, T3, T4, infer R> ? Function2<T1, T2, R> :
any
>;
/**
* @see _.partial
*/
partial<T1, T3, T4>(arg1: T1, plc2: __, arg3: T3, arg4: T4): Function<
T extends Function4<T1, infer T2, T3, T4, infer R> ? Function1<T2, R> :
any
>;
/**
* @see _.partial
*/
partial<T2, T3, T4>(plc1: __, arg2: T2, arg3: T3, arg4: T4): Function<
T extends Function4<infer T1, T2, T3, T4, infer R> ? Function1<T1, R> :
any
>;
/**
* @see _.partial
*/
partial<T1, T2, T3, T4>(arg1: T1, arg2: T2, arg3: T3, arg4: T4): Function<
T extends (t1: T1, t2: T2, t3: T3, t4: T4, ...ts: infer TS) => infer R ? (...ts: TS) => R :
any
>;
/**
* @see _.partial
*/
partial<T1, T2, T3>(arg1: T1, arg2: T2, arg3: T3): Function<
T extends (t1: T1, t2: T2, t3: T3, ...ts: infer TS) => infer R ? (...ts: TS) => R :
any
>;
/**
* @see _.partial
*/
partial<T1, T2>(arg1: T1, arg2: T2): Function<
T extends (t1: T1, t2: T2, ...ts: infer TS) => infer R ? (...ts: TS) => R :
any
>;
/**
* @see _.partial
*/
partial<T1>(arg1: T1): Function<
T extends (t1: T1, ...ts: infer TS) => infer R ? (...ts: TS) => R :
any
>;
/**
* @see _.partial
*/
partial(): Function<T extends (...ts: any[]) => any ? T : any>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.partial
*/
partial<T2>(plc1: __, arg2: T2): FunctionChain<
T extends Function2<infer T1, T2, infer R> ? Function1<T1, R> :
T extends Function3<infer T1, T2, infer T3, infer R> ? Function2<T1, T3, R> :
T extends Function4<infer T1, T2, infer T3, infer T4, infer R> ? Function3<T1, T3, T4, R> :
any
>;
/**
* @see _.partial
*/
partial<T3>(plc1: __, plc2: __, arg3: T3): FunctionChain<
T extends Function3<infer T1, infer T2, T3, infer R> ? Function2<T1, T2, R> :
T extends Function4<infer T1, infer T2, T3, infer T4, infer R> ? Function3<T1, T2, T4, R> :
any
>;
/**
* @see _.partial
*/
partial<T1, T3>(arg1: T1, plc2: __, arg3: T3): FunctionChain<
T extends Function3<T1, infer T2, T3, infer R> ? Function1<T2, R> :
T extends Function4<T1, infer T2, T3, infer T4, infer R> ? Function2<T2, T4, R> :
any
>;
/**
* @see _.partial
*/
partial<T2, T3>(plc1: __, arg2: T2, arg3: T3): FunctionChain<
T extends Function3<infer T1, T2, T3, infer R> ? Function1<T1, R> :
T extends Function4<infer T1, T2, T3, infer T4, infer R> ? Function2<T1, T4, R> :
any
>;
/**
* @see _.partial
*/
partial<T3>(plc1: __, plc2: __, arg3: T3): FunctionChain<
T extends Function4<infer T1, infer T2, T3, infer T4, infer R> ? Function3<T1, T2, T4, R> :
any
>;
/**
* @see _.partial
*/
partial<T1, T4>(arg1: T1, plc2: __, plc3: __, arg4: T4): FunctionChain<
T extends Function4<T1, infer T2, infer T3, T4, infer R> ? Function2<T2, T3, R> :
any
>;
/**
* @see _.partial
*/
partial<T2, T4>(plc1: __, arg2: T2, plc3: __, arg4: T4): FunctionChain<
T extends Function4<infer T1, T2, infer T3, T4, infer R> ? Function2<T1, T3, R> :
any
>;
/**
* @see _.partial
*/
partial<T1, T2, T4>(arg1: T1, arg2: T2, plc3: __, arg4: T4): FunctionChain<
T extends Function4<T1, T2, infer T3, T4, infer R> ? Function1<T3, R> :
any
>;
/**
* @see _.partial
*/
partial<T3, T4>(plc1: __, plc2: __, arg3: T3, arg4: T4): FunctionChain<
T extends Function4<infer T1, infer T2, T3, T4, infer R> ? Function2<T1, T2, R> :
any
>;
/**
* @see _.partial
*/
partial<T1, T3, T4>(arg1: T1, plc2: __, arg3: T3, arg4: T4): FunctionChain<
T extends Function4<T1, infer T2, T3, T4, infer R> ? Function1<T2, R> :
any
>;
/**
* @see _.partial
*/
partial<T2, T3, T4>(plc1: __, arg2: T2, arg3: T3, arg4: T4): FunctionChain<
T extends Function4<infer T1, T2, T3, T4, infer R> ? Function1<T1, R> :
any
>;
/**
* @see _.partial
*/
partial<T1, T2, T3, T4>(arg1: T1, arg2: T2, arg3: T3, arg4: T4): FunctionChain<
T extends (t1: T1, t2: T2, t3: T3, t4: T4, ...ts: infer TS) => infer R ? (...ts: TS) => R :
any
>;
/**
* @see _.partial
*/
partial<T1, T2, T3>(arg1: T1, arg2: T2, arg3: T3): FunctionChain<
T extends (t1: T1, t2: T2, t3: T3, ...ts: infer TS) => infer R ? (...ts: TS) => R :
any
>;
/**
* @see _.partial
*/
partial<T1, T2>(arg1: T1, arg2: T2): FunctionChain<
T extends (t1: T1, t2: T2, ...ts: infer TS) => infer R ? (...ts: TS) => R :
any
>;
/**
* @see _.partial
*/
partial<T1>(arg1: T1): FunctionChain<
T extends (t1: T1, ...ts: infer TS) => infer R ? (...ts: TS) => R :
any
>;
/**
* @see _.partial
*/
partial(): FunctionChain<T extends (...ts: any[]) => any ? T : any>;
}
interface LoDashStatic {
/**
* This method is like _.partial except that partial arguments are appended to those provided
* to the new function.
* @param func The function to partially apply arguments to.
* @param args Arguments to be partially applied.
* @return The new partially applied function.
*/
partialRight: PartialRight;
}
interface PartialRight {
<R>(func: Function0<R>): Function0<R>;
<T1, R>(func: Function1<T1, R>): Function1<T1, R>;
<T1, R>(func: Function1<T1, R>, arg1: T1): Function0<R>;
<T1, T2, R>(func: Function2<T1, T2, R>): Function2<T1, T2, R>;
<T1, T2, R>(func: Function2<T1, T2, R>, arg1: T1, plc2: __): Function1<T2, R>;
<T1, T2, R>(func: Function2<T1, T2, R>, arg2: T2): Function1<T1, R>;
<T1, T2, R>(func: Function2<T1, T2, R>, arg1: T1, arg2: T2): Function0<R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>): Function3<T1, T2, T3, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, plc2: __, plc3: __): Function2<T2, T3, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg2: T2, plc3: __): Function2<T1, T3, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, arg2: T2, plc3: __): Function1<T3, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg3: T3): Function2<T1, T2, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, plc2: __, arg3: T3): Function1<T2, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg2: T2, arg3: T3): Function1<T1, R>;
<T1, T2, T3, R>(func: Function3<T1, T2, T3, R>, arg1: T1, arg2: T2, arg3: T3): Function0<R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>): Function4<T1, T2, T3, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: __, plc3: __, plc4: __): Function3<T2, T3, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg2: T2, plc3: __, plc4: __): Function3<T1, T3, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, plc3: __, plc4: __): Function2<T3, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg3: T3, plc4: __): Function3<T1, T2, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: __, arg3: T3, plc4: __): Function2<T2, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg2: T2, arg3: T3, plc4: __): Function2<T1, T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, arg3: T3, plc4: __): Function1<T4, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg4: T4): Function3<T1, T2, T3, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: __, plc3: __, arg4: T4): Function2<T2, T3, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg2: T2, plc3: __, arg4: T4): Function2<T1, T3, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, plc3: __, arg4: T4): Function1<T3, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg3: T3, arg4: T4): Function2<T1, T2, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, plc2: __, arg3: T3, arg4: T4): Function1<T2, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg2: T2, arg3: T3, arg4: T4): Function1<T1, R>;
<T1, T2, T3, T4, R>(func: Function4<T1, T2, T3, T4, R>, arg1: T1, arg2: T2, arg3: T3, arg4: T4): Function0<R>;
(func: (...args: any[]) => any, ...args: any[]): (...args: any[]) => any;
placeholder: __;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.partialRight
*/
partialRight<T1>(arg1: T1, plc2: __): Function<
T extends Function2<T1, infer T2, infer R> ? Function1<T2, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2>(arg2: T2): Function<
T extends Function2<infer T1, T2, infer R> ? Function1<T1, R> : any
>;
/**
* @see _.partialRight
*/
partialRight<T1>(arg1: T1, plc2: __, plc3: __): Function<
T extends Function3<T1, infer T2, infer T3, infer R> ? Function2<T2, T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2>(arg2: T2, plc3: __): Function<
T extends Function3<infer T1, T2, infer T3, infer R> ? Function2<T1, T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T2>(arg1: T1, arg2: T2, plc3: __): Function<
T extends Function3<T1, T2, infer T3, infer R> ? Function1<T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T3>(arg3: T3): Function<
T extends Function3<infer T1, infer T2, T3, infer R> ? Function2<T1, T2, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T3>(arg1: T1, plc2: __, arg3: T3): Function<
T extends Function3<T1, infer T2, T3, infer R> ? Function1<T2, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2, T3>(arg2: T2, arg3: T3): Function<
T extends Function3<infer T1, T2, T3, infer R> ? Function1<T1, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1>(arg1: T1, plc2: __, plc3: __, plc4: __): Function<
T extends Function4<T1, infer T2, infer T3, infer T4, infer R> ? Function3<T2, T3, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2>(arg2: T2, plc3: __, plc4: __): Function<
T extends Function4<infer T1, T2, infer T3, infer T4, infer R> ? Function3<T1, T3, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T2>(arg1: T1, arg2: T2, plc3: __, plc4: __): Function<
T extends Function4<T1, T2, infer T3, infer T4, infer R> ? Function2<T3, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T3>(arg3: T3, plc4: __): Function<
T extends Function4<infer T1, infer T2, T3, infer T4, infer R> ? Function3<T1, T2, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T3>(arg1: T1, plc2: __, arg3: T3, plc4: __): Function<
T extends Function4<T1, infer T2, infer T3, infer T4, infer R> ? Function2<T2, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2, T3>(arg2: T2, arg3: T3, plc4: __): Function<
T extends Function4<infer T1, T2, T3, infer T4, infer R> ? Function2<T1, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T2, T3>(arg1: T1, arg2: T2, arg3: T3, plc4: __): Function<
T extends Function4<T1, T2, T3, infer T4, infer R> ? Function1<T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T4>(arg4: T4): Function<
T extends Function4<infer T1, infer T2, infer T3, T4, infer R> ? Function3<T1, T2, T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T4>(arg1: T1, plc2: __, plc3: __, arg4: T4): Function<
T extends Function4<T1, infer T2, infer T3, T4, infer R> ? Function2<T2, T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2, T4>(arg2: T2, plc3: __, arg4: T4): Function<
T extends Function4<infer T1, T2, infer T3, T4, infer R> ? Function2<T1, T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T2, T4>(arg1: T1, arg2: T2, plc3: __, arg4: T4): Function<
T extends Function4<T1, T2, infer T3, T4, infer R> ? Function1<T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T3, T4>(arg3: T3, arg4: T4): Function<
T extends Function4<infer T1, infer T2, T3, T4, infer R> ? Function2<T1, T2, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T3, T4>(arg1: T1, plc2: __, arg3: T3, arg4: T4): Function<
T extends Function4<T1, infer T2, T3, T4, infer R> ? Function1<T2, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2, T3, T4>(arg2: T2, arg3: T3, arg4: T4): Function<
T extends Function4<infer T1, T2, T3, T4, infer R> ? Function1<T1, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<TS extends any[]>(...ts: TS): Function<T extends (...args: TS) => infer R ? () => R : any>;
/**
* @see _.partialRight
*/
partialRight(): Function<T extends (...ts: any[]) => any ? T : any>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.partialRight
*/
partialRight<T1>(arg1: T1, plc2: __): FunctionChain<
T extends Function2<T1, infer T2, infer R> ? Function1<T2, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2>(arg2: T2): FunctionChain<
T extends Function2<infer T1, T2, infer R> ? Function1<T1, R> : any
>;
/**
* @see _.partialRight
*/
partialRight<T1>(arg1: T1, plc2: __, plc3: __): FunctionChain<
T extends Function3<T1, infer T2, infer T3, infer R> ? Function2<T2, T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2>(arg2: T2, plc3: __): FunctionChain<
T extends Function3<infer T1, T2, infer T3, infer R> ? Function2<T1, T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T2>(arg1: T1, arg2: T2, plc3: __): FunctionChain<
T extends Function3<T1, T2, infer T3, infer R> ? Function1<T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T3>(arg3: T3): FunctionChain<
T extends Function3<infer T1, infer T2, T3, infer R> ? Function2<T1, T2, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T3>(arg1: T1, plc2: __, arg3: T3): FunctionChain<
T extends Function3<T1, infer T2, T3, infer R> ? Function1<T2, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2, T3>(arg2: T2, arg3: T3): FunctionChain<
T extends Function3<infer T1, T2, T3, infer R> ? Function1<T1, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1>(arg1: T1, plc2: __, plc3: __, plc4: __): FunctionChain<
T extends Function4<T1, infer T2, infer T3, infer T4, infer R> ? Function3<T2, T3, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2>(arg2: T2, plc3: __, plc4: __): FunctionChain<
T extends Function4<infer T1, T2, infer T3, infer T4, infer R> ? Function3<T1, T3, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T2>(arg1: T1, arg2: T2, plc3: __, plc4: __): FunctionChain<
T extends Function4<T1, T2, infer T3, infer T4, infer R> ? Function2<T3, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T3>(arg3: T3, plc4: __): FunctionChain<
T extends Function4<infer T1, infer T2, T3, infer T4, infer R> ? Function3<T1, T2, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T3>(arg1: T1, plc2: __, arg3: T3, plc4: __): FunctionChain<
T extends Function4<T1, infer T2, infer T3, infer T4, infer R> ? Function2<T2, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2, T3>(arg2: T2, arg3: T3, plc4: __): FunctionChain<
T extends Function4<infer T1, T2, T3, infer T4, infer R> ? Function2<T1, T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T2, T3>(arg1: T1, arg2: T2, arg3: T3, plc4: __): FunctionChain<
T extends Function4<T1, T2, T3, infer T4, infer R> ? Function1<T4, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T4>(arg4: T4): FunctionChain<
T extends Function4<infer T1, infer T2, infer T3, T4, infer R> ? Function3<T1, T2, T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T4>(arg1: T1, plc2: __, plc3: __, arg4: T4): FunctionChain<
T extends Function4<T1, infer T2, infer T3, T4, infer R> ? Function2<T2, T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2, T4>(arg2: T2, plc3: __, arg4: T4): FunctionChain<
T extends Function4<infer T1, T2, infer T3, T4, infer R> ? Function2<T1, T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T2, T4>(arg1: T1, arg2: T2, plc3: __, arg4: T4): FunctionChain<
T extends Function4<T1, T2, infer T3, T4, infer R> ? Function1<T3, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T3, T4>(arg3: T3, arg4: T4): FunctionChain<
T extends Function4<infer T1, infer T2, T3, T4, infer R> ? Function2<T1, T2, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T1, T3, T4>(arg1: T1, plc2: __, arg3: T3, arg4: T4): FunctionChain<
T extends Function4<T1, infer T2, T3, T4, infer R> ? Function1<T2, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<T2, T3, T4>(arg2: T2, arg3: T3, arg4: T4): FunctionChain<
T extends Function4<infer T1, T2, T3, T4, infer R> ? Function1<T1, R> :
any
>;
/**
* @see _.partialRight
*/
partialRight<TS extends any[]>(...ts: TS): FunctionChain<T extends (...args: TS) => infer R ? () => R : any>;
/**
* @see _.partialRight
*/
partialRight(): FunctionChain<T extends (...ts: any[]) => any ? T : any>;
}
interface LoDashStatic {
/**
* Creates a function that invokes func with arguments arranged according to the specified indexes where the
* argument value at the first index is provided as the first argument, the argument value at the second index
* is provided as the second argument, and so on.
* @param func The function to rearrange arguments for.
* @param indexes The arranged argument indexes, specified as individual indexes or arrays of indexes.
* @return Returns the new function.
*/
rearg(func: (...args: any[]) => any, ...indexes: Array<Many<number>>): (...args: any[]) => any;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.rearg
*/
rearg(...indexes: Array<Many<number>>): Function<(...args: any[]) => any>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.rearg
*/
rearg(...indexes: Array<Many<number>>): FunctionChain<(...args: any[]) => any>;
}
interface LoDashStatic {
/**
* Creates a function that invokes func with the this binding of the created function and arguments from start
* and beyond provided as an array.
*
* Note: This method is based on the rest parameter.
*
* @param func The function to apply a rest parameter to.
* @param start The start position of the rest parameter.
* @return Returns the new function.
*/
rest(func: (...args: any[]) => any, start?: number): (...args: any[]) => any;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.rest
*/
rest(start?: number): Function<(...args: any[]) => any>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.rest
*/
rest(start?: number): FunctionChain<(...args: any[]) => any>;
}
interface LoDashStatic {
/**
* Creates a function that invokes func with the this binding of the created function and an array of arguments
* much like Function#apply.
*
* Note: This method is based on the spread operator.
*
* @param func The function to spread arguments over.
* @return Returns the new function.
*/
spread<TResult>(func: (...args: any[]) => TResult, start?: number): (...args: any[]) => TResult;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.spread
*/
spread(start?: number): Function<(...args: any[]) => ReturnType<T>>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.spread
*/
spread(start?: number): FunctionChain<(...args: any[]) => ReturnType<T>>;
}
interface ThrottleSettings {
/**
* @see _.leading
*/
leading?: boolean;
/**
* @see _.trailing
*/
trailing?: boolean;
}
interface LoDashStatic {
/**
* Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled
* function comes with a cancel method to cancel delayed invocations and a flush method to immediately invoke
* them. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge
* of the wait timeout. Subsequent calls to the throttled function return the result of the last func call.
*
* Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if
* the the throttled function is invoked more than once during the wait timeout.
*
* @param func The function to throttle.
* @param wait The number of milliseconds to throttle invocations to.
* @param options The options object.
* @param options.leading Specify invoking on the leading edge of the timeout.
* @param options.trailing Specify invoking on the trailing edge of the timeout.
* @return Returns the new throttled function.
*/
throttle<T extends (...args: any) => any>(func: T, wait?: number, options?: ThrottleSettings): T & Cancelable;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.throttle
*/
throttle(wait?: number, options?: ThrottleSettings): Function<T & Cancelable>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.throttle
*/
throttle(wait?: number, options?: ThrottleSettings): FunctionChain<T & Cancelable>;
}
interface LoDashStatic {
/**
* Creates a function that accepts up to one argument, ignoring any
* additional arguments.
*
* @category Function
* @param func The function to cap arguments for.
* @returns Returns the new function.
* @example
*
* _.map(['6', '8', '10'], _.unary(parseInt));
* // => [6, 8, 10]
*/
unary<T, TResult>(func: (arg1: T, ...args: any[]) => TResult): (arg1: T) => TResult;
}
interface Function<T extends (...args: any) => any> {
/**
* @see _.unary
*/
unary(): Function<(arg1: Parameters<T>['0']) => ReturnType<T>>;
}
interface FunctionChain<T extends (...args: any) => any> {
/**
* @see _.unary
*/
unary(): FunctionChain<(arg1: Parameters<T>['0']) => ReturnType<T>>;
}
interface LoDashStatic {
/**
* Creates a function that provides value to the wrapper function as its first argument. Any additional
* arguments provided to the function are appended to those provided to the wrapper function. The wrapper is
* invoked with the this binding of the created function.
*
* @param value The value to wrap.
* @param wrapper The wrapper function.
* @return Returns the new function.
*/
wrap<T, TArgs, TResult>(value: T, wrapper: (value: T, ...args: TArgs[]) => TResult): (...args: TArgs[]) => TResult;
}
interface LoDashImplicitWrapper<TValue> {
/**
* @see _.wrap
*/
wrap<TArgs, TResult>(wrapper: (value: TValue, ...args: TArgs[]) => TResult): Function<(...args: TArgs[]) => TResult>;
}
interface LoDashExplicitWrapper<TValue> {
/**
* @see _.wrap
*/
wrap<TArgs, TResult>(wrapper: (value: TValue, ...args: TArgs[]) => TResult): FunctionChain<(...args: TArgs[]) => TResult>;
}
} | the_stack |
import { BaseResource, CloudError } from "ms-rest-azure";
import * as moment from "moment";
export {
BaseResource,
CloudError
};
/**
* SKU parameters supplied to the create Redis operation.
*/
export interface Sku {
/**
* The type of Redis cache to deploy. Valid values: (Basic, Standard, Premium). Possible values
* include: 'Basic', 'Standard', 'Premium'
*/
name: string;
/**
* The SKU family to use. Valid values: (C, P). (C = Basic/Standard, P = Premium). Possible
* values include: 'C', 'P'
*/
family: string;
/**
* The size of the Redis cache to deploy. Valid values: for C (Basic/Standard) family (0, 1, 2,
* 3, 4, 5, 6), for P (Premium) family (1, 2, 3, 4).
*/
capacity: number;
}
/**
* Redis cache access keys.
*/
export interface RedisAccessKeys {
/**
* The current primary key that clients can use to authenticate with Redis cache.
*/
readonly primaryKey?: string;
/**
* The current secondary key that clients can use to authenticate with Redis cache.
*/
readonly secondaryKey?: string;
}
/**
* Linked server Id
*/
export interface RedisLinkedServer {
/**
* Linked server Id.
*/
readonly id?: string;
}
/**
* The Resource definition.
*/
export interface Resource extends BaseResource {
/**
* Resource ID.
*/
readonly id?: string;
/**
* Resource name.
*/
readonly name?: string;
/**
* Resource type.
*/
readonly type?: string;
}
/**
* The resource model definition for a ARM proxy resource. It will have everything other than
* required location and tags
*/
export interface ProxyResource extends Resource {
}
/**
* The resource model definition for a ARM tracked top level resource
*/
export interface TrackedResource extends Resource {
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
/**
* The geo-location where the resource lives
*/
location: string;
}
/**
* Parameters supplied to the Create Redis operation.
*/
export interface RedisCreateParameters {
/**
* All Redis Settings. Few possible keys:
* rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta,maxmemory-policy,notify-keyspace-events,maxmemory-samples,slowlog-log-slower-than,slowlog-max-len,list-max-ziplist-entries,list-max-ziplist-value,hash-max-ziplist-entries,hash-max-ziplist-value,set-max-intset-entries,zset-max-ziplist-entries,zset-max-ziplist-value
* etc.
*/
redisConfiguration?: { [propertyName: string]: string };
/**
* Specifies whether the non-ssl Redis server port (6379) is enabled.
*/
enableNonSslPort?: boolean;
/**
* A dictionary of tenant settings
*/
tenantSettings?: { [propertyName: string]: string };
/**
* The number of shards to be created on a Premium Cluster Cache.
*/
shardCount?: number;
/**
* Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0',
* '1.1', '1.2'). Possible values include: '1.0', '1.1', '1.2'
*/
minimumTlsVersion?: string;
/**
* The SKU of the Redis cache to deploy.
*/
sku: Sku;
/**
* The full resource ID of a subnet in a virtual network to deploy the Redis cache in. Example
* format:
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1
*/
subnetId?: string;
/**
* Static IP address. Required when deploying a Redis cache inside an existing Azure Virtual
* Network.
*/
staticIP?: string;
/**
* A list of availability zones denoting where the resource needs to come from.
*/
zones?: string[];
/**
* The geo-location where the resource lives
*/
location: string;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* Parameters supplied to the Update Redis operation.
*/
export interface RedisUpdateParameters {
/**
* All Redis Settings. Few possible keys:
* rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta,maxmemory-policy,notify-keyspace-events,maxmemory-samples,slowlog-log-slower-than,slowlog-max-len,list-max-ziplist-entries,list-max-ziplist-value,hash-max-ziplist-entries,hash-max-ziplist-value,set-max-intset-entries,zset-max-ziplist-entries,zset-max-ziplist-value
* etc.
*/
redisConfiguration?: { [propertyName: string]: string };
/**
* Specifies whether the non-ssl Redis server port (6379) is enabled.
*/
enableNonSslPort?: boolean;
/**
* A dictionary of tenant settings
*/
tenantSettings?: { [propertyName: string]: string };
/**
* The number of shards to be created on a Premium Cluster Cache.
*/
shardCount?: number;
/**
* Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0',
* '1.1', '1.2'). Possible values include: '1.0', '1.1', '1.2'
*/
minimumTlsVersion?: string;
/**
* The SKU of the Redis cache to deploy.
*/
sku?: Sku;
/**
* Resource tags.
*/
tags?: { [propertyName: string]: string };
}
/**
* Specifies a range of IP addresses permitted to connect to the cache
*/
export interface RedisFirewallRuleProperties {
/**
* lowest IP address included in the range
*/
startIP: string;
/**
* highest IP address included in the range
*/
endIP: string;
}
/**
* A firewall rule on a redis cache has a name, and describes a contiguous range of IP addresses
* permitted to connect
*/
export interface RedisFirewallRule extends ProxyResource {
/**
* lowest IP address included in the range
*/
startIP: string;
/**
* highest IP address included in the range
*/
endIP: string;
}
/**
* Parameters required for creating a firewall rule on redis cache.
*/
export interface RedisFirewallRuleCreateParameters {
/**
* lowest IP address included in the range
*/
startIP: string;
/**
* highest IP address included in the range
*/
endIP: string;
}
/**
* A single Redis item in List or Get Operation.
*/
export interface RedisResource extends TrackedResource {
/**
* All Redis Settings. Few possible keys:
* rdb-backup-enabled,rdb-storage-connection-string,rdb-backup-frequency,maxmemory-delta,maxmemory-policy,notify-keyspace-events,maxmemory-samples,slowlog-log-slower-than,slowlog-max-len,list-max-ziplist-entries,list-max-ziplist-value,hash-max-ziplist-entries,hash-max-ziplist-value,set-max-intset-entries,zset-max-ziplist-entries,zset-max-ziplist-value
* etc.
*/
redisConfiguration?: { [propertyName: string]: string };
/**
* Specifies whether the non-ssl Redis server port (6379) is enabled.
*/
enableNonSslPort?: boolean;
/**
* A dictionary of tenant settings
*/
tenantSettings?: { [propertyName: string]: string };
/**
* The number of shards to be created on a Premium Cluster Cache.
*/
shardCount?: number;
/**
* Optional: requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0',
* '1.1', '1.2'). Possible values include: '1.0', '1.1', '1.2'
*/
minimumTlsVersion?: string;
/**
* The SKU of the Redis cache to deploy.
*/
sku: Sku;
/**
* The full resource ID of a subnet in a virtual network to deploy the Redis cache in. Example
* format:
* /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/Microsoft.{Network|ClassicNetwork}/VirtualNetworks/vnet1/subnets/subnet1
*/
subnetId?: string;
/**
* Static IP address. Required when deploying a Redis cache inside an existing Azure Virtual
* Network.
*/
staticIP?: string;
/**
* Redis version.
*/
readonly redisVersion?: string;
/**
* Redis instance provisioning status. Possible values include: 'Creating', 'Deleting',
* 'Disabled', 'Failed', 'Linking', 'Provisioning', 'RecoveringScaleFailure', 'Scaling',
* 'Succeeded', 'Unlinking', 'Unprovisioning', 'Updating'
*/
readonly provisioningState?: string;
/**
* Redis host name.
*/
readonly hostName?: string;
/**
* Redis non-SSL port.
*/
readonly port?: number;
/**
* Redis SSL port.
*/
readonly sslPort?: number;
/**
* The keys of the Redis cache - not set if this object is not the response to Create or Update
* redis cache
*/
readonly accessKeys?: RedisAccessKeys;
/**
* List of the linked servers associated with the cache
*/
readonly linkedServers?: RedisLinkedServer[];
/**
* A list of availability zones denoting where the resource needs to come from.
*/
zones?: string[];
}
/**
* Specifies which Redis access keys to reset.
*/
export interface RedisRegenerateKeyParameters {
/**
* The Redis access key to regenerate. Possible values include: 'Primary', 'Secondary'
*/
keyType: string;
}
/**
* Specifies which Redis node(s) to reboot.
*/
export interface RedisRebootParameters {
/**
* Which Redis node(s) to reboot. Depending on this value data loss is possible. Possible values
* include: 'PrimaryNode', 'SecondaryNode', 'AllNodes'
*/
rebootType: string;
/**
* If clustering is enabled, the ID of the shard to be rebooted.
*/
shardId?: number;
}
/**
* Parameters for Redis export operation.
*/
export interface ExportRDBParameters {
/**
* File format.
*/
format?: string;
/**
* Prefix to use for exported files.
*/
prefix: string;
/**
* Container name to export to.
*/
container: string;
}
/**
* Parameters for Redis import operation.
*/
export interface ImportRDBParameters {
/**
* File format.
*/
format?: string;
/**
* files to import.
*/
files: string[];
}
/**
* Patch schedule entry for a Premium Redis Cache.
*/
export interface ScheduleEntry {
/**
* Day of the week when a cache can be patched. Possible values include: 'Monday', 'Tuesday',
* 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Everyday', 'Weekend'
*/
dayOfWeek: string;
/**
* Start hour after which cache patching can start.
*/
startHourUtc: number;
/**
* ISO8601 timespan specifying how much time cache patching can take.
*/
maintenanceWindow?: moment.Duration;
}
/**
* List of patch schedules for a Redis cache.
*/
export interface ScheduleEntries {
/**
* List of patch schedules for a Redis cache.
*/
scheduleEntries: ScheduleEntry[];
}
/**
* Response to put/get patch schedules for Redis cache.
*/
export interface RedisPatchSchedule extends ProxyResource {
/**
* List of patch schedules for a Redis cache.
*/
scheduleEntries: ScheduleEntry[];
}
/**
* Response to force reboot for Redis cache.
*/
export interface RedisForceRebootResponse {
/**
* Status message
*/
readonly message?: string;
}
/**
* Create properties for a linked server
*/
export interface RedisLinkedServerCreateProperties {
/**
* Fully qualified resourceId of the linked redis cache.
*/
linkedRedisCacheId: string;
/**
* Location of the linked redis cache.
*/
linkedRedisCacheLocation: string;
/**
* Role of the linked server. Possible values include: 'Primary', 'Secondary'
*/
serverRole: string;
}
/**
* Properties of a linked server to be returned in get/put response
*/
export interface RedisLinkedServerProperties extends RedisLinkedServerCreateProperties {
/**
* Terminal state of the link between primary and secondary redis cache.
*/
readonly provisioningState?: string;
}
/**
* Response to put/get linked server (with properties) for Redis cache.
*/
export interface RedisLinkedServerWithProperties extends ProxyResource {
/**
* Fully qualified resourceId of the linked redis cache.
*/
linkedRedisCacheId: string;
/**
* Location of the linked redis cache.
*/
linkedRedisCacheLocation: string;
/**
* Role of the linked server. Possible values include: 'Primary', 'Secondary'
*/
serverRole: string;
/**
* Terminal state of the link between primary and secondary redis cache.
*/
readonly provisioningState?: string;
}
/**
* Parameter required for creating a linked server to redis cache.
*/
export interface RedisLinkedServerCreateParameters {
/**
* Fully qualified resourceId of the linked redis cache.
*/
linkedRedisCacheId: string;
/**
* Location of the linked redis cache.
*/
linkedRedisCacheLocation: string;
/**
* Role of the linked server. Possible values include: 'Primary', 'Secondary'
*/
serverRole: string;
}
/**
* The object that describes the operation.
*/
export interface OperationDisplay {
/**
* Friendly name of the resource provider
*/
provider?: string;
/**
* Operation type: read, write, delete, listKeys/action, etc.
*/
operation?: string;
/**
* Resource type on which the operation is performed.
*/
resource?: string;
/**
* Friendly name of the operation
*/
description?: string;
}
/**
* REST API operation
*/
export interface Operation {
/**
* Operation name: {provider}/{resource}/{operation}
*/
name?: string;
/**
* The object that describes the operation.
*/
display?: OperationDisplay;
}
/**
* Parameters body to pass for resource name availability check.
*/
export interface CheckNameAvailabilityParameters {
/**
* Resource name.
*/
name: string;
/**
* Resource type. The only legal value of this property for checking redis cache name
* availability is 'Microsoft.Cache/redis'.
*/
type: string;
}
/**
* Properties of upgrade notification.
*/
export interface UpgradeNotification {
/**
* Name of upgrade notification.
*/
readonly name?: string;
/**
* Timestamp when upgrade notification occurred.
*/
readonly timestamp?: Date;
/**
* Details about this upgrade notification
*/
readonly upsellNotification?: { [propertyName: string]: string };
}
/**
* The response of listUpgradeNotifications.
*/
export interface NotificationListResponse {
/**
* List of all notifications.
*/
value?: UpgradeNotification[];
/**
* Link for next set of notifications.
*/
readonly nextLink?: string;
}
/**
* Result of the request to list REST API operations. It contains a list of operations and a URL
* nextLink to get the next set of results.
*/
export interface OperationListResult extends Array<Operation> {
/**
* URL to get the next set of operation list results if there are any.
*/
readonly nextLink?: string;
}
/**
* The response of list Redis operation.
*/
export interface RedisListResult extends Array<RedisResource> {
/**
* Link for next page of results.
*/
readonly nextLink?: string;
}
/**
* The response of list firewall rules Redis operation.
*/
export interface RedisFirewallRuleListResult extends Array<RedisFirewallRule> {
/**
* Link for next page of results.
*/
readonly nextLink?: string;
}
/**
* The response of list patch schedules Redis operation.
*/
export interface RedisPatchScheduleListResult extends Array<RedisPatchSchedule> {
/**
* Link for next page of results.
*/
readonly nextLink?: string;
}
/**
* List of linked servers (with properties) of a Redis cache.
*/
export interface RedisLinkedServerWithPropertiesList extends Array<RedisLinkedServerWithProperties> {
/**
* Link for next set.
*/
readonly nextLink?: string;
} | the_stack |
import { AnimationEvent } from '@angular/animations';
import { FocusOrigin } from '@angular/cdk/a11y';
import { Direction } from '@angular/cdk/bidi';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { DOWN_ARROW, UP_ARROW } from '@angular/cdk/keycodes';
import {
AfterContentInit,
ChangeDetectionStrategy,
Component,
ContentChild,
ContentChildren,
ElementRef,
EventEmitter,
Inject,
Input,
NgZone,
OnDestroy,
Output,
TemplateRef,
QueryList,
ViewChild,
ViewEncapsulation,
OnInit
} from '@angular/core';
import { FocusKeyManager } from '@ptsecurity/cdk/a11y';
import { ESCAPE, LEFT_ARROW, RIGHT_ARROW } from '@ptsecurity/cdk/keycodes';
import { merge, Observable, Subject, Subscription } from 'rxjs';
import { startWith, switchMap, take } from 'rxjs/operators';
import { mcDropdownAnimations } from './dropdown-animations';
import { McDropdownContent } from './dropdown-content.directive';
import { throwMcDropdownInvalidPositionX, throwMcDropdownInvalidPositionY } from './dropdown-errors';
import { McDropdownItem } from './dropdown-item.component';
import {
DropdownPositionX,
DropdownPositionY,
MC_DROPDOWN_DEFAULT_OPTIONS,
MC_DROPDOWN_PANEL,
McDropdownDefaultOptions,
McDropdownPanel
} from './dropdown.types';
@Component({
selector: 'mc-dropdown',
exportAs: 'mcDropdown',
templateUrl: 'dropdown.html',
styleUrls: ['dropdown.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
animations: [
mcDropdownAnimations.transformDropdown,
mcDropdownAnimations.fadeInItems
],
providers: [
{ provide: MC_DROPDOWN_PANEL, useExisting: McDropdown }
]
})
export class McDropdown implements AfterContentInit, McDropdownPanel, OnInit, OnDestroy {
@Input() navigationWithWrap: boolean = false;
/** Position of the dropdown in the X axis. */
@Input()
get xPosition(): DropdownPositionX {
return this._xPosition;
}
set xPosition(value: DropdownPositionX) {
if (value !== 'before' && value !== 'after') {
throwMcDropdownInvalidPositionX();
}
this._xPosition = value;
this.setPositionClasses();
}
/** Position of the dropdown in the Y axis. */
@Input()
get yPosition(): DropdownPositionY {
return this._yPosition;
}
set yPosition(value: DropdownPositionY) {
if (value !== 'above' && value !== 'below') {
throwMcDropdownInvalidPositionY();
}
this._yPosition = value;
this.setPositionClasses();
}
/** Whether the dropdown should overlap its trigger vertically. */
@Input()
get overlapTriggerY(): boolean {
return this._overlapTriggerY;
}
set overlapTriggerY(value: boolean) {
this._overlapTriggerY = coerceBooleanProperty(value);
}
/** Whether the dropdown should overlap its trigger horizontally. */
@Input()
get overlapTriggerX(): boolean {
return this._overlapTriggerX;
}
set overlapTriggerX(value: boolean) {
this._overlapTriggerX = coerceBooleanProperty(value);
}
/** Whether the dropdown has a backdrop. */
@Input()
get hasBackdrop(): boolean {
return this._hasBackdrop;
}
set hasBackdrop(value: boolean) {
this._hasBackdrop = coerceBooleanProperty(value);
}
/**
* This method takes classes set on the host mc-dropdown element and applies them on the
* dropdown template that displays in the overlay container. Otherwise, it's difficult
* to style the containing dropdown from outside the component.
* @param classes list of class names
*/
@Input('class')
set panelClass(classes: string) {
const previousPanelClass = this.previousPanelClass;
if (previousPanelClass && previousPanelClass.length) {
previousPanelClass
.split(' ')
.forEach((className: string) => this.classList[className] = false);
}
this.previousPanelClass = classes;
if (classes?.length) {
classes
.split(' ')
.forEach((className: string) => this.classList[className] = true);
this.elementRef.nativeElement.className = '';
}
}
private _xPosition: DropdownPositionX = this.defaultOptions.xPosition;
private _yPosition: DropdownPositionY = this.defaultOptions.yPosition;
private _overlapTriggerX: boolean = this.defaultOptions.overlapTriggerX;
private _overlapTriggerY: boolean = this.defaultOptions.overlapTriggerY;
private _hasBackdrop: boolean = this.defaultOptions.hasBackdrop;
triggerWidth: string = '';
/** Config object to be passed into the dropdown's ngClass */
classList: { [key: string]: boolean } = {};
/** Current state of the panel animation. */
panelAnimationState: 'void' | 'enter' = 'void';
/** Emits whenever an animation on the dropdown completes. */
animationDone = new Subject<AnimationEvent>();
/** Whether the dropdown is animating. */
isAnimating: boolean;
/** Parent dropdown of the current dropdown panel. */
parent: McDropdownPanel | undefined;
/** Layout direction of the dropdown. */
direction: Direction;
/** Class to be added to the backdrop element. */
@Input() backdropClass: string = this.defaultOptions.backdropClass;
/** @docs-private */
@ViewChild(TemplateRef, { static: false }) templateRef: TemplateRef<any>;
/**
* List of the items inside of a dropdown.
*/
@ContentChildren(McDropdownItem, { descendants: true }) items: QueryList<McDropdownItem>;
/**
* Dropdown content that will be rendered lazily.
* @docs-private
*/
@ContentChild(McDropdownContent, { static: false }) lazyContent: McDropdownContent;
/** Event emitted when the dropdown is closed. */
@Output() readonly closed = new EventEmitter<void | 'click' | 'keydown' | 'tab'>();
private previousPanelClass: string;
private keyManager: FocusKeyManager<McDropdownItem>;
/** Only the direct descendant menu items. */
private directDescendantItems = new QueryList<McDropdownItem>();
/** Subscription to tab events on the dropdown panel */
private tabSubscription = Subscription.EMPTY;
constructor(
private elementRef: ElementRef<HTMLElement>,
private ngZone: NgZone,
@Inject(MC_DROPDOWN_DEFAULT_OPTIONS) private defaultOptions: McDropdownDefaultOptions) { }
ngOnInit() {
this.setPositionClasses();
}
ngAfterContentInit() {
this.updateDirectDescendants();
this.keyManager = new FocusKeyManager<McDropdownItem>(this.directDescendantItems)
.withTypeAhead();
if (this.navigationWithWrap) {
this.keyManager.withWrap();
}
this.tabSubscription = this.keyManager.tabOut
.subscribe(() => this.closed.emit('tab'));
// If a user manually (programmatically) focuses a menu item, we need to reflect that focus
// change back to the key manager. Note that we don't need to unsubscribe here because focused
// is internal and we know that it gets completed on destroy.
this.directDescendantItems.changes
.pipe(
startWith(this.directDescendantItems),
switchMap((items) => merge(...items.map((item: McDropdownItem) => item.focused)))
)
.subscribe((focusedItem) => this.keyManager.updateActiveItem(focusedItem as McDropdownItem));
}
ngOnDestroy() {
this.directDescendantItems.destroy();
this.tabSubscription.unsubscribe();
this.closed.complete();
}
/** Stream that emits whenever the hovered dropdown item changes. */
hovered(): Observable<McDropdownItem> {
const itemChanges = this.directDescendantItems.changes as Observable<QueryList<McDropdownItem>>;
return itemChanges.pipe(
startWith(this.directDescendantItems),
switchMap((items) => merge(...items.map((item: McDropdownItem) => item.hovered)))
) as Observable<McDropdownItem>;
}
/** Handle a keyboard event from the dropdown, delegating to the appropriate action. */
handleKeydown(event: KeyboardEvent) {
// tslint:disable-next-line:deprecation
const keyCode = event.keyCode;
switch (keyCode) {
case ESCAPE:
this.closed.emit('keydown');
break;
case LEFT_ARROW:
if (this.parent && this.direction === 'ltr') {
this.closed.emit('keydown');
}
break;
case RIGHT_ARROW:
if (this.parent && this.direction === 'rtl') {
this.closed.emit('keydown');
}
break;
default:
if (keyCode === UP_ARROW || keyCode === DOWN_ARROW) {
this.keyManager.setFocusOrigin('keyboard');
}
this.keyManager.onKeydown(event);
return;
}
// Don't allow the event to propagate if we've already handled it, or it may
// end up reaching other overlays that were opened earlier.
event.stopPropagation();
}
/**
* Focus the first item in the dropdown.
* @param origin Action from which the focus originated. Used to set the correct styling.
*/
focusFirstItem(origin: FocusOrigin = 'program'): void {
// When the content is rendered lazily, it takes a bit before the items are inside the DOM.
if (this.lazyContent) {
this.ngZone.onStable
.pipe(take(1))
.subscribe(() => this.keyManager.setFocusOrigin(origin).setFirstItemActive());
} else {
this.keyManager.setFocusOrigin(origin).setFirstItemActive();
}
}
/**
* Resets the active item in the dropdown. This is used when the dropdown is opened, allowing
* the user to start from the first option when pressing the down arrow.
*/
resetActiveItem() {
this.keyManager.activeItem?.resetStyles();
this.keyManager.setActiveItem(-1);
}
/**
* Adds classes to the dropdown panel based on its position. Can be used by
* consumers to add specific styling based on the position.
* @param posX Position of the dropdown along the x axis.
* @param posY Position of the dropdown along the y axis.
* @docs-private
*/
setPositionClasses(posX: DropdownPositionX = this.xPosition, posY: DropdownPositionY = this.yPosition) {
const classes = this.classList;
classes['mc-dropdown-before'] = posX === 'before';
classes['mc-dropdown-after'] = posX === 'after';
classes['mc-dropdown-above'] = posY === 'above';
classes['mc-dropdown-below'] = posY === 'below';
}
/** Starts the enter animation. */
startAnimation() {
this.panelAnimationState = 'enter';
}
/** Resets the panel animation to its initial state. */
resetAnimation() {
this.panelAnimationState = 'void';
}
/** Callback that is invoked when the panel animation completes. */
onAnimationDone(event: AnimationEvent) {
this.animationDone.next(event);
this.isAnimating = false;
}
onAnimationStart(event: AnimationEvent) {
this.isAnimating = true;
// Scroll the content element to the top as soon as the animation starts. This is necessary,
// because we move focus to the first item while it's still being animated, which can throw
// the browser off when it determines the scroll position. Alternatively we can move focus
// when the animation is done, however moving focus asynchronously will interrupt screen
// readers which are in the process of reading out the dropdown already. We take the `element`
// from the `event` since we can't use a `ViewChild` to access the pane.
if (event.toState === 'enter' && this.keyManager.activeItemIndex === 0) {
event.element.scrollTop = 0;
}
}
close() {
const focusOrigin = this.keyManager.getFocusOrigin() === 'keyboard' ? 'keydown' : 'click';
this.closed.emit(focusOrigin);
}
/**
* Sets up a stream that will keep track of any newly-added menu items and will update the list
* of direct descendants. We collect the descendants this way, because `_allItems` can include
* items that are part of child menus, and using a custom way of registering items is unreliable
* when it comes to maintaining the item order.
*/
private updateDirectDescendants() {
this.items.changes
.pipe(startWith(this.items))
.subscribe((items: QueryList<McDropdownItem>) => {
this.directDescendantItems.reset(items.filter((item) => item.parentDropdownPanel === this));
this.directDescendantItems.notifyOnChanges();
});
}
} | the_stack |
import * as React from 'react';
import NetInfo, { NetInfoStateType } from '@react-native-community/netinfo';
import { AppState, Platform, View } from 'react-native';
import { shallow } from 'enzyme';
import { render } from 'react-native-testing-library';
import NetworkConnectivity, {
RequiredProps,
} from '../src/components/NetworkConnectivity';
import { clear, setup } from '../src/utils/checkConnectivityInterval';
import checkInternetAccess from '../src/utils/checkInternetAccess';
import entries from '../src/utils/objectEntries';
import { DEFAULT_CUSTOM_HEADERS } from '../src/utils/constants';
type OptionalProps = Omit<RequiredProps, 'children'>;
type GetElementParams<P = any> = {
props?: Pick<RequiredProps, 'children'> & Partial<OptionalProps>;
Component?: React.ComponentType<P>;
};
interface MethodsMap {
getConnectionChangeHandler?: any;
intervalHandler?: any;
setState?: any;
}
const mockConnectionChangeHandler = jest.fn();
const mockGetConnectionChangeHandler = jest.fn(
() => mockConnectionChangeHandler,
);
const mockIntervalHandler = jest.fn();
const mockHandleNetInfoChange = jest.fn();
const mockHandleConnectivityChange = jest.fn();
const mockCheckInternet = jest.fn();
const addEventListener = NetInfo.addEventListener as jest.Mock;
const unsubscribe = jest.fn();
const fetch = NetInfo.fetch as jest.Mock;
jest.mock('../src/utils/checkConnectivityInterval');
jest.mock('../src/utils/checkInternetAccess', () =>
jest.fn().mockResolvedValue(true),
);
/**
* Helper function that creates a class that extends NetworkConnectivity
* and mocks the specific methods on the prototype,
* in order to not affect the rest of the tests
* @param methodsMap
* @returns {ClassWithMocks}
*/
function mockPrototypeMethods(methodsMap: MethodsMap = {} as MethodsMap) {
class ClassWithMocks extends NetworkConnectivity {}
entries(methodsMap).forEach(
([method, mockFn]) => (ClassWithMocks.prototype[method] = mockFn),
);
return ClassWithMocks;
}
const ChildrenComponent = () => <View />;
const initialProps = {
children: ChildrenComponent,
};
const getElement = ({
props = initialProps,
Component = NetworkConnectivity,
}: GetElementParams = {}) => {
const { children, ...rest } = props;
return <Component {...rest}>{children}</Component>;
};
describe('NetworkConnectivity', () => {
afterEach(() => {
addEventListener.mockClear();
fetch.mockClear();
mockConnectionChangeHandler.mockClear();
mockGetConnectionChangeHandler.mockClear();
mockIntervalHandler.mockClear();
mockHandleNetInfoChange.mockClear();
mockHandleConnectivityChange.mockClear();
mockCheckInternet.mockClear();
});
it('defaultProps', () => {
expect(NetworkConnectivity.defaultProps).toMatchSnapshot();
});
it('passes the connection state into the FACC', () => {
const children = jest.fn();
shallow(getElement({ props: { children } }));
expect(children).toHaveBeenCalledWith({ isConnected: null });
});
describe('componentDidMount', () => {
describe('iOS, pingInterval = 0', () => {
it(`sets up a NetInfo.isConnected listener for connectionChange
AND does NOT call setupConnectivityCheckInterval`, () => {
Platform.OS = 'ios';
const MockedNetworkConnectivity = mockPrototypeMethods({
getConnectionChangeHandler: mockGetConnectionChangeHandler,
});
shallow(
getElement({
Component: MockedNetworkConnectivity,
}),
);
expect(NetInfo.addEventListener).toHaveBeenCalledTimes(1);
expect(NetInfo.addEventListener).toHaveBeenCalledWith(
mockConnectionChangeHandler,
);
expect(setup).not.toHaveBeenCalled();
});
});
describe('Android, pingInterval = 0', () => {
it(`sets up a NetInfo.isConnected listener for connectionChange
AND fetches initial connection
AND calls the handler
AND does NOT call setupConnectivityCheckInterval`, (done: Function) => {
fetch.mockImplementationOnce(() => Promise.resolve(false));
Platform.OS = 'android';
const MockedNetworkConnectivity = mockPrototypeMethods({
getConnectionChangeHandler: mockGetConnectionChangeHandler,
});
shallow(
getElement({
Component: MockedNetworkConnectivity,
}),
);
expect(NetInfo.addEventListener).toHaveBeenCalledTimes(1);
expect(NetInfo.addEventListener).toHaveBeenCalledWith(
mockConnectionChangeHandler,
);
expect(NetInfo.fetch).toHaveBeenCalledTimes(1);
process.nextTick(() => {
expect(mockConnectionChangeHandler).toHaveBeenCalledWith(false);
expect(setup).not.toHaveBeenCalled();
done();
});
});
});
it(`calls setupConnectivityCheckInterval with the right arguments
WHEN pingInterval is higher than 0`, () => {
Platform.OS = 'ios';
const MockedNetworkConnectivity = mockPrototypeMethods({
intervalHandler: mockIntervalHandler,
});
shallow(
getElement({
Component: MockedNetworkConnectivity,
props: {
children: ChildrenComponent,
pingInterval: 1000,
},
}),
);
expect(setup).toHaveBeenCalled();
});
});
describe('componentWillUnmount', () => {
it(`removes the NetInfo listener with the right parameters
AND call connectivityInterval.clear`, () => {
(NetInfo.addEventListener as jest.Mock).mockReturnValueOnce(unsubscribe);
const MockedNetworkConnectivity = mockPrototypeMethods({
getConnectionChangeHandler: mockGetConnectionChangeHandler,
});
const wrapper = shallow(
getElement({
Component: MockedNetworkConnectivity,
}),
);
wrapper.unmount();
expect(unsubscribe).toHaveBeenCalledTimes(1);
expect(clear).toHaveBeenCalled();
});
});
describe('getConnectionChangeHandler', () => {
it('returns this.handleNetInfoChange when props.shouldPing = true', () => {
const wrapper = shallow<NetworkConnectivity>(
getElement({
props: {
children: ChildrenComponent,
shouldPing: true,
},
}),
);
wrapper.instance().handleNetInfoChange = mockHandleNetInfoChange;
expect(wrapper.instance().getConnectionChangeHandler()).toBe(
mockHandleNetInfoChange,
);
});
it('returns this.handleConnectivityChange when props.shouldPing = false', () => {
const wrapper = shallow<NetworkConnectivity>(
getElement({
props: {
children: ChildrenComponent,
shouldPing: false,
},
}),
);
wrapper.instance().handleConnectivityChange = mockHandleConnectivityChange;
expect(wrapper.instance().getConnectionChangeHandler()).toBe(
mockHandleConnectivityChange,
);
});
});
describe('handleNetInfoChange', () => {
it('calls handleConnectivityChange if isConnected is false', () => {
const wrapper = shallow<NetworkConnectivity>(getElement());
wrapper.instance().handleConnectivityChange = mockHandleConnectivityChange;
wrapper.instance().checkInternet = mockCheckInternet;
wrapper.instance().handleNetInfoChange({
type: 'none' as NetInfoStateType.none,
isConnected: false,
isInternetReachable: false,
details: null,
});
expect(mockHandleConnectivityChange).toHaveBeenCalledWith({
type: 'none' as NetInfoStateType.none,
isConnected: false,
isInternetReachable: false,
details: null,
});
expect(mockCheckInternet).not.toHaveBeenCalled();
});
it('calls checkInternet if isConnected is true', () => {
const wrapper = shallow<NetworkConnectivity>(getElement());
wrapper.instance().handleConnectivityChange = mockHandleConnectivityChange;
wrapper.instance().checkInternet = mockCheckInternet;
wrapper.instance().handleNetInfoChange({
type: 'other' as NetInfoStateType.other,
isConnected: true,
isInternetReachable: true,
details: {
cellularGeneration: null,
isConnectionExpensive: false,
},
});
expect(mockHandleConnectivityChange).not.toHaveBeenCalled();
expect(mockCheckInternet).toHaveBeenCalled();
});
});
describe('checkInternet', () => {
it('returns early if pingIfBackground = false AND app is not in the foreground', async () => {
AppState.currentState = 'background';
const wrapper = shallow<NetworkConnectivity>(
getElement({
props: {
children: ChildrenComponent,
pingInBackground: false,
},
}),
);
wrapper.instance().handleConnectivityChange = mockHandleConnectivityChange;
await wrapper.instance().checkInternet();
expect(checkInternetAccess).not.toHaveBeenCalled();
expect(mockHandleConnectivityChange).not.toHaveBeenCalled();
});
it(`calls checkInternetAccess AND handleConnectivityChange
with the right arguments if app is in foreground`, async () => {
const props = {
pingTimeout: 2000,
pingServerUrl: 'dummy.com',
httpMethod: 'OPTIONS' as 'OPTIONS',
children: ChildrenComponent,
customHeaders: DEFAULT_CUSTOM_HEADERS,
};
AppState.currentState = 'active';
const wrapper = shallow<NetworkConnectivity>(
getElement({
props,
}),
);
wrapper.instance().handleConnectivityChange = mockHandleConnectivityChange;
await wrapper.instance().checkInternet();
expect(checkInternetAccess).toHaveBeenCalledWith({
url: props.pingServerUrl,
timeout: props.pingTimeout,
method: props.httpMethod,
customHeaders: props.customHeaders,
});
expect(mockHandleConnectivityChange).toHaveBeenCalledWith({
isConnected: true,
});
});
});
describe('intervalHandler', () => {
it('returns early if there is connection AND pingOnlyIfOffline = true', () => {
const wrapper = shallow<NetworkConnectivity>(
getElement({
props: {
children: ChildrenComponent,
pingOnlyIfOffline: true,
},
}),
);
wrapper.instance().checkInternet = mockCheckInternet;
wrapper.setState({ isConnected: true });
wrapper.instance().intervalHandler();
expect(mockCheckInternet).not.toHaveBeenCalled();
});
it(`calls checkInternet if it's not connected OR pingOnlyIfOffline = false`, () => {
const wrapper = shallow<NetworkConnectivity>(
getElement({
props: {
children: ChildrenComponent,
pingOnlyIfOffline: false,
},
}),
);
wrapper.instance().checkInternet = mockCheckInternet;
wrapper.setState({ isConnected: false });
wrapper.instance().intervalHandler();
expect(mockCheckInternet).toHaveBeenCalledTimes(1);
wrapper.setState({ isConnected: true });
wrapper.instance().intervalHandler();
expect(mockCheckInternet).toHaveBeenCalledTimes(2);
});
});
describe('handleConnectivityChange', () => {
it('calls setState with the new connection value', () => {
const mockSetState = jest.fn();
const MockedNetworkConnectivity = mockPrototypeMethods({
setState: mockSetState,
});
const wrapper = shallow<NetworkConnectivity>(
getElement({
Component: MockedNetworkConnectivity,
}),
);
wrapper.instance().handleConnectivityChange({
type: 'other' as NetInfoStateType.other,
isConnected: true,
isInternetReachable: true,
details: {
cellularGeneration: null,
isConnectionExpensive: false,
},
});
expect(mockSetState).toHaveBeenCalledWith({ isConnected: true });
wrapper.instance().handleConnectivityChange({
type: 'none' as NetInfoStateType.none,
isConnected: false,
isInternetReachable: false,
details: null,
});
expect(mockSetState).toHaveBeenCalledWith({ isConnected: false });
});
});
describe('pingUrlChange', () => {
it('calls checkInternet if pingServerUrl changes', () => {
const wrapper = shallow<NetworkConnectivity>(getElement());
wrapper.instance().checkInternet = mockCheckInternet;
expect(mockCheckInternet).not.toHaveBeenCalled();
wrapper.setProps({ pingServerUrl: 'https://newServerToPing.com' });
expect(mockCheckInternet).toHaveBeenCalled();
});
});
describe('props validation', () => {
it('throws if prop pingTimeout is not a number', () => {
expect(() =>
render(
// @ts-ignore
getElement({
props: { pingTimeout: '4000', children: ChildrenComponent },
}),
),
).toThrow('you should pass a number as pingTimeout parameter');
});
it('throws if prop pingServerUrl is not a string', () => {
expect(() =>
render(
// @ts-ignore
getElement({
props: { pingServerUrl: 90, children: ChildrenComponent },
}),
),
).toThrow('you should pass a string as pingServerUrl parameter');
});
it('throws if prop shouldPing is not a boolean', () => {
expect(() =>
render(
// @ts-ignore
getElement({
props: { shouldPing: () => null, children: ChildrenComponent },
}),
),
).toThrow('you should pass a boolean as shouldPing parameter');
});
it('throws if prop pingInterval is not a number', () => {
expect(() =>
render(
// @ts-ignore
getElement({
props: { pingInterval: false, children: ChildrenComponent },
}),
),
).toThrow('you should pass a number as pingInterval parameter');
});
it('throws if prop pingOnlyIfOffline is not a boolean', () => {
expect(() =>
render(
// @ts-ignore
getElement({
props: { pingOnlyIfOffline: 10, children: ChildrenComponent },
}),
),
).toThrow('you should pass a boolean as pingOnlyIfOffline parameter');
});
it('throws if prop pingInBackground is not a boolean', () => {
expect(() =>
render(
// @ts-ignore
getElement({
props: { pingInBackground: '4000', children: ChildrenComponent },
}),
),
).toThrow('you should pass a string as pingServerUrl parameter');
});
it('throws if prop httpMethod is not either HEAD or OPTIONS', () => {
expect(() =>
render(
// @ts-ignore
getElement({
props: { httpMethod: 'POST', children: ChildrenComponent },
}),
),
).toThrow('httpMethod parameter should be either HEAD or OPTIONS');
});
it('throws if prop onConnectivityChange is not a function', () => {
expect(() =>
render(
// @ts-ignore
getElement({
props: { onConnectivityChange: 'foo', children: ChildrenComponent },
}),
),
).toThrow('you should pass a function as onConnectivityChange parameter');
});
});
}); | the_stack |
import { matchRightIncl } from "string-match-left-right";
import { arrayiffy } from "arrayiffy-if-string";
import { version as v } from "../package.json";
const version: string = v;
function isObj(something: any): boolean {
return (
something && typeof something === "object" && !Array.isArray(something)
);
}
function isStr(something: any): boolean {
return typeof something === "string";
}
interface Opts {
fromIndex?: number;
throwWhenSomethingWrongIsDetected?: boolean;
allowWholeValueToBeOnlyHeadsOrTails?: boolean;
source?: string;
matchHeadsAndTailsStrictlyInPairsByTheirOrder?: boolean;
relaxedAPI?: boolean;
}
const defaults = {
fromIndex: 0,
throwWhenSomethingWrongIsDetected: true,
allowWholeValueToBeOnlyHeadsOrTails: true,
source: "string-find-heads-tails",
matchHeadsAndTailsStrictlyInPairsByTheirOrder: false,
relaxedAPI: false,
};
interface ResObj {
headsStartAt: number;
headsEndAt: number;
tailsStartAt: number;
tailsEndAt: number;
}
function strFindHeadsTails(
str: string,
heads: string | string[],
tails: string | string[],
originalOpts?: Opts
): ResObj[] {
// prep opts
if (originalOpts && !isObj(originalOpts)) {
throw new TypeError(
`string-find-heads-tails: [THROW_ID_01] the fourth input argument, an Optional Options Object, must be a plain object! Currently it's equal to: ${originalOpts} (type: ${typeof originalOpts})`
);
}
const opts = { ...defaults, ...originalOpts };
if (typeof opts.fromIndex === "string" && /^\d*$/.test(opts.fromIndex)) {
opts.fromIndex = Number(opts.fromIndex);
} else if (!Number.isInteger(opts.fromIndex) || opts.fromIndex < 0) {
throw new TypeError(
`${opts.source} [THROW_ID_18] the fourth input argument must be a natural number or zero! Currently it's: ${opts.fromIndex}`
);
}
console.log(
`063 FINAL ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify(
opts,
null,
4
)}`
);
//
// insurance
// ---------
if (!isStr(str) || str.length === 0) {
if (opts.relaxedAPI) {
return [];
}
throw new TypeError(
`string-find-heads-tails: [THROW_ID_02] the first input argument, input string, must be a non-zero-length string! Currently it's: ${typeof str}, equal to: ${str}`
);
}
let culpritsVal;
let culpritsIndex;
// - for heads
if (typeof heads !== "string" && !Array.isArray(heads)) {
if (opts.relaxedAPI) {
return [];
}
throw new TypeError(
`string-find-heads-tails: [THROW_ID_03] the second input argument, heads, must be either a string or an array of strings! Currently it's: ${typeof heads}, equal to:\n${JSON.stringify(
heads,
null,
4
)}`
);
} else if (typeof heads === "string") {
if (heads.length === 0) {
if (opts.relaxedAPI) {
return [];
}
throw new TypeError(
"string-find-heads-tails: [THROW_ID_04] the second input argument, heads, must be a non-empty string! Currently it's empty."
);
} else {
// eslint-disable-next-line no-param-reassign
heads = arrayiffy(heads);
}
} else if (Array.isArray(heads)) {
if (heads.length === 0) {
if (opts.relaxedAPI) {
return [];
}
throw new TypeError(
"string-find-heads-tails: [THROW_ID_05] the second input argument, heads, must be a non-empty array and contain at least one string! Currently it's empty."
);
} else if (
!heads.every((val, index) => {
culpritsVal = val;
culpritsIndex = index;
return isStr(val);
})
) {
if (opts.relaxedAPI) {
// eslint-disable-next-line no-param-reassign
heads = heads.filter((el) => isStr(el) && el.length > 0);
if (heads.length === 0) {
return [];
}
} else {
throw new TypeError(
`string-find-heads-tails: [THROW_ID_06] the second input argument, heads, contains non-string elements! For example, element at ${culpritsIndex}th index is ${typeof culpritsVal}, equal to:\n${JSON.stringify(
culpritsVal,
null,
4
)}. Whole heads array looks like:\n${JSON.stringify(heads, null, 4)}`
);
}
} else if (
!heads.every((val, index) => {
culpritsIndex = index;
return isStr(val) && val.length > 0 && val.trim() !== "";
})
) {
if (opts.relaxedAPI) {
// eslint-disable-next-line no-param-reassign
heads = heads.filter((el) => isStr(el) && el.length > 0);
if (heads.length === 0) {
return [];
}
} else {
throw new TypeError(
`string-find-heads-tails: [THROW_ID_07] the second input argument, heads, should not contain empty strings! For example, there's one detected at index ${culpritsIndex} of heads array:\n${JSON.stringify(
heads,
null,
4
)}.`
);
}
}
}
// - for tails
if (!isStr(tails) && !Array.isArray(tails)) {
if (opts.relaxedAPI) {
return [];
}
throw new TypeError(
`string-find-heads-tails: [THROW_ID_08] the third input argument, tails, must be either a string or an array of strings! Currently it's: ${typeof tails}, equal to:\n${JSON.stringify(
tails,
null,
4
)}`
);
} else if (isStr(tails)) {
if (tails.length === 0) {
if (opts.relaxedAPI) {
return [];
}
throw new TypeError(
"string-find-heads-tails: [THROW_ID_09] the third input argument, tails, must be a non-empty string! Currently it's empty."
);
} else {
// eslint-disable-next-line no-param-reassign
tails = arrayiffy(tails as any);
}
} else if (Array.isArray(tails)) {
if (tails.length === 0) {
if (opts.relaxedAPI) {
return [];
}
throw new TypeError(
"string-find-heads-tails: [THROW_ID_10] the third input argument, tails, must be a non-empty array and contain at least one string! Currently it's empty."
);
} else if (
!tails.every((val, index) => {
culpritsVal = val;
culpritsIndex = index;
return isStr(val);
})
) {
if (opts.relaxedAPI) {
// eslint-disable-next-line no-param-reassign
tails = tails.filter((el) => isStr(el) && el.length > 0);
if (tails.length === 0) {
return [];
}
} else {
throw new TypeError(
`string-find-heads-tails: [THROW_ID_11] the third input argument, tails, contains non-string elements! For example, element at ${culpritsIndex}th index is ${typeof culpritsVal}, equal to:\n${JSON.stringify(
culpritsVal,
null,
4
)}. Whole tails array is equal to:\n${JSON.stringify(tails, null, 4)}`
);
}
} else if (
!tails.every((val, index) => {
culpritsIndex = index;
return isStr(val) && val.length > 0 && val.trim() !== "";
})
) {
if (opts.relaxedAPI) {
// eslint-disable-next-line no-param-reassign
tails = tails.filter((el) => isStr(el) && el.length > 0);
if (tails.length === 0) {
return [];
}
} else {
throw new TypeError(
`string-find-heads-tails: [THROW_ID_12] the third input argument, tails, should not contain empty strings! For example, there's one detected at index ${culpritsIndex}. Whole tails array is equal to:\n${JSON.stringify(
tails,
null,
4
)}`
);
}
}
}
// inner variable meaning is opts.source the default-one
const s = opts.source === defaults.source;
if (
opts.throwWhenSomethingWrongIsDetected &&
!opts.allowWholeValueToBeOnlyHeadsOrTails
) {
if (arrayiffy(heads as any).includes(str)) {
throw new Error(
`${opts.source}${
s ? ": [THROW_ID_16]" : ""
} the whole input string can't be equal to ${
isStr(heads) ? "" : "one of "
}heads (${str})!`
);
} else if (arrayiffy(tails as any).includes(str)) {
throw new Error(
`${opts.source}${
s ? ": [THROW_ID_17]" : ""
} the whole input string can't be equal to ${
isStr(tails) ? "" : "one of "
}tails (${str})!`
);
}
}
//
// prep stage.
// ----
// We are going to traverse the input string, checking each character one-by-one,
// is it a first character of a sub-string, heads or tails.
// The easy but inefficient algorithm is to traverse the input string, then
// for each of the character, run another loop, slicing and matching, is there
// one of heads or tails on the right of it.
// Let's cut corners a little bit.
// We know that heads and tails often start with special characters, not letters.
// For example, "%%-" and "-%%".
// There might be few types of heads and tails, for example, ones that will be
// further processed (like wrapped with other strings) and ones that won't.
// So, you might have two sets of heads and tails:
// "%%-" and "-%%"; "%%_" and "_%%".
// Notice they're quite similar and don't contain letters.
// Imagine we're traversing the string and looking for above set of heads and
// tails. We're concerned only if the current character is equal to "%", "-" or "_".
// Practically, that "String.charCodeAt(0)" values:
// '%'.charCodeAt(0) = 37
// '-'.charCodeAt(0) = 45
// '_'.charCodeAt(0) = 95
// Since we don't know how many head and tail sets there will be nor their values,
// conceptually, we are going to extract the RANGE OF CHARCODES, in the case above,
// [37, 95].
// This means, we traverse the string and check, is its charcode in range [37, 95].
// If so, then we'll do all slicing/comparing.
// take array of strings, heads, and extract the upper and lower range of indexes
// of their first letters using charCodeAt(0)
const headsAndTailsFirstCharIndexesRange = heads
.concat(tails)
.map((value) => value.charAt(0)) // get first letters
.reduce(
(res, val) => {
if (val.charCodeAt(0) > res[1]) {
return [res[0], val.charCodeAt(0)]; // find the char index of the max char index out of all
}
if (val.charCodeAt(0) < res[0]) {
return [val.charCodeAt(0), res[1]]; // find the char index of the min char index out of all
}
return res;
},
[
heads[0].charCodeAt(0), // base is the 1st char index of 1st el.
heads[0].charCodeAt(0),
]
);
console.log(
`324 headsAndTailsFirstCharIndexesRange = ${JSON.stringify(
headsAndTailsFirstCharIndexesRange,
null,
4
)}`
);
const res = [];
let oneHeadFound = false;
let tempResObj: Partial<ResObj> = {};
let tailSuspicionRaised = "";
// if opts.opts.matchHeadsAndTailsStrictlyInPairsByTheirOrder is on and heads
// matched was i-th in the array, we will record its index "i" and later match
// the next tails to be also "i-th". Or throw.
let strictMatchingIndex;
for (let i = opts.fromIndex, len = str.length; i < len; i++) {
const firstCharsIndex = str[i].charCodeAt(0);
console.log(
`---------------------------------------> ${str[i]} i=${i} (#${firstCharsIndex})`
);
if (
firstCharsIndex <= headsAndTailsFirstCharIndexesRange[1] &&
firstCharsIndex >= headsAndTailsFirstCharIndexesRange[0]
) {
const matchedHeads = matchRightIncl(str, i, heads);
if (matchedHeads && opts.matchHeadsAndTailsStrictlyInPairsByTheirOrder) {
for (let z = heads.length; z--; ) {
if (heads[z] === matchedHeads) {
strictMatchingIndex = z;
break;
}
}
}
console.log(
`360 matchedHeads = ${JSON.stringify(matchedHeads, null, 4)}`
);
if (typeof matchedHeads === "string") {
if (!oneHeadFound) {
// res[0].push(i)
tempResObj = {};
tempResObj.headsStartAt = i;
tempResObj.headsEndAt = i + matchedHeads.length;
oneHeadFound = true;
console.log("369 head pushed");
// offset the index so the characters of the confirmed heads can't be "reused"
// again for subsequent, false detections:
i += matchedHeads.length - 1;
if (tailSuspicionRaised) {
tailSuspicionRaised = "";
console.log(
`376 !!! tailSuspicionRaised = ${!!tailSuspicionRaised}`
);
}
continue;
} else if (opts.throwWhenSomethingWrongIsDetected) {
throw new TypeError(
`${opts.source}${
s ? ": [THROW_ID_19]" : ""
} When processing "${str}", we found heads (${str.slice(
i,
i + matchedHeads.length
)}) starting at character with index number "${i}" and there was another set of heads before it! Generally speaking, there should be "heads-tails-heads-tails", not "heads-heads-tails"!\nWe're talking about the area of the code:\n\n\n--------------------------------------starts\n${str.slice(
Math.max(i - 200, 0),
i
)}\n ${`\u001b[${33}m------->\u001b[${39}m`} ${`\u001b[${31}m${str.slice(
i,
i + matchedHeads.length
)}\u001b[${39}m`} \u001b[${33}m${"<-------"}\u001b[${39}m\n${str.slice(
i + matchedHeads.length,
Math.min(len, i + 200)
)}\n--------------------------------------ends\n\n\nTo turn off this error being thrown, set opts.throwWhenSomethingWrongIsDetected to Boolean false.`
);
}
}
const matchedTails = matchRightIncl(str, i, tails);
console.log(
`402 matchedTails = ${JSON.stringify(matchedTails, null, 4)}`
);
if (
oneHeadFound &&
matchedTails &&
opts.matchHeadsAndTailsStrictlyInPairsByTheirOrder &&
strictMatchingIndex !== undefined &&
tails[strictMatchingIndex] !== undefined &&
tails[strictMatchingIndex] !== matchedTails
) {
let temp;
// find out which index in "matchedTails" does have "tails":
for (let z = tails.length; z--; ) {
if (tails[z] === matchedTails) {
temp = z;
break;
}
}
throw new TypeError(
`${opts.source}${
s ? ": [THROW_ID_20]" : ""
} When processing "${str}", we had "opts.matchHeadsAndTailsStrictlyInPairsByTheirOrder" on. We found heads (${
heads[strictMatchingIndex]
}) but the tails the followed it were not of the same index, ${strictMatchingIndex} (${
tails[strictMatchingIndex]
}) but ${temp} (${matchedTails}).`
);
}
if (typeof matchedTails === "string") {
if (oneHeadFound) {
tempResObj.tailsStartAt = i;
tempResObj.tailsEndAt = i + matchedTails.length;
res.push(tempResObj);
tempResObj = {};
oneHeadFound = false;
console.log("439 tail pushed");
// same for tails, offset the index to prevent partial, erroneous detections:
i += matchedTails.length - 1;
continue;
} else if (opts.throwWhenSomethingWrongIsDetected) {
// this means it's tails found, without preceding heads
tailSuspicionRaised = `${opts.source}${
s ? ": [THROW_ID_21]" : ""
} When processing "${str}", we found tails (${str.slice(
i,
i + matchedTails.length
)}) starting at character with index number "${i}" but there were no heads preceding it. That's very naughty!`;
console.log(`451 !!! tailSuspicionRaised = ${!!tailSuspicionRaised}`);
}
}
}
// closing, global checks:
console.log(`458 tempResObj = ${JSON.stringify(tempResObj, null, 4)}`);
// if it's the last character and some heads were found but no tails:
if (opts.throwWhenSomethingWrongIsDetected && i === len - 1) {
console.log("461");
if (Object.keys(tempResObj).length !== 0) {
console.log("463");
throw new TypeError(
`${opts.source}${
s ? ": [THROW_ID_22]" : ""
} When processing "${str}", we reached the end of the string and yet didn't find any tails (${JSON.stringify(
tails,
null,
4
)}) to match the last detected heads (${str.slice(
tempResObj.headsStartAt,
tempResObj.headsEndAt
)})!`
);
} else if (tailSuspicionRaised) {
console.log("477");
throw new Error(tailSuspicionRaised);
}
}
}
console.log(`482 final res = ${JSON.stringify(res, null, 4)}`);
return res as ResObj[];
}
export { strFindHeadsTails, defaults, version }; | the_stack |
import { PutFileEntry } from 'aws-sdk/clients/codecommit';
import * as yaml from 'js-yaml';
import { S3 } from '../aws/s3';
import { CodeCommit } from '../aws/codecommit';
import { pretty, FormatType } from './prettier';
import { RAW_CONFIG_FILE, JSON_FORMAT } from './constants';
import { DynamoDB } from '../aws/dynamodb';
import { Account } from '@aws-accelerator/common-outputs/src/accounts';
import { AssignedVpcCidrPool, AssignedSubnetCidrPool, CidrPool } from '@aws-accelerator/common-outputs/src/cidr-pools';
import { ReplacementObject, ReplacementsConfig } from '@aws-accelerator/common-config';
import { string as StringType } from 'io-ts';
const GLOBAL_REGION = 'us-east-1';
export function getFormattedObject(input: string, format: FormatType) {
if (!input || input === '') {
return {};
}
if (format === JSON_FORMAT) {
return JSON.parse(input);
}
return yaml.load(input);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getStringFromObject(input: any, format: FormatType) {
if (format === JSON_FORMAT) {
return JSON.stringify(input, null, 2);
}
return yaml.dump(input);
}
interface RawConfigProps {
configFilePath: string;
source: string;
repositoryName: string;
branchName: string;
format: FormatType;
region: string;
acceleratorPrefix: string;
acceleratorName: string;
s3Bucket?: string;
}
interface RawConfigOutput {
config: string;
loadFiles: PutFileEntry[];
}
export class RawConfig {
private readonly codecommit: CodeCommit;
private readonly s3: S3;
private readonly props: RawConfigProps;
constructor(props: RawConfigProps) {
this.props = props;
this.codecommit = new CodeCommit(undefined, this.props.region);
this.s3 = new S3();
}
async prepare(): Promise<RawConfigOutput> {
const loadFiles: PutFileEntry[] = [];
const { configFilePath, format } = this.props;
const configString = await this.getFromFile(configFilePath);
const config = getFormattedObject(configString, format);
const loadConfigResponse = await this.load(config, loadFiles);
// Sending Root Config back
loadConfigResponse.loadFiles.push({
filePath: configFilePath,
fileContent: pretty(configString, format),
});
let updatedRawconfig = replaceDefaults({
config: getStringFromObject(loadConfigResponse.config, JSON_FORMAT),
acceleratorName: this.props.acceleratorName,
acceleratorPrefix: this.props.acceleratorPrefix,
region: this.props.region,
additionalReplacements: additionalReplacements(loadConfigResponse.config.replacements || {}),
});
updatedRawconfig = await vpcReplacements({
rawConfigStr: updatedRawconfig,
});
// Sending Raw Config back
loadConfigResponse.loadFiles.push({
filePath: RAW_CONFIG_FILE,
fileContent: pretty(updatedRawconfig, JSON_FORMAT),
});
return {
config: JSON.stringify(loadConfigResponse.config),
loadFiles: loadConfigResponse.loadFiles,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async load(configElement: any, loadFiles: PutFileEntry[]) {
if (configElement.__LOAD) {
if (typeof configElement.__LOAD === 'string') {
console.log(`Loading file : ${configElement.__LOAD}`);
const tempConfig = await this.getFromFile(configElement.__LOAD);
if (!loadFiles.find(ldf => ldf.filePath === configElement.__LOAD)) {
loadFiles.push({
filePath: configElement.__LOAD,
fileContent: pretty(tempConfig, this.props.format),
});
}
delete configElement.__LOAD;
const tempConfigFormatted = getFormattedObject(tempConfig, this.props.format);
if (Array.isArray(tempConfigFormatted)) {
configElement = tempConfigFormatted;
} else {
configElement = {
...configElement,
...tempConfigFormatted,
};
}
} else {
for (const filename of configElement.__LOAD) {
const tempConfig = await this.getFromFile(filename);
if (!loadFiles.find(ldf => ldf.filePath === filename)) {
loadFiles.push({
filePath: filename,
fileContent: pretty(tempConfig, this.props.format),
});
}
configElement = {
...configElement,
...getFormattedObject(tempConfig, this.props.format),
};
}
delete configElement.__LOAD;
}
}
for (const element of Object.keys(configElement)) {
if (typeof configElement[element] === 'object') {
const loadConfigResponse = await this.load(configElement[element], loadFiles);
configElement[element] = loadConfigResponse.config;
loadFiles = loadConfigResponse.loadFiles;
}
}
return {
config: configElement,
loadFiles,
};
}
async getFromFile(filePath: string) {
const { source, branchName, repositoryName, s3Bucket } = this.props;
if (source === 's3') {
console.log(`Reading file ${filePath} from Bucket ${s3Bucket}`);
const configString = await this.s3.getObjectBodyAsString({
Bucket: s3Bucket!,
Key: filePath,
});
return configString;
}
console.log(`Reading file ${filePath} from Repository ${repositoryName}`);
const configResponse = await this.codecommit.getFile(repositoryName, filePath, branchName);
return configResponse.fileContent.toString();
}
}
export function equalIgnoreCase(value1: string, value2: string): boolean {
return value1.toLowerCase() === value2.toLowerCase();
}
export async function loadAccounts(tableName: string, client: DynamoDB): Promise<Account[]> {
let index = 0;
const accounts: Account[] = [];
if (!client) {
client = new DynamoDB();
}
while (true) {
const itemsInput = {
TableName: tableName,
Key: { id: { S: `accounts/${index}` } },
};
const item = await client.getItem(itemsInput);
if (index === 0 && !item.Item) {
throw new Error(`Cannot find parameter with ID "accounts"`);
}
if (!item.Item) {
break;
}
accounts.push(...JSON.parse(item.Item.value.S!));
index++;
}
return accounts;
}
export function additionalReplacements(configReplacements: ReplacementsConfig): { [key: string]: string | string[] } {
const replacements: { [key: string]: string | string[] } = {};
for (const [key, value] of Object.entries(configReplacements)) {
if (!ReplacementObject.is(value)) {
if (StringType.is(value)) {
replacements['\\${' + key.toUpperCase() + '}'] = value;
} else {
replacements['"?\\${' + key.toUpperCase() + '}"?'] = value;
}
} else {
for (const [needle, replacement] of Object.entries(value)) {
if (StringType.is(replacement)) {
replacements['\\${' + key.toUpperCase() + '_' + needle.toUpperCase() + '}'] = replacement;
} else {
replacements['"?\\${' + key.toUpperCase() + '_' + needle.toUpperCase() + '}"?'] = replacement;
}
}
}
}
return replacements;
}
export function replaceDefaults(props: {
config: string;
acceleratorPrefix: string;
acceleratorName: string;
region: string;
additionalReplacements: { [key: string]: string | string[] };
orgAdminRole?: string;
}) {
const { acceleratorName, acceleratorPrefix, additionalReplacements, region, orgAdminRole } = props;
let { config } = props;
const accelPrefixNd = acceleratorPrefix.endsWith('-') ? acceleratorPrefix.slice(0, -1) : acceleratorPrefix;
for (const [key, value] of Object.entries(additionalReplacements)) {
config = config.replace(new RegExp(key, 'g'), StringType.is(value) ? value : JSON.stringify(value));
}
/* eslint-disable no-template-curly-in-string */
const replacements = {
'\\${HOME_REGION}': region,
'\\${GBL_REGION}': GLOBAL_REGION,
'\\${ACCELERATOR_NAME}': acceleratorName,
'\\${ACCELERATOR_PREFIX}': acceleratorPrefix,
'\\${ACCELERATOR_PREFIX_ND}': accelPrefixNd,
'\\${ACCELERATOR_PREFIX_LND}': accelPrefixNd.toLowerCase(),
'\\${ORG_ADMIN_ROLE}': orgAdminRole!,
};
/* eslint-enable */
Object.entries(replacements).map(([key, value]) => {
config = config.replace(new RegExp(key, 'g'), value);
});
return config;
}
/**
* Dynamic VPC Replacements
* @param rawConfigStr
* @returns
*/
export async function vpcReplacements(props: { rawConfigStr: string }): Promise<string> {
const { rawConfigStr } = props;
/* eslint-disable no-template-curly-in-string */
const ouOrAccountReplacementRegex = '\\${CONFIG::OU_NAME}';
const vpcConfigSections = ['workload-account-configs', 'mandatory-account-configs', 'organizational-units'];
const rawConfig = JSON.parse(rawConfigStr);
for (const vpcConfigSection of vpcConfigSections) {
Object.entries(rawConfig[vpcConfigSection]).map(([key, _]) => {
const replacements = {
'\\${CONFIG::VPC_NAME}': key,
'\\${CONFIG::VPC_NAME_L}': key.toLowerCase(),
'\\${CONFIG::OU_NAME}': key,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
for (const [index, vpcConfig] of Object.entries(rawConfig[vpcConfigSection][key].vpc || []) as [string, any]) {
vpcConfig.name = vpcConfig.name.replace(new RegExp(ouOrAccountReplacementRegex, 'g'), key);
let vpcConfigStr = JSON.stringify(vpcConfig);
for (const [key, value] of Object.entries(replacements)) {
vpcConfigStr = vpcConfigStr.replace(new RegExp(key, 'g'), value);
}
rawConfig[vpcConfigSection][key].vpc[index] = JSON.parse(vpcConfigStr);
}
});
}
/* eslint-enable */
return getStringFromObject(rawConfig, JSON_FORMAT);
}
export async function loadAssignedVpcCidrPool(tableName: string, client?: DynamoDB) {
if (!client) {
client = new DynamoDB();
}
const assignedVpcCidrPools = await client.scan({
TableName: tableName,
});
return (assignedVpcCidrPools as unknown) as AssignedVpcCidrPool[];
}
export async function loadAssignedSubnetCidrPool(tableName: string, client?: DynamoDB) {
if (!client) {
client = new DynamoDB();
}
const assignedSubnetCidrPools = await client.scan({
TableName: tableName,
});
return (assignedSubnetCidrPools as unknown) as AssignedSubnetCidrPool[];
}
export async function loadCidrPools(tableName: string, client?: DynamoDB): Promise<CidrPool[]> {
if (!client) {
client = new DynamoDB();
}
const cidrPools = await client.scan({
TableName: tableName,
});
return (cidrPools as unknown) as CidrPool[];
}
export function randomAlphanumericString(length: number) {
const numbers = Math.random().toString(11).slice(2);
const chars = randomString(length - 2);
return numbers.slice(0, 2) + chars;
}
function randomString(length: number, charSet?: string) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let randomString = '';
for (let i = 0; i < length; i++) {
randomString += charSet.charAt(Math.floor(Math.random() * charSet.length));
}
return randomString;
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.