text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { makeExecutableSchema } from '@graphql-tools/schema'
import { $$asyncIterator } from 'iterall'
import {
applyMiddleware,
applyMiddlewareToDeclaredResolvers,
IMiddlewareFunction,
IMiddlewareTypeMap,
} from '../src'
import { IResolvers } from '../src/types'
/**
* Tests whether graphql-middleware-tool correctly applies middleware to fields it
* ought to impact based on the width of the middleware specification.
*/
describe('fragments:', () => {
test('schema-wide middleware', async () => {
/* Schema. */
const typeDefs = `
type Query {
book: Book!
}
type Book {
id: ID!
name: String!
content: String!
author: String!
}
`
const resolvers = {
Query: {
book() {
return {
id: 'id',
name: 'name',
content: 'content',
author: 'author',
}
},
},
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
/* Middleware. */
const schemaMiddlewareWithFragment: IMiddlewareFunction = {
fragment: `fragment NodeID on Node { id }`,
resolve: (resolve) => resolve(),
}
const { fragmentReplacements } = applyMiddleware(
schema,
schemaMiddlewareWithFragment,
)
/* Tests. */
expect(fragmentReplacements).toEqual([
{ field: 'book', fragment: '... on Node {\n id\n}' },
{ field: 'name', fragment: '... on Node {\n id\n}' },
{ field: 'content', fragment: '... on Node {\n id\n}' },
{ field: 'author', fragment: '... on Node {\n id\n}' },
])
})
test('type-wide middleware', async () => {
/* Schema. */
const typeDefs = `
type Query {
book: Book!
author: Author!
}
type Book {
id: ID!
content: String!
author: String!
}
type Author {
id: ID!
name: String!
}
`
const resolvers = {
Query: {
book() {
return {
id: 'id',
content: 'content',
author: 'author',
}
},
author() {
return {
name: 'name',
}
},
},
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
// Middleware
const typeMiddlewareWithFragment: IMiddlewareTypeMap = {
Book: {
fragment: `fragment BookId on Book { id }`,
resolve: (resolve) => resolve(),
},
Author: {
fragments: [`... on Author { id }`, `... on Author { name }`],
resolve: (resolve) => resolve(),
},
}
const { fragmentReplacements } = applyMiddleware(
schema,
typeMiddlewareWithFragment,
)
/* Tests. */
expect(fragmentReplacements).toEqual([
{
field: 'content',
fragment: '... on Book {\n id\n}',
},
{
field: 'author',
fragment: '... on Book {\n id\n}',
},
{
field: 'id',
fragment: '... on Author {\n name\n}',
},
{
field: 'name',
fragment: '... on Author {\n id\n}',
},
])
})
test('field-specific middleware', async () => {
const typeDefs = `
type Query {
book: Book!
}
type Book {
id: ID!
name: String!
content: String!
author: String!
}
`
const resolvers = {
Query: {
book() {
return {
id: 'id',
name: 'name',
content: 'content',
author: 'author',
}
},
},
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
// Middleware
const fieldMiddlewareWithFragment: IMiddlewareTypeMap = {
Book: {
content: {
fragment: `fragment BookId on Book { id ... on Book { name } }`,
resolve: (resolve) => resolve(),
},
author: {
fragments: [
`fragment BookId on Book { id }`,
`fragment BookContent on Book { content }`,
],
resolve: (resolve) => resolve(),
},
},
}
const { fragmentReplacements } = applyMiddleware(
schema,
fieldMiddlewareWithFragment,
)
/* Tests. */
expect(fragmentReplacements).toEqual([
{
field: 'content',
fragment: '... on Book {\n id\n ... on Book {\n name\n }\n}',
},
{
field: 'author',
fragment: '... on Book {\n id\n}',
},
{
field: 'author',
fragment: '... on Book {\n content\n}',
},
])
})
test('subscription fragment', async () => {
/* Schema. */
const typeDefs = `
type Query {
book(id: ID!): Book!
}
type Subscription {
book(id: ID!): Book!
}
type Book {
id: ID!
name: String!
}
schema {
query: Query,
subscription: Subscription
}
`
const resolvers: IResolvers = {
Query: {
book() {
return {
id: 'id',
name: 'name',
}
},
},
Subscription: {
book: {
subscribe: async (parent, { id }) => {
const iterator = {
next: () => Promise.resolve({ done: false, value: { sub: id } }),
return: () => {
return
},
throw: () => {
return
},
[$$asyncIterator]: () => iterator,
}
return iterator
},
},
},
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
/* Middleware. */
const fieldMiddlewareWithFragment: IMiddlewareTypeMap = {
Subscription: {
book: {
fragment: `fragment Ignored on Book { ignore }`,
resolve: (resolve) => resolve(),
},
},
}
const { fragmentReplacements } = applyMiddlewareToDeclaredResolvers(
schema,
fieldMiddlewareWithFragment,
)
/* Tests. */
expect(fragmentReplacements).toEqual([
{
field: 'book',
fragment: '... on Book {\n ignore\n}',
},
])
})
})
describe('fragments on declared resolvers:', () => {
test('schema-wide middleware', async () => {
/* Schema. */
const typeDefs = `
type Query {
book: Book!
}
type Book {
id: ID!
name: String!
content: String!
author: String!
}
`
const resolvers = {
Query: {
book() {
return {
id: 'id',
name: 'name',
content: 'content',
author: 'author',
}
},
},
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
/* Middleware. */
const schemaMiddlewareWithFragment: IMiddlewareFunction = {
fragment: `fragment NodeId on Node { id }`,
resolve: (resolve) => resolve(),
}
const { fragmentReplacements } = applyMiddlewareToDeclaredResolvers(
schema,
schemaMiddlewareWithFragment,
)
/* Tests. */
expect(fragmentReplacements).toEqual([
{ field: 'book', fragment: '... on Node {\n id\n}' },
])
})
test('type-wide middleware', async () => {
/* Schema. */
const typeDefs = `
type Query {
book: Book!
}
type Book {
id: ID!
name: String!
content: String!
author: String!
}
`
const resolvers = {
Query: {
book() {
return {
id: 'id',
name: 'name',
content: 'content',
author: 'author',
}
},
},
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
/* Middleware. */
const typeMiddlewareWithFragment: IMiddlewareTypeMap = {
Query: {
fragments: [`fragment QueryViewer on Query { viewer }`],
resolve: (resolve) => resolve(),
},
Book: {
fragment: `... on Book { id }`,
resolve: (resolve) => resolve(),
},
}
const { fragmentReplacements } = applyMiddlewareToDeclaredResolvers(
schema,
typeMiddlewareWithFragment,
)
/* Tests. */
expect(fragmentReplacements).toEqual([
{
field: 'book',
fragment: '... on Query {\n viewer\n}',
},
])
})
test('field-specific middleware', async () => {
/* Schema. */
const typeDefs = `
type Query {
book: Book!
}
type Book {
id: ID!
name: String!
content: String!
author: String!
}
`
const resolvers = {
Query: {
book() {
return {}
},
},
Book: {
id: () => 'id',
name: () => 'name',
content: () => 'content',
author: () => 'author',
},
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
/* Middleware. */
const fieldMiddlewareWithFragment: IMiddlewareTypeMap = {
Book: {
id: {
fragment: `fragment Ignored on Book { ignore }`,
resolve: (resolve) => resolve(),
},
content: {
fragment: `fragment BookId on Book { id }`,
resolve: (resolve) => resolve(),
},
author: {
fragments: [
`fragment AuthorId on Author { id }`,
`fragment AuthorName on Author { name }`,
],
resolve: (resolve) => resolve(),
},
},
}
const { fragmentReplacements } = applyMiddlewareToDeclaredResolvers(
schema,
fieldMiddlewareWithFragment,
)
/* Tests. */
expect(fragmentReplacements).toEqual([
{
field: 'id',
fragment: '... on Book {\n ignore\n}',
},
{
field: 'content',
fragment: '... on Book {\n id\n}',
},
{
field: 'author',
fragment: '... on Author {\n id\n}',
},
{
field: 'author',
fragment: '... on Author {\n name\n}',
},
])
})
})
test('imparsable fragment', async () => {
/* Schema. */
const typeDefs = `
type Query {
book: String!
}
`
const resolvers = {
Query: {
book() {
return 'book'
},
},
}
const schema = makeExecutableSchema({ typeDefs, resolvers })
/* Middleware. */
const fieldMiddlewareWithFragment: IMiddlewareFunction = {
fragment: 'foo',
resolve: (resolve) => resolve(),
}
/* Tests. */
expect(() => {
applyMiddlewareToDeclaredResolvers(schema, fieldMiddlewareWithFragment)
}).toThrow('Could not parse fragment')
}) | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ShowMoreInfoTestsQueryVariables = {
showID: string;
};
export type ShowMoreInfoTestsQueryResponse = {
readonly show: {
readonly " $fragmentRefs": FragmentRefs<"ShowMoreInfo_show">;
} | null;
};
export type ShowMoreInfoTestsQuery = {
readonly response: ShowMoreInfoTestsQueryResponse;
readonly variables: ShowMoreInfoTestsQueryVariables;
};
/*
query ShowMoreInfoTestsQuery(
$showID: String!
) {
show(id: $showID) {
...ShowMoreInfo_show
id
}
}
fragment LocationMap_location on Location {
id
internalID
city
address
address2
postalCode
summary
coordinates {
lat
lng
}
}
fragment PartnerEntityHeader_partner on Partner {
...PartnerFollowButton_partner
href
name
cities
isDefaultProfilePublic
initials
profile {
icon {
url(version: "square140")
}
id
}
}
fragment PartnerFollowButton_partner on Partner {
internalID
slug
profile {
id
internalID
isFollowed
}
}
fragment ShowHours_show on Show {
id
location {
...ShowLocationHours_location
id
}
fair {
location {
...ShowLocationHours_location
id
}
id
}
}
fragment ShowLocationHours_location on Location {
openingHours {
__typename
... on OpeningHoursArray {
schedules {
days
hours
}
}
... on OpeningHoursText {
text
}
}
}
fragment ShowLocation_show on Show {
partner {
__typename
... on Partner {
name
}
... on ExternalPartner {
name
id
}
... on Node {
__isNode: __typename
id
}
}
fair {
name
location {
...LocationMap_location
id
}
id
}
location {
...LocationMap_location
id
}
}
fragment ShowMoreInfo_show on Show {
...ShowLocation_show
...ShowHours_show
internalID
slug
href
about: description
pressRelease(format: MARKDOWN)
partner {
...PartnerEntityHeader_partner
__typename
... on Partner {
type
}
... on Node {
__isNode: __typename
id
}
... on ExternalPartner {
id
}
}
fair {
location {
__typename
openingHours {
__typename
... on OpeningHoursArray {
schedules {
__typename
}
}
... on OpeningHoursText {
text
}
}
coordinates {
lat
lng
}
id
}
id
}
location {
__typename
openingHours {
__typename
... on OpeningHoursArray {
schedules {
__typename
}
}
... on OpeningHoursText {
text
}
}
coordinates {
lat
lng
}
id
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"defaultValue": null,
"kind": "LocalArgument",
"name": "showID"
}
],
v1 = [
{
"kind": "Variable",
"name": "id",
"variableName": "showID"
}
],
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v3 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
v6 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v7 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
v8 = {
"alias": null,
"args": null,
"concreteType": "Location",
"kind": "LinkedField",
"name": "location",
"plural": false,
"selections": [
(v6/*: any*/),
(v4/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "city",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "address",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "address2",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "postalCode",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "summary",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "LatLng",
"kind": "LinkedField",
"name": "coordinates",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "lat",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "lng",
"storageKey": null
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "openingHours",
"plural": false,
"selections": [
(v2/*: any*/),
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "FormattedDaySchedules",
"kind": "LinkedField",
"name": "schedules",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "days",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "hours",
"storageKey": null
},
(v2/*: any*/)
],
"storageKey": null
}
],
"type": "OpeningHoursArray",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "text",
"storageKey": null
}
],
"type": "OpeningHoursText",
"abstractKey": null
}
],
"storageKey": null
},
(v2/*: any*/)
],
"storageKey": null
},
v9 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "String"
},
v10 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "ID"
},
v11 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Location"
},
v12 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "String"
},
v13 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "LatLng"
},
v14 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Float"
},
v15 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "OpeningHoursUnion"
},
v16 = {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "FormattedDaySchedules"
},
v17 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Boolean"
};
return {
"fragment": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Fragment",
"metadata": null,
"name": "ShowMoreInfoTestsQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Show",
"kind": "LinkedField",
"name": "show",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "ShowMoreInfo_show"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": (v0/*: any*/),
"kind": "Operation",
"name": "ShowMoreInfoTestsQuery",
"selections": [
{
"alias": null,
"args": (v1/*: any*/),
"concreteType": "Show",
"kind": "LinkedField",
"name": "show",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
(v2/*: any*/),
{
"kind": "InlineFragment",
"selections": [
(v3/*: any*/),
(v4/*: any*/),
(v5/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Profile",
"kind": "LinkedField",
"name": "profile",
"plural": false,
"selections": [
(v6/*: any*/),
(v4/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isFollowed",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "icon",
"plural": false,
"selections": [
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "version",
"value": "square140"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"square140\")"
}
],
"storageKey": null
}
],
"storageKey": null
},
(v7/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cities",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isDefaultProfilePublic",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "initials",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "type",
"storageKey": null
}
],
"type": "Partner",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v3/*: any*/),
(v6/*: any*/)
],
"type": "ExternalPartner",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v6/*: any*/)
],
"type": "Node",
"abstractKey": "__isNode"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Fair",
"kind": "LinkedField",
"name": "fair",
"plural": false,
"selections": [
(v3/*: any*/),
(v8/*: any*/),
(v6/*: any*/)
],
"storageKey": null
},
(v8/*: any*/),
(v6/*: any*/),
(v4/*: any*/),
(v5/*: any*/),
(v7/*: any*/),
{
"alias": "about",
"args": null,
"kind": "ScalarField",
"name": "description",
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "format",
"value": "MARKDOWN"
}
],
"kind": "ScalarField",
"name": "pressRelease",
"storageKey": "pressRelease(format:\"MARKDOWN\")"
}
],
"storageKey": null
}
]
},
"params": {
"id": "51ed4fc2ad0db12641b64dc1ab85bc30",
"metadata": {
"relayTestingSelectionTypeInfo": {
"show": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Show"
},
"show.about": (v9/*: any*/),
"show.fair": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Fair"
},
"show.fair.id": (v10/*: any*/),
"show.fair.location": (v11/*: any*/),
"show.fair.location.__typename": (v12/*: any*/),
"show.fair.location.address": (v9/*: any*/),
"show.fair.location.address2": (v9/*: any*/),
"show.fair.location.city": (v9/*: any*/),
"show.fair.location.coordinates": (v13/*: any*/),
"show.fair.location.coordinates.lat": (v14/*: any*/),
"show.fair.location.coordinates.lng": (v14/*: any*/),
"show.fair.location.id": (v10/*: any*/),
"show.fair.location.internalID": (v10/*: any*/),
"show.fair.location.openingHours": (v15/*: any*/),
"show.fair.location.openingHours.__typename": (v12/*: any*/),
"show.fair.location.openingHours.schedules": (v16/*: any*/),
"show.fair.location.openingHours.schedules.__typename": (v12/*: any*/),
"show.fair.location.openingHours.schedules.days": (v9/*: any*/),
"show.fair.location.openingHours.schedules.hours": (v9/*: any*/),
"show.fair.location.openingHours.text": (v9/*: any*/),
"show.fair.location.postalCode": (v9/*: any*/),
"show.fair.location.summary": (v9/*: any*/),
"show.fair.name": (v9/*: any*/),
"show.href": (v9/*: any*/),
"show.id": (v10/*: any*/),
"show.internalID": (v10/*: any*/),
"show.location": (v11/*: any*/),
"show.location.__typename": (v12/*: any*/),
"show.location.address": (v9/*: any*/),
"show.location.address2": (v9/*: any*/),
"show.location.city": (v9/*: any*/),
"show.location.coordinates": (v13/*: any*/),
"show.location.coordinates.lat": (v14/*: any*/),
"show.location.coordinates.lng": (v14/*: any*/),
"show.location.id": (v10/*: any*/),
"show.location.internalID": (v10/*: any*/),
"show.location.openingHours": (v15/*: any*/),
"show.location.openingHours.__typename": (v12/*: any*/),
"show.location.openingHours.schedules": (v16/*: any*/),
"show.location.openingHours.schedules.__typename": (v12/*: any*/),
"show.location.openingHours.schedules.days": (v9/*: any*/),
"show.location.openingHours.schedules.hours": (v9/*: any*/),
"show.location.openingHours.text": (v9/*: any*/),
"show.location.postalCode": (v9/*: any*/),
"show.location.summary": (v9/*: any*/),
"show.partner": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "PartnerTypes"
},
"show.partner.__isNode": (v12/*: any*/),
"show.partner.__typename": (v12/*: any*/),
"show.partner.cities": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "String"
},
"show.partner.href": (v9/*: any*/),
"show.partner.id": (v10/*: any*/),
"show.partner.initials": (v9/*: any*/),
"show.partner.internalID": (v10/*: any*/),
"show.partner.isDefaultProfilePublic": (v17/*: any*/),
"show.partner.name": (v9/*: any*/),
"show.partner.profile": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Profile"
},
"show.partner.profile.icon": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Image"
},
"show.partner.profile.icon.url": (v9/*: any*/),
"show.partner.profile.id": (v10/*: any*/),
"show.partner.profile.internalID": (v10/*: any*/),
"show.partner.profile.isFollowed": (v17/*: any*/),
"show.partner.slug": (v10/*: any*/),
"show.partner.type": (v9/*: any*/),
"show.pressRelease": (v9/*: any*/),
"show.slug": (v10/*: any*/)
}
},
"name": "ShowMoreInfoTestsQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = '6a3892da3b0e64394890f8be5b8847af';
export default node; | the_stack |
import { Event, EventHint } from '@sentry/types';
import { getGlobalObject } from '@sentry/utils';
import { addGlobalEventProcessor, Scope } from '../src';
describe('Scope', () => {
afterEach(() => {
jest.resetAllMocks();
jest.useRealTimers();
getGlobalObject<any>().__SENTRY__.globalEventProcessors = undefined;
});
describe('attributes modification', () => {
test('setFingerprint', () => {
const scope = new Scope();
scope.setFingerprint(['abcd']);
expect((scope as any)._fingerprint).toEqual(['abcd']);
});
test('setExtra', () => {
const scope = new Scope();
scope.setExtra('a', 1);
expect((scope as any)._extra).toEqual({ a: 1 });
});
test('setExtras', () => {
const scope = new Scope();
scope.setExtras({ a: 1 });
expect((scope as any)._extra).toEqual({ a: 1 });
});
test('setExtras with undefined overrides the value', () => {
const scope = new Scope();
scope.setExtra('a', 1);
scope.setExtras({ a: undefined });
expect((scope as any)._extra).toEqual({ a: undefined });
});
test('setTag', () => {
const scope = new Scope();
scope.setTag('a', 'b');
expect((scope as any)._tags).toEqual({ a: 'b' });
});
test('setTags', () => {
const scope = new Scope();
scope.setTags({ a: 'b' });
expect((scope as any)._tags).toEqual({ a: 'b' });
});
test('setUser', () => {
const scope = new Scope();
scope.setUser({ id: '1' });
expect((scope as any)._user).toEqual({ id: '1' });
});
test('setUser with null unsets the user', () => {
const scope = new Scope();
scope.setUser({ id: '1' });
scope.setUser(null);
expect((scope as any)._user).toEqual({});
});
test('addBreadcrumb', () => {
const scope = new Scope();
scope.addBreadcrumb({ message: 'test' });
expect((scope as any)._breadcrumbs[0]).toHaveProperty('message', 'test');
});
test('addBreadcrumb can be limited to hold up to N breadcrumbs', () => {
const scope = new Scope();
for (let i = 0; i < 10; i++) {
scope.addBreadcrumb({ message: 'test' }, 5);
}
expect((scope as any)._breadcrumbs).toHaveLength(5);
});
test('addBreadcrumb cannot go over MAX_BREADCRUMBS value', () => {
const scope = new Scope();
for (let i = 0; i < 111; i++) {
scope.addBreadcrumb({ message: 'test' }, 111);
}
expect((scope as any)._breadcrumbs).toHaveLength(100);
});
test('setLevel', () => {
const scope = new Scope();
scope.setLevel('critical');
expect((scope as any)._level).toEqual('critical');
});
test('setTransactionName', () => {
const scope = new Scope();
scope.setTransactionName('/abc');
expect((scope as any)._transactionName).toEqual('/abc');
});
test('setTransactionName with no value unsets it', () => {
const scope = new Scope();
scope.setTransactionName('/abc');
scope.setTransactionName();
expect((scope as any)._transactionName).toBeUndefined();
});
test('setContext', () => {
const scope = new Scope();
scope.setContext('os', { id: '1' });
expect((scope as any)._contexts.os).toEqual({ id: '1' });
});
test('setContext with null unsets it', () => {
const scope = new Scope();
scope.setContext('os', { id: '1' });
scope.setContext('os', null);
expect((scope as any)._user).toEqual({});
});
test('setSpan', () => {
const scope = new Scope();
const span = { fake: 'span' } as any;
scope.setSpan(span);
expect((scope as any)._span).toEqual(span);
});
test('setSpan with no value unsets it', () => {
const scope = new Scope();
scope.setSpan({ fake: 'span' } as any);
scope.setSpan();
expect((scope as any)._span).toEqual(undefined);
});
test('chaining', () => {
const scope = new Scope();
scope.setLevel('critical').setUser({ id: '1' });
expect((scope as any)._level).toEqual('critical');
expect((scope as any)._user).toEqual({ id: '1' });
});
});
describe('clone', () => {
test('basic inheritance', () => {
const parentScope = new Scope();
parentScope.setExtra('a', 1);
const scope = Scope.clone(parentScope);
expect((parentScope as any)._extra).toEqual((scope as any)._extra);
});
test('_requestSession clone', () => {
const parentScope = new Scope();
parentScope.setRequestSession({ status: 'errored' });
const scope = Scope.clone(parentScope);
expect(parentScope.getRequestSession()).toEqual(scope.getRequestSession());
});
test('parent changed inheritance', () => {
const parentScope = new Scope();
const scope = Scope.clone(parentScope);
parentScope.setExtra('a', 2);
expect((scope as any)._extra).toEqual({});
expect((parentScope as any)._extra).toEqual({ a: 2 });
});
test('child override inheritance', () => {
const parentScope = new Scope();
parentScope.setExtra('a', 1);
const scope = Scope.clone(parentScope);
scope.setExtra('a', 2);
expect((parentScope as any)._extra).toEqual({ a: 1 });
expect((scope as any)._extra).toEqual({ a: 2 });
});
test('child override should set the value of parent _requestSession', () => {
// Test that ensures if the status value of `status` of `_requestSession` is changed in a child scope
// that it should also change in parent scope because we are copying the reference to the object
const parentScope = new Scope();
parentScope.setRequestSession({ status: 'errored' });
const scope = Scope.clone(parentScope);
const requestSession = scope.getRequestSession();
if (requestSession) {
requestSession.status = 'ok';
}
expect(parentScope.getRequestSession()).toEqual({ status: 'ok' });
expect(scope.getRequestSession()).toEqual({ status: 'ok' });
});
});
describe('applyToEvent', () => {
test('basic usage', () => {
expect.assertions(8);
const scope = new Scope();
scope.setExtra('a', 2);
scope.setTag('a', 'b');
scope.setUser({ id: '1' });
scope.setFingerprint(['abcd']);
scope.setLevel('warning');
scope.setTransactionName('/abc');
scope.addBreadcrumb({ message: 'test' });
scope.setContext('os', { id: '1' });
const event: Event = {};
return scope.applyToEvent(event).then(processedEvent => {
expect(processedEvent!.extra).toEqual({ a: 2 });
expect(processedEvent!.tags).toEqual({ a: 'b' });
expect(processedEvent!.user).toEqual({ id: '1' });
expect(processedEvent!.fingerprint).toEqual(['abcd']);
expect(processedEvent!.level).toEqual('warning');
expect(processedEvent!.transaction).toEqual('/abc');
expect(processedEvent!.breadcrumbs![0]).toHaveProperty('message', 'test');
expect(processedEvent!.contexts).toEqual({ os: { id: '1' } });
});
});
test('merge with existing event data', () => {
expect.assertions(8);
const scope = new Scope();
scope.setExtra('a', 2);
scope.setTag('a', 'b');
scope.setUser({ id: '1' });
scope.setFingerprint(['abcd']);
scope.addBreadcrumb({ message: 'test' });
scope.setContext('server', { id: '2' });
const event: Event = {
breadcrumbs: [{ message: 'test1' }],
contexts: { os: { id: '1' } },
extra: { b: 3 },
fingerprint: ['efgh'],
tags: { b: 'c' },
user: { id: '3' },
};
return scope.applyToEvent(event).then(processedEvent => {
expect(processedEvent!.extra).toEqual({ a: 2, b: 3 });
expect(processedEvent!.tags).toEqual({ a: 'b', b: 'c' });
expect(processedEvent!.user).toEqual({ id: '3' });
expect(processedEvent!.fingerprint).toEqual(['efgh', 'abcd']);
expect(processedEvent!.breadcrumbs).toHaveLength(2);
expect(processedEvent!.breadcrumbs![0]).toHaveProperty('message', 'test1');
expect(processedEvent!.breadcrumbs![1]).toHaveProperty('message', 'test');
expect(processedEvent!.contexts).toEqual({
os: { id: '1' },
server: { id: '2' },
});
});
});
test('should make sure that fingerprint is always array', async () => {
const scope = new Scope();
const event: Event = {};
// @ts-ignore we want to be able to assign string value
event.fingerprint = 'foo';
await scope.applyToEvent(event).then(processedEvent => {
expect(processedEvent!.fingerprint).toEqual(['foo']);
});
// @ts-ignore we want to be able to assign string value
event.fingerprint = 'bar';
await scope.applyToEvent(event).then(processedEvent => {
expect(processedEvent!.fingerprint).toEqual(['bar']);
});
});
test('should merge fingerprint from event and scope', async () => {
const scope = new Scope();
scope.setFingerprint(['foo']);
const event: Event = {
fingerprint: ['bar'],
};
await scope.applyToEvent(event).then(processedEvent => {
expect(processedEvent!.fingerprint).toEqual(['bar', 'foo']);
});
});
test('should remove default empty fingerprint array if theres no data available', async () => {
const scope = new Scope();
const event: Event = {};
await scope.applyToEvent(event).then(processedEvent => {
expect(processedEvent!.fingerprint).toEqual(undefined);
});
});
test('scope level should have priority over event level', () => {
expect.assertions(1);
const scope = new Scope();
scope.setLevel('warning');
const event: Event = {};
event.level = 'critical';
return scope.applyToEvent(event).then(processedEvent => {
expect(processedEvent!.level).toEqual('warning');
});
});
test('scope transaction should have priority over event transaction', () => {
expect.assertions(1);
const scope = new Scope();
scope.setTransactionName('/abc');
const event: Event = {};
event.transaction = '/cdf';
return scope.applyToEvent(event).then(processedEvent => {
expect(processedEvent!.transaction).toEqual('/abc');
});
});
});
test('applyToEvent trace context', async () => {
expect.assertions(1);
const scope = new Scope();
const span = {
fake: 'span',
getTraceContext: () => ({ a: 'b' }),
} as any;
scope.setSpan(span);
const event: Event = {};
return scope.applyToEvent(event).then(processedEvent => {
expect((processedEvent!.contexts!.trace as any).a).toEqual('b');
});
});
test('applyToEvent existing trace context in event should be stronger', async () => {
expect.assertions(1);
const scope = new Scope();
const span = {
fake: 'span',
getTraceContext: () => ({ a: 'b' }),
} as any;
scope.setSpan(span);
const event: Event = {
contexts: {
trace: { a: 'c' },
},
};
return scope.applyToEvent(event).then(processedEvent => {
expect((processedEvent!.contexts!.trace as any).a).toEqual('c');
});
});
test('applyToEvent transaction name tag when transaction on scope', async () => {
expect.assertions(1);
const scope = new Scope();
const transaction = {
fake: 'span',
getTraceContext: () => ({ a: 'b' }),
name: 'fake transaction',
} as any;
transaction.transaction = transaction; // because this is a transaction, its transaction pointer points to itself
scope.setSpan(transaction);
const event: Event = {};
return scope.applyToEvent(event).then(processedEvent => {
expect(processedEvent!.tags!.transaction).toEqual('fake transaction');
});
});
test('applyToEvent transaction name tag when span on scope', async () => {
expect.assertions(1);
const scope = new Scope();
const transaction = { name: 'fake transaction' };
const span = {
fake: 'span',
getTraceContext: () => ({ a: 'b' }),
transaction,
} as any;
scope.setSpan(span);
const event: Event = {};
return scope.applyToEvent(event).then(processedEvent => {
expect(processedEvent!.tags!.transaction).toEqual('fake transaction');
});
});
test('clear', () => {
const scope = new Scope();
scope.setExtra('a', 2);
scope.setTag('a', 'b');
scope.setUser({ id: '1' });
scope.setFingerprint(['abcd']);
scope.addBreadcrumb({ message: 'test' });
scope.setRequestSession({ status: 'ok' });
expect((scope as any)._extra).toEqual({ a: 2 });
scope.clear();
expect((scope as any)._extra).toEqual({});
expect((scope as any)._requestSession).toEqual(undefined);
});
test('clearBreadcrumbs', () => {
const scope = new Scope();
scope.addBreadcrumb({ message: 'test' });
expect((scope as any)._breadcrumbs).toHaveLength(1);
scope.clearBreadcrumbs();
expect((scope as any)._breadcrumbs).toHaveLength(0);
});
describe('update', () => {
let scope: Scope;
beforeEach(() => {
scope = new Scope();
scope.setTags({ foo: '1', bar: '2' });
scope.setExtras({ foo: '1', bar: '2' });
scope.setContext('foo', { id: '1' });
scope.setContext('bar', { id: '2' });
scope.setUser({ id: '1337' });
scope.setLevel('info');
scope.setFingerprint(['foo']);
scope.setRequestSession({ status: 'ok' });
});
test('given no data, returns the original scope', () => {
const updatedScope = scope.update();
expect(updatedScope).toEqual(scope);
});
test('given neither function, Scope or plain object, returns original scope', () => {
// @ts-ignore we want to be able to update scope with string
const updatedScope = scope.update('wat');
expect(updatedScope).toEqual(scope);
});
test('given callback function, pass it the scope and returns original or modified scope', () => {
const cb = jest
.fn()
.mockImplementationOnce(v => v)
.mockImplementationOnce(v => {
v.setTag('foo', 'bar');
return v;
});
let updatedScope = scope.update(cb);
expect(cb).toHaveBeenNthCalledWith(1, scope);
expect(updatedScope).toEqual(scope);
updatedScope = scope.update(cb);
expect(cb).toHaveBeenNthCalledWith(2, scope);
expect(updatedScope).toEqual(scope);
});
test('given callback function, when it doesnt return instanceof Scope, ignore it and return original scope', () => {
const cb = jest.fn().mockImplementationOnce(_v => 'wat');
const updatedScope = scope.update(cb);
expect(cb).toHaveBeenCalledWith(scope);
expect(updatedScope).toEqual(scope);
});
test('given another instance of Scope, it should merge two together, with the passed scope having priority', () => {
const localScope = new Scope();
localScope.setTags({ bar: '3', baz: '4' });
localScope.setExtras({ bar: '3', baz: '4' });
localScope.setContext('bar', { id: '3' });
localScope.setContext('baz', { id: '4' });
localScope.setUser({ id: '42' });
localScope.setLevel('warning');
localScope.setFingerprint(['bar']);
(localScope as any)._requestSession = { status: 'ok' };
const updatedScope = scope.update(localScope) as any;
expect(updatedScope._tags).toEqual({
bar: '3',
baz: '4',
foo: '1',
});
expect(updatedScope._extra).toEqual({
bar: '3',
baz: '4',
foo: '1',
});
expect(updatedScope._contexts).toEqual({
bar: { id: '3' },
baz: { id: '4' },
foo: { id: '1' },
});
expect(updatedScope._user).toEqual({ id: '42' });
expect(updatedScope._level).toEqual('warning');
expect(updatedScope._fingerprint).toEqual(['bar']);
expect(updatedScope._requestSession.status).toEqual('ok');
});
test('given an empty instance of Scope, it should preserve all the original scope data', () => {
const updatedScope = scope.update(new Scope()) as any;
expect(updatedScope._tags).toEqual({
bar: '2',
foo: '1',
});
expect(updatedScope._extra).toEqual({
bar: '2',
foo: '1',
});
expect(updatedScope._contexts).toEqual({
bar: { id: '2' },
foo: { id: '1' },
});
expect(updatedScope._user).toEqual({ id: '1337' });
expect(updatedScope._level).toEqual('info');
expect(updatedScope._fingerprint).toEqual(['foo']);
expect(updatedScope._requestSession.status).toEqual('ok');
});
test('given a plain object, it should merge two together, with the passed object having priority', () => {
const localAttributes = {
contexts: { bar: { id: '3' }, baz: { id: '4' } },
extra: { bar: '3', baz: '4' },
fingerprint: ['bar'],
level: 'warning',
tags: { bar: '3', baz: '4' },
user: { id: '42' },
requestSession: { status: 'errored' },
};
const updatedScope = scope.update(localAttributes) as any;
expect(updatedScope._tags).toEqual({
bar: '3',
baz: '4',
foo: '1',
});
expect(updatedScope._extra).toEqual({
bar: '3',
baz: '4',
foo: '1',
});
expect(updatedScope._contexts).toEqual({
bar: { id: '3' },
baz: { id: '4' },
foo: { id: '1' },
});
expect(updatedScope._user).toEqual({ id: '42' });
expect(updatedScope._level).toEqual('warning');
expect(updatedScope._fingerprint).toEqual(['bar']);
expect(updatedScope._requestSession).toEqual({ status: 'errored' });
});
});
describe('addEventProcessor', () => {
test('should allow for basic event manipulation', () => {
expect.assertions(3);
const event: Event = {
extra: { b: 3 },
};
const localScope = new Scope();
localScope.setExtra('a', 'b');
localScope.addEventProcessor((processedEvent: Event) => {
expect(processedEvent.extra).toEqual({ a: 'b', b: 3 });
return processedEvent;
});
localScope.addEventProcessor((processedEvent: Event) => {
processedEvent.dist = '1';
return processedEvent;
});
localScope.addEventProcessor((processedEvent: Event) => {
expect(processedEvent.dist).toEqual('1');
return processedEvent;
});
return localScope.applyToEvent(event).then(final => {
expect(final!.dist).toEqual('1');
});
});
test('should work alongside global event processors', () => {
expect.assertions(3);
const event: Event = {
extra: { b: 3 },
};
const localScope = new Scope();
localScope.setExtra('a', 'b');
addGlobalEventProcessor((processedEvent: Event) => {
processedEvent.dist = '1';
return processedEvent;
});
localScope.addEventProcessor((processedEvent: Event) => {
expect(processedEvent.extra).toEqual({ a: 'b', b: 3 });
return processedEvent;
});
localScope.addEventProcessor((processedEvent: Event) => {
expect(processedEvent.dist).toEqual('1');
return processedEvent;
});
return localScope.applyToEvent(event).then(final => {
expect(final!.dist).toEqual('1');
});
});
test('should allow for async callbacks', async () => {
jest.useFakeTimers();
expect.assertions(6);
const event: Event = {
extra: { b: 3 },
};
const localScope = new Scope();
localScope.setExtra('a', 'b');
const callCounter = jest.fn();
localScope.addEventProcessor((processedEvent: Event) => {
callCounter(1);
expect(processedEvent.extra).toEqual({ a: 'b', b: 3 });
return processedEvent;
});
localScope.addEventProcessor(
async (processedEvent: Event) =>
new Promise<Event>(resolve => {
callCounter(2);
setTimeout(() => {
callCounter(3);
processedEvent.dist = '1';
resolve(processedEvent);
}, 1);
jest.runAllTimers();
}),
);
localScope.addEventProcessor((processedEvent: Event) => {
callCounter(4);
return processedEvent;
});
return localScope.applyToEvent(event).then(processedEvent => {
expect(callCounter.mock.calls[0][0]).toBe(1);
expect(callCounter.mock.calls[1][0]).toBe(2);
expect(callCounter.mock.calls[2][0]).toBe(3);
expect(callCounter.mock.calls[3][0]).toBe(4);
expect(processedEvent!.dist).toEqual('1');
});
});
test('should correctly handle async rejections', async () => {
jest.useFakeTimers();
expect.assertions(2);
const event: Event = {
extra: { b: 3 },
};
const localScope = new Scope();
localScope.setExtra('a', 'b');
const callCounter = jest.fn();
localScope.addEventProcessor((processedEvent: Event) => {
callCounter(1);
expect(processedEvent.extra).toEqual({ a: 'b', b: 3 });
return processedEvent;
});
localScope.addEventProcessor(
async (_processedEvent: Event) =>
new Promise<Event>((_, reject) => {
setTimeout(() => {
reject('bla');
}, 1);
jest.runAllTimers();
}),
);
localScope.addEventProcessor((processedEvent: Event) => {
callCounter(4);
return processedEvent;
});
return localScope.applyToEvent(event).then(null, reason => {
expect(reason).toEqual('bla');
});
});
test('should drop an event when any of processors return null', () => {
expect.assertions(1);
const event: Event = {
extra: { b: 3 },
};
const localScope = new Scope();
localScope.setExtra('a', 'b');
localScope.addEventProcessor(async (_: Event) => null);
return localScope.applyToEvent(event).then(processedEvent => {
expect(processedEvent).toBeNull();
});
});
test('should have an access to the EventHint', () => {
expect.assertions(3);
const event: Event = {
extra: { b: 3 },
};
const localScope = new Scope();
localScope.setExtra('a', 'b');
localScope.addEventProcessor(async (internalEvent: Event, hint?: EventHint) => {
expect(hint).toBeTruthy();
expect(hint!.syntheticException).toBeTruthy();
return internalEvent;
});
return localScope.applyToEvent(event, { syntheticException: new Error('what') }).then(processedEvent => {
expect(processedEvent).toEqual(event);
});
});
test('should notify all the listeners about the changes', () => {
jest.useFakeTimers();
const scope = new Scope();
const listener = jest.fn();
scope.addScopeListener(listener);
scope.setExtra('a', 2);
jest.runAllTimers();
expect(listener).toHaveBeenCalled();
expect(listener.mock.calls[0][0]._extra).toEqual({ a: 2 });
});
});
}); | the_stack |
import * as sinon from 'sinon';
import * as get from 'lodash.get';
import * as isObject from 'lodash.isobject';
import * as path from 'path';
import * as depGraphLib from '@snyk/dep-graph';
interface AcceptanceTests {
language: string;
tests: {
[name: string]: any;
};
}
export const AllProjectsTests: AcceptanceTests = {
language: 'Mixed',
tests: {
'`monitor mono-repo-with-ignores --all-projects` respects .snyk policy': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
await params.cli.monitor('mono-repo-with-ignores', {
allProjects: true,
detectionDepth: 2,
});
const requests = params.server
.getRequests()
.filter((req) => req.url.includes('/monitor/'));
let policyCount = 0;
requests.forEach((req) => {
const vulnerableFolderPath =
process.platform === 'win32'
? 'vulnerable\\package-lock.json'
: 'vulnerable/package-lock.json';
if (req.body.targetFileRelativePath.endsWith(vulnerableFolderPath)) {
t.match(
req.body.policy,
'npm:node-uuid:20160328',
'body contains policy',
);
policyCount += 1;
}
});
t.equal(policyCount, 1, 'one policy found');
},
'`monitor mono-repo-project --all-projects --detection-depth=1`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
// mock python plugin becuase CI tooling doesn't have pipenv installed
const mockPlugin = {
async inspect() {
return {
plugin: {
targetFile: 'Pipfile',
name: 'snyk-python-plugin',
},
package: {},
};
},
};
const loadPlugin = sinon.stub(params.plugins, 'loadPlugin');
t.teardown(loadPlugin.restore);
loadPlugin.withArgs('pip').returns(mockPlugin);
loadPlugin.callThrough(); // don't mock other plugins
const result = await params.cli.monitor('mono-repo-project', {
allProjects: true,
detectionDepth: 1,
});
t.ok(loadPlugin.withArgs('rubygems').calledOnce, 'calls rubygems plugin');
t.ok(loadPlugin.withArgs('npm').calledOnce, 'calls npm plugin');
t.ok(loadPlugin.withArgs('maven').calledOnce, 'calls maven plugin');
t.ok(loadPlugin.withArgs('nuget').calledOnce, 'calls nuget plugin');
t.ok(loadPlugin.withArgs('paket').calledOnce, 'calls nuget plugin');
t.ok(loadPlugin.withArgs('pip').calledOnce, 'calls pip plugin');
t.ok(loadPlugin.withArgs('sbt').calledOnce, 'calls sbt plugin');
t.match(
result,
'rubygems/graph/some/project-id',
'ruby project in output',
);
t.match(result, 'npm/graph/some/project-id', 'npm project in output');
t.match(result, 'maven/some/project-id', 'maven project in output ');
t.match(result, 'nuget/some/project-id', 'nuget project in output');
t.match(result, 'paket/some/project-id', 'paket project in output');
t.match(result, 'pip/some/project-id', 'python project in output ');
t.match(result, 'sbt/graph/some/project-id', 'sbt project in output ');
const requests = params.server
.getRequests()
.filter((req) => req.url.includes('/monitor/'));
t.equal(requests.length, 7, 'correct amount of monitor requests');
const pluginsWithoutTargetFileInBody = [
'snyk-nodejs-lockfile-parser',
'bundled:maven',
'bundled:rubygems',
'snyk:sbt',
];
requests.forEach((req) => {
t.match(
req.url,
/\/api\/v1\/monitor\/(npm\/graph|rubygems|maven|nuget|paket|pip|sbt)/,
'puts at correct url',
);
if (pluginsWithoutTargetFileInBody.includes(req.body.meta.pluginName)) {
t.notOk(
req.body.targetFile,
`doesn't send the targetFile for ${req.body.meta.pluginName}`,
);
} else {
t.ok(
req.body.targetFile,
`does send the targetFile ${req.body.meta.pluginName}`,
);
}
t.equal(req.method, 'PUT', 'makes PUT request');
t.equal(
req.headers['x-snyk-cli-version'],
params.versionNumber,
'sends version number',
);
});
},
'`monitor maven-multi-app --all-projects --detection-depth=2`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
const spyPlugin = sinon.spy(params.plugins, 'loadPlugin');
t.teardown(spyPlugin.restore);
const result = await params.cli.monitor('maven-multi-app', {
allProjects: true,
detectionDepth: 2,
});
t.ok(
spyPlugin.withArgs('rubygems').notCalled,
'did not call rubygems plugin',
);
t.ok(spyPlugin.withArgs('npm').notCalled, 'did not call npm plugin');
t.equals(
spyPlugin.withArgs('maven').callCount,
2,
'calls maven plugin twice',
);
t.match(result, 'maven/some/project-id', 'maven project was monitored ');
const requests = params.server.popRequests(2);
requests.forEach((request) => {
t.match(request.url, '/api/v1/monitor/maven', 'puts at correct url');
t.notOk(request.body.targetFile, "doesn't send the targetFile");
t.equal(request.method, 'PUT', 'makes PUT request');
t.equal(
request.headers['x-snyk-cli-version'],
params.versionNumber,
'sends version number',
);
});
},
'`monitor monorepo-bad-project --all-projects`': (params, utils) => async (
t,
) => {
utils.chdirWorkspaces();
const spyPlugin = sinon.spy(params.plugins, 'loadPlugin');
t.teardown(spyPlugin.restore);
let result;
try {
await params.cli.monitor('monorepo-bad-project', {
allProjects: true,
});
} catch (error) {
result = error.message;
}
t.ok(spyPlugin.withArgs('rubygems').calledOnce, 'calls rubygems plugin');
t.ok(spyPlugin.withArgs('yarn').calledOnce, 'calls npm plugin');
t.ok(spyPlugin.withArgs('maven').notCalled, 'did not call maven plugin');
t.match(
result,
'rubygems/graph/some/project-id',
'rubygems project was monitored',
);
t.match(
result,
'Dependency snyk was not found in yarn.lock',
'yarn project had an error and we displayed it',
);
const request = params.server.popRequest();
t.match(
request.url,
'/api/v1/monitor/rubygems/graph',
'puts at correct url',
);
t.notOk(request.body.targetFile, "doesn't send the targetFile");
t.equal(request.method, 'PUT', 'makes PUT request');
t.equal(
request.headers['x-snyk-cli-version'],
params.versionNumber,
'sends version number',
);
},
'`monitor mono-repo-project --all-projects sends same payload as --file`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
// mock python plugin becuase CI tooling doesn't have pipenv installed
const mockPlugin = {
async inspect() {
return {
plugin: {
targetFile: 'Pipfile',
name: 'snyk-python-plugin',
},
package: {},
};
},
};
const loadPlugin = sinon.stub(params.plugins, 'loadPlugin');
t.teardown(loadPlugin.restore);
loadPlugin.withArgs('pip').returns(mockPlugin);
loadPlugin.callThrough(); // don't mock other plugins
await params.cli.monitor('mono-repo-project', {
allProjects: true,
detectionDepth: 1,
});
const requests = params.server
.getRequests()
.filter((req) => req.url.includes('/monitor/'));
// find each type of request
const rubyAll = requests.find((req) => req.url.indexOf('rubygems') > -1);
const pipAll = requests.find((req) => req.url.indexOf('pip') > -1);
const npmAll = requests.find((req) => req.url.indexOf('npm') > -1);
const nugetAll = requests.find((req) => req.url.indexOf('nuget') > -1);
const paketAll = requests.find((req) => req.url.indexOf('paket') > -1);
const mavenAll = requests.find((req) => req.url.indexOf('maven') > -1);
const sbtAll = requests.find((req) => req.url.indexOf('sbt') > -1);
params.server.restore();
await params.cli.monitor('mono-repo-project', {
file: 'Gemfile.lock',
});
const rubyFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('mono-repo-project', {
file: 'Pipfile',
});
const pipFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('mono-repo-project', {
file: 'package-lock.json',
});
const npmFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('mono-repo-project', {
file: 'packages.config',
});
const nugetFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('mono-repo-project', {
file: 'paket.dependencies',
});
const paketFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('mono-repo-project', {
file: 'pom.xml',
});
const mavenFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('mono-repo-project', {
file: 'build.sbt',
});
const sbtFile = params.server.popRequest();
t.same(
rubyAll.body,
rubyFile.body,
'same body for --all-projects and --file=Gemfile.lock',
);
t.same(
pipAll.body,
pipFile.body,
'same body for --all-projects and --file=Pipfile',
);
t.same(
npmAll.body,
npmFile.body,
'same body for --all-projects and --file=package-lock.json',
);
t.same(
nugetAll.body,
nugetFile.body,
'same body for --all-projects and --file=packages.config',
);
t.same(
paketAll.body,
paketFile.body,
'same body for --all-projects and --file=paket.dependencies',
);
t.same(
mavenAll.body,
mavenFile.body,
'same body for --all-projects and --file=pom.xml',
);
t.same(
sbtAll.body,
sbtFile.body,
'same body for --all-projects and --file=build.sbt',
);
},
'`monitor composer-app with --all-projects sends same payload as --file`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
const spyPlugin = sinon.spy(params.plugins, 'loadPlugin');
t.teardown(spyPlugin.restore);
await params.cli.monitor('composer-app', {
allProjects: true,
});
const composerAll = params.server.popRequest();
await params.cli.monitor('composer-app', {
file: 'composer.lock',
});
const composerFile = params.server.popRequest();
t.same(
composerAll.body,
composerFile.body,
'same body for --all-projects and --file=composer.lock',
);
},
'`monitor mono-repo-project with lockfiles --all-projects --json`': (
params,
utils,
) => async (t) => {
try {
utils.chdirWorkspaces();
// mock python plugin becuase CI tooling doesn't have pipenv installed
const mockPlugin = {
async inspect() {
return {
plugin: {
targetFile: 'Pipfile',
name: 'snyk-python-plugin',
},
package: {
name: 'mono-repo-project', // used by projectName
},
};
},
};
const loadPlugin = sinon.stub(params.plugins, 'loadPlugin');
t.teardown(loadPlugin.restore);
loadPlugin.withArgs('pip').returns(mockPlugin);
loadPlugin.callThrough(); // don't mock other plugins
const response = await params.cli.monitor('mono-repo-project', {
json: true,
allProjects: true,
detectionDepth: 1,
});
const jsonResponse = JSON.parse(response);
t.equal(
jsonResponse.length,
7,
'json response array has expected # elements',
);
jsonResponse.forEach((res) => {
if (isObject(res)) {
t.pass('monitor outputted JSON');
} else {
t.fail('Failed parsing monitor JSON output');
}
const keyList = [
'packageManager',
'manageUrl',
'id',
'projectName',
'isMonitored',
];
keyList.forEach((k) => {
!get(res, k) ? t.fail(k + ' not found') : t.pass(k + ' found');
});
});
} catch (error) {
t.fail('should have passed', error);
}
},
'`monitor maven-multi-app --all-projects --detection-depth=2 --exclude=simple-child`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
const spyPlugin = sinon.spy(params.plugins, 'loadPlugin');
t.teardown(spyPlugin.restore);
const result = await params.cli.monitor('maven-multi-app', {
allProjects: true,
detectionDepth: 2,
exclude: 'simple-child',
});
t.ok(
spyPlugin.withArgs('rubygems').notCalled,
'did not call rubygems plugin',
);
t.ok(spyPlugin.withArgs('npm').notCalled, 'did not call npm plugin');
t.equals(
spyPlugin.withArgs('maven').callCount,
1,
'calls maven plugin once, excluding simple-child',
);
t.match(result, 'maven/some/project-id', 'maven project was monitored ');
const request = params.server.popRequest();
t.match(request.url, '/monitor/', 'puts at correct url');
t.notOk(request.body.targetFile, "doesn't send the targetFile");
t.equal(request.method, 'PUT', 'makes PUT request');
t.equal(
request.headers['x-snyk-cli-version'],
params.versionNumber,
'sends version number',
);
},
'`monitor monorepo-with-nuget --all-projects sends same payload as --file`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
// mock go plugin becuase CI tooling doesn't have go installed
const mockPlugin = {
async inspect() {
return {
plugin: {
targetFile: 'Gopkg.lock',
name: 'snyk-go-plugin',
runtime: 'go',
},
package: {},
};
},
};
const loadPlugin = sinon.stub(params.plugins, 'loadPlugin');
t.teardown(loadPlugin.restore);
loadPlugin.withArgs('golangdep').returns(mockPlugin);
loadPlugin.callThrough(); // don't mock other plugins
await params.cli.monitor('monorepo-with-nuget', {
allProjects: true,
detectionDepth: 4,
});
const [
projectAssetsAll,
cocoapodsAll,
golangdepAll,
npmAll,
packageConfigAll,
paketAll,
] = params.server
.getRequests()
.filter((req) => req.url.includes('/monitor/'));
params.server.restore();
await params.cli.monitor('monorepo-with-nuget', {
file: `src${path.sep}cartservice-nuget${path.sep}obj${path.sep}project.assets.json`,
});
const projectAssetsFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('monorepo-with-nuget', {
file: `src${path.sep}cocoapods-app${path.sep}Podfile.lock`,
});
const cocoapodsFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('monorepo-with-nuget', {
file: `src${path.sep}frontend${path.sep}Gopkg.lock`,
});
const golangdepFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('monorepo-with-nuget', {
file: `src${path.sep}paymentservice${path.sep}package-lock.json`,
});
const npmFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('monorepo-with-nuget', {
file: `test${path.sep}nuget-app-4${path.sep}packages.config`,
});
const packageConfigFile = params.server.popRequest();
params.server.restore();
await params.cli.monitor('monorepo-with-nuget', {
file: `test${path.sep}paket-app${path.sep}paket.dependencies`,
});
const paketFile = params.server.popRequest();
t.same(
projectAssetsAll.body,
projectAssetsFile.body,
`same body for --all-projects and --file=src${path.sep}cartservice-nuget${path.sep}obj${path.sep}project.assets.json`,
);
t.same(
cocoapodsAll.body,
cocoapodsFile.body,
`same body for --all-projects and --file=src${path.sep}cocoapods-app${path.sep}Podfile.lock`,
);
t.same(
golangdepAll.body,
golangdepFile.body,
`same body for --all-projects and --file=src${path.sep}frontend${path.sep}Gopkg.lock`,
);
t.same(
npmAll.body,
npmFile.body,
`same body for --all-projects and --file=src${path.sep}paymentservice${path.sep}package-lock.json`,
);
t.same(
packageConfigAll.body,
packageConfigFile.body,
`same body for --all-projects and --file=test${path.sep}nuget-app-4${path.sep}packages.config`,
);
t.same(
paketAll.body,
paketFile.body,
`same body for --all-projects and --file=test${path.sep}paket-app${path.sep}paket.dependencies`,
);
},
'`monitor mono-repo-go/hello-dep --all-projects sends same body as --file`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
// mock plugin becuase CI tooling doesn't have go installed
const mockPlugin = {
async inspect() {
return {
plugin: {
targetFile: 'Gopkg.lock',
name: 'snyk-go-plugin',
runtime: 'go',
},
package: {},
};
},
};
const loadPlugin = sinon.stub(params.plugins, 'loadPlugin');
t.teardown(loadPlugin.restore);
loadPlugin.withArgs('golangdep').returns(mockPlugin);
await params.cli.monitor('mono-repo-go/hello-dep', {
allProjects: true,
});
const allProjectsBody = params.server.popRequest();
await params.cli.monitor('mono-repo-go/hello-dep', {
file: 'Gopkg.lock',
});
const fileBody = params.server.popRequest();
t.same(
allProjectsBody.body,
fileBody.body,
'same body for --all-projects and --file=mono-repo-go/hello-dep/Gopkg.lock',
);
},
'`monitor mono-repo-go/hello-mod --all-projects sends same body as --file`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
// mock plugin becuase CI tooling doesn't have go installed
const mockPlugin = {
async inspect() {
return {
plugin: {
targetFile: 'go.mod',
name: 'snyk-go-plugin',
runtime: 'go',
},
package: {},
};
},
};
const loadPlugin = sinon.stub(params.plugins, 'loadPlugin');
t.teardown(loadPlugin.restore);
loadPlugin.withArgs('gomodules').returns(mockPlugin);
await params.cli.monitor('mono-repo-go/hello-mod', {
allProjects: true,
});
const allProjectsBody = params.server.popRequest();
await params.cli.monitor('mono-repo-go/hello-mod', {
file: 'go.mod',
});
const fileBody = params.server.popRequest();
t.same(
allProjectsBody.body,
fileBody.body,
'same body for --all-projects and --file=mono-repo-go/hello-mod/go.mod',
);
},
'`monitor mono-repo-go/hello-vendor --all-projects sends same body as --file`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
// mock plugin becuase CI tooling doesn't have go installed
const mockPlugin = {
async inspect() {
return {
plugin: {
targetFile: 'vendor/vendor.json',
name: 'snyk-go-plugin',
runtime: 'go',
},
package: {},
};
},
};
const loadPlugin = sinon.stub(params.plugins, 'loadPlugin');
t.teardown(loadPlugin.restore);
loadPlugin.withArgs('govendor').returns(mockPlugin);
await params.cli.monitor('mono-repo-go/hello-vendor', {
allProjects: true,
});
const allProjectsBody = params.server.popRequest();
await params.cli.monitor('mono-repo-go/hello-vendor', {
file: 'vendor/vendor.json',
});
const fileBody = params.server.popRequest();
t.same(
allProjectsBody.body,
fileBody.body,
'same body for --all-projects and --file=mono-repo-go/hello-vendor/vendor/vendor.json',
);
},
'`monitor mono-repo-go with --all-projects and --detectin-depth=3`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
// mock plugin becuase CI tooling doesn't have go installed
const mockPlugin = {
async inspect() {
return {
plugin: {
name: 'mock',
},
package: {},
};
},
};
const loadPlugin = sinon.stub(params.plugins, 'loadPlugin');
t.teardown(loadPlugin.restore);
loadPlugin.withArgs('golangdep').returns(mockPlugin);
loadPlugin.withArgs('gomodules').returns(mockPlugin);
loadPlugin.withArgs('govendor').returns(mockPlugin);
loadPlugin.callThrough(); // don't mock npm plugin
const result = await params.cli.monitor('mono-repo-go', {
allProjects: true,
detectionDepth: 3,
});
t.match(result, 'golangdep/some/project-id', 'dep project was monitored');
t.match(result, 'gomodules/some/project-id', 'mod project was monitored');
t.match(result, 'npm/graph/some/project-id', 'npm project was monitored');
t.match(
result,
'govendor/some/project-id',
'vendor project was monitored',
);
const requests = params.server
.getRequests()
.filter((req) => req.url.includes('/monitor/'));
t.equal(requests.length, 4, 'correct amount of monitor requests');
requests.forEach((req) => {
t.match(
req.url,
/\/api\/v1\/monitor\/(npm\/graph|golangdep|gomodules|govendor)/,
'puts at correct url',
);
t.notOk(req.body.targetFile, "doesn't send the targetFile");
t.equal(req.method, 'PUT', 'makes PUT request');
t.equal(
req.headers['x-snyk-cli-version'],
params.versionNumber,
'sends version number',
);
});
},
'`monitor gradle-monorepo with --all-projects`': (params, utils) => async (
t,
) => {
utils.chdirWorkspaces();
const simpleGradleGraph = depGraphLib.createFromJSON({
schemaVersion: '1.2.0',
pkgManager: {
name: 'gradle',
},
pkgs: [
{
id: 'gradle-monorepo@0.0.0',
info: {
name: 'gradle-monorepo',
version: '0.0.0',
},
},
],
graph: {
rootNodeId: 'root-node',
nodes: [
{
nodeId: 'root-node',
pkgId: 'gradle-monorepo@0.0.0',
deps: [],
},
],
},
});
const plugin = {
async inspect() {
return {
plugin: {
name: 'bundled:gradle',
runtime: 'unknown',
meta: {},
},
scannedProjects: [
{
meta: {
gradleProjectName: 'root-proj',
versionBuildInfo: {
gradleVersion: '6.5',
},
},
depGraph: simpleGradleGraph,
},
{
meta: {
gradleProjectName: 'root-proj/subproj',
versionBuildInfo: {
gradleVersion: '6.5',
},
},
depGraph: simpleGradleGraph,
},
],
};
},
};
const loadPlugin = sinon.stub(params.plugins, 'loadPlugin');
t.teardown(loadPlugin.restore);
loadPlugin.withArgs('gradle').returns(plugin);
loadPlugin.callThrough();
const result = await params.cli.monitor('gradle-monorepo', {
allProjects: true,
detectionDepth: 3,
d: true,
});
t.match(
result,
'gradle/graph/some/project-id',
'gradle project was monitored',
);
t.match(
result,
'npm/graph/some/project-id',
'gradle project was monitored',
);
const requests = params.server
.getRequests()
.filter((req) => req.url.includes('/monitor/'));
t.equal(requests.length, 3, 'correct amount of monitor requests');
requests.forEach((req) => {
t.match(
req.url,
/\/api\/v1\/monitor\/(npm\/graph|gradle\/graph)/,
'puts at correct url',
);
t.notOk(req.body.targetFile, "doesn't send the targetFile");
t.equal(req.method, 'PUT', 'makes PUT request');
t.equal(
req.headers['x-snyk-cli-version'],
params.versionNumber,
'sends version number',
);
});
},
'`monitor kotlin-monorepo --all-projects` scans kotlin files': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
const simpleGradleGraph = depGraphLib.createFromJSON({
schemaVersion: '1.2.0',
pkgManager: {
name: 'gradle',
},
pkgs: [
{
id: 'gradle-monorepo@0.0.0',
info: {
name: 'gradle-monorepo',
version: '0.0.0',
},
},
],
graph: {
rootNodeId: 'root-node',
nodes: [
{
nodeId: 'root-node',
pkgId: 'gradle-monorepo@0.0.0',
deps: [],
},
],
},
});
const plugin = {
async inspect() {
return {
plugin: {
name: 'bundled:gradle',
runtime: 'unknown',
meta: {},
},
scannedProjects: [
{
meta: {
gradleProjectName: 'root-proj',
versionBuildInfo: {
gradleVersion: '6.5',
},
},
depGraph: simpleGradleGraph,
},
{
meta: {
gradleProjectName: 'root-proj/subproj',
versionBuildInfo: {
gradleVersion: '6.5',
},
},
depGraph: simpleGradleGraph,
},
],
};
},
};
const loadPlugin = sinon.stub(params.plugins, 'loadPlugin');
t.teardown(loadPlugin.restore);
loadPlugin.withArgs('gradle').returns(plugin);
loadPlugin.callThrough();
const result = await params.cli.monitor('kotlin-monorepo', {
allProjects: true,
detectionDepth: 3,
});
t.ok(loadPlugin.withArgs('rubygems').calledOnce, 'calls rubygems plugin');
t.ok(loadPlugin.withArgs('gradle').calledOnce, 'calls gradle plugin');
t.match(
result,
'gradle/graph/some/project-id',
'gradle project was monitored',
);
t.match(
result,
'rubygems/graph/some/project-id',
'rubygems project was monitored',
);
const requests = params.server
.getRequests()
.filter((req) => req.url.includes('/monitor/'));
t.equal(requests.length, 3, 'correct amount of monitor requests');
requests.forEach((req) => {
t.match(
req.url,
/\/api\/v1\/monitor\/(rubygems\/graph|gradle\/graph)/,
'puts at correct url',
);
t.notOk(req.body.targetFile, "doesn't send the targetFile");
t.equal(req.method, 'PUT', 'makes PUT request');
t.equal(
req.headers['x-snyk-cli-version'],
params.versionNumber,
'sends version number',
);
});
},
'`monitor mono-repo-poetry with --all-projects --detection-depth=2`': (
params,
utils,
) => async (t) => {
utils.chdirWorkspaces();
const result = await params.cli.monitor('mono-repo-poetry', {
allProjects: true,
detectionDepth: 2,
});
t.match(
result,
'npm/graph/some/project-id',
'npm project was monitored ',
);
t.match(
result,
'poetry/graph/some/project-id',
'poetry project was monitored ',
);
const requests = params.server.popRequests(2);
requests.forEach((request) => {
const urlOk =
request.url === '/api/v1/monitor/npm' ||
'/api/v1/monitor/poetry/graph';
t.ok(urlOk, 'puts at correct url');
t.equal(request.method, 'PUT', 'makes PUT request');
t.equal(
request.headers['x-snyk-cli-version'],
params.versionNumber,
'sends version number',
);
});
},
},
}; | the_stack |
import { Vec3 } from '../math/Vec3'
import { Transform } from '../math/Transform'
import { RaycastResult } from '../collision/RaycastResult'
import { Utils } from '../utils/Utils'
import type { Body } from '../objects/Body'
export type WheelInfoOptions = ConstructorParameters<typeof WheelInfo>[0]
export type WheelRaycastResult = RaycastResult &
Partial<{
suspensionLength: number
directionWorld: Vec3
groundObject: number
}>
/**
* WheelInfo
*/
export class WheelInfo {
/**
* Max travel distance of the suspension, in meters.
* @default 1
*/
maxSuspensionTravel: number
/**
* Speed to apply to the wheel rotation when the wheel is sliding.
* @default -0.1
*/
customSlidingRotationalSpeed: number
/**
* If the customSlidingRotationalSpeed should be used.
* @default false
*/
useCustomSlidingRotationalSpeed: boolean
/**
* sliding
*/
sliding: boolean
/**
* Connection point, defined locally in the chassis body frame.
*/
chassisConnectionPointLocal: Vec3
/**
* chassisConnectionPointWorld
*/
chassisConnectionPointWorld: Vec3
/**
* directionLocal
*/
directionLocal: Vec3
/**
* directionWorld
*/
directionWorld: Vec3
/**
* axleLocal
*/
axleLocal: Vec3
/**
* axleWorld
*/
axleWorld: Vec3
/**
* suspensionRestLength
* @default 1
*/
suspensionRestLength: number
/**
* suspensionMaxLength
* @default 2
*/
suspensionMaxLength: number
/**
* radius
* @default 1
*/
radius: number
/**
* suspensionStiffness
* @default 100
*/
suspensionStiffness: number
/**
* dampingCompression
* @default 10
*/
dampingCompression: number
/**
* dampingRelaxation
* @default 10
*/
dampingRelaxation: number
/**
* frictionSlip
* @default 10.5
*/
frictionSlip: number
/** forwardAcceleration */
forwardAcceleration: number
/** sideAcceleration */
sideAcceleration: number
/**
* steering
* @default 0
*/
steering: number
/**
* Rotation value, in radians.
* @default 0
*/
rotation: number
/**
* deltaRotation
* @default 0
*/
deltaRotation: number
/**
* rollInfluence
* @default 0.01
*/
rollInfluence: number
/**
* maxSuspensionForce
*/
maxSuspensionForce: number
/**
* engineForce
*/
engineForce: number
/**
* brake
*/
brake: number
/**
* isFrontWheel
* @default true
*/
isFrontWheel: boolean
/**
* clippedInvContactDotSuspension
* @default 1
*/
clippedInvContactDotSuspension: number
/**
* suspensionRelativeVelocity
* @default 0
*/
suspensionRelativeVelocity: number
/**
* suspensionForce
* @default 0
*/
suspensionForce: number
/**
* slipInfo
*/
slipInfo: number
/**
* skidInfo
* @default 0
*/
skidInfo: number
/**
* suspensionLength
* @default 0
*/
suspensionLength: number
/**
* sideImpulse
*/
sideImpulse: number
/**
* forwardImpulse
*/
forwardImpulse: number
/**
* The result from raycasting.
*/
raycastResult: WheelRaycastResult
/**
* Wheel world transform.
*/
worldTransform: Transform
/**
* isInContact
*/
isInContact: boolean
constructor(
options: {
/**
* Connection point, defined locally in the chassis body frame.
*/
chassisConnectionPointLocal?: Vec3
/**
* chassisConnectionPointWorld
*/
chassisConnectionPointWorld?: Vec3
/**
* directionLocal
*/
directionLocal?: Vec3
/**
* directionWorld
*/
directionWorld?: Vec3
/**
* axleLocal
*/
axleLocal?: Vec3
/**
* axleWorld
*/
axleWorld?: Vec3
/**
* suspensionRestLength
* @default 1
*/
suspensionRestLength?: number
/**
* suspensionMaxLength
* @default 2
*/
suspensionMaxLength?: number
/**
* radius
* @default 1
*/
radius?: number
/**
* suspensionStiffness
* @default 100
*/
suspensionStiffness?: number
/**
* dampingCompression
* @default 10
*/
dampingCompression?: number
/**
* dampingRelaxation
* @default 10
*/
dampingRelaxation?: number
/**
* frictionSlip
* @default 10.5
*/
frictionSlip?: number
/** forwardAcceleration */
forwardAcceleration?: number
/** sideAcceleration */
sideAcceleration?: number
/**
* steering
* @default 0
*/
steering?: number
/**
* Rotation value, in radians.
* @default 0
*/
rotation?: number
/**
* deltaRotation
* @default 0
*/
deltaRotation?: number
/**
* rollInfluence
* @default 0.01
*/
rollInfluence?: number
/**
* maxSuspensionForce
*/
maxSuspensionForce?: number
/**
* isFrontWheel
* @default true
*/
isFrontWheel?: boolean
/**
* clippedInvContactDotSuspension
* @default 1
*/
clippedInvContactDotSuspension?: number
/**
* suspensionRelativeVelocity
* @default 0
*/
suspensionRelativeVelocity?: number
/**
* suspensionForce
* @default 0
*/
suspensionForce?: number
/**
* slipInfo
*/
slipInfo?: number
/**
* skidInfo
* @default 0
*/
skidInfo?: number
/**
* suspensionLength
* @default 0
*/
suspensionLength?: number
/**
* Max travel distance of the suspension, in meters.
* @default 1
*/
maxSuspensionTravel?: number
/**
* If the customSlidingRotationalSpeed should be used.
* @default false
*/
useCustomSlidingRotationalSpeed?: boolean
/**
* Speed to apply to the wheel rotation when the wheel is sliding.
* @default -0.1
*/
customSlidingRotationalSpeed?: number
} = {}
) {
options = Utils.defaults(options, {
chassisConnectionPointLocal: new Vec3(),
chassisConnectionPointWorld: new Vec3(),
directionLocal: new Vec3(),
directionWorld: new Vec3(),
axleLocal: new Vec3(),
axleWorld: new Vec3(),
suspensionRestLength: 1,
suspensionMaxLength: 2,
radius: 1,
suspensionStiffness: 100,
dampingCompression: 10,
dampingRelaxation: 10,
frictionSlip: 10.5,
forwardAcceleration: 1,
sideAcceleration: 1,
steering: 0,
rotation: 0,
deltaRotation: 0,
rollInfluence: 0.01,
maxSuspensionForce: Number.MAX_VALUE,
isFrontWheel: true,
clippedInvContactDotSuspension: 1,
suspensionRelativeVelocity: 0,
suspensionForce: 0,
slipInfo: 0,
skidInfo: 0,
suspensionLength: 0,
maxSuspensionTravel: 1,
useCustomSlidingRotationalSpeed: false,
customSlidingRotationalSpeed: -0.1,
})
this.maxSuspensionTravel = options.maxSuspensionTravel!
this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed!
this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed!
this.sliding = false
this.chassisConnectionPointLocal = options.chassisConnectionPointLocal!.clone()
this.chassisConnectionPointWorld = options.chassisConnectionPointWorld!.clone()
this.directionLocal = options.directionLocal!.clone()
this.directionWorld = options.directionWorld!.clone()
this.axleLocal = options.axleLocal!.clone()
this.axleWorld = options.axleWorld!.clone()
this.suspensionRestLength = options.suspensionRestLength!
this.suspensionMaxLength = options.suspensionMaxLength!
this.radius = options.radius!
this.suspensionStiffness = options.suspensionStiffness!
this.dampingCompression = options.dampingCompression!
this.dampingRelaxation = options.dampingRelaxation!
this.frictionSlip = options.frictionSlip!
this.forwardAcceleration = options.forwardAcceleration!
this.sideAcceleration = options.sideAcceleration!
this.steering = 0
this.rotation = 0
this.deltaRotation = 0
this.rollInfluence = options.rollInfluence!
this.maxSuspensionForce = options.maxSuspensionForce!
this.engineForce = 0
this.brake = 0
this.isFrontWheel = options.isFrontWheel!
this.clippedInvContactDotSuspension = 1
this.suspensionRelativeVelocity = 0
this.suspensionForce = 0
this.slipInfo = 0
this.skidInfo = 0
this.suspensionLength = 0
this.sideImpulse = 0
this.forwardImpulse = 0
this.raycastResult = new RaycastResult()
this.worldTransform = new Transform()
this.isInContact = false
}
updateWheel(chassis: Body): void {
const raycastResult = this.raycastResult
if (this.isInContact) {
const project = raycastResult.hitNormalWorld.dot(raycastResult.directionWorld!)
raycastResult.hitPointWorld.vsub(chassis.position, relpos)
chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint)
const projVel = raycastResult.hitNormalWorld.dot(chassis_velocity_at_contactPoint)
if (project >= -0.1) {
this.suspensionRelativeVelocity = 0.0
this.clippedInvContactDotSuspension = 1.0 / 0.1
} else {
const inv = -1 / project
this.suspensionRelativeVelocity = projVel * inv
this.clippedInvContactDotSuspension = inv
}
} else {
// Not in contact : position wheel in a nice (rest length) position
raycastResult.suspensionLength = this.suspensionRestLength
this.suspensionRelativeVelocity = 0.0
raycastResult.directionWorld!.scale(-1, raycastResult.hitNormalWorld)
this.clippedInvContactDotSuspension = 1.0
}
}
}
const chassis_velocity_at_contactPoint = new Vec3()
const relpos = new Vec3() | the_stack |
import {Class, Initable, Range, AnyTiming, Timing, Easing, LinearRange} from "@swim/util";
import {Affinity, MemberFastenerClass, Property} from "@swim/component";
import {AnyLength, Length, R2Point, R2Box} from "@swim/math";
import {AnyFont, Font, AnyColor, Color} from "@swim/style";
import {Look, ThemeAnimator} from "@swim/theme";
import {View, ViewRef} from "@swim/view";
import type {ChartViewObserver} from "./ChartViewObserver";
import {ScaledViewInit, ScaledView} from "../scaled/ScaledView";
import {AnyGraphView, GraphView} from "../graph/GraphView";
import type {AnyAxisView, AxisViewInit, AxisView} from "../axis/AxisView";
import {TopAxisView} from "../axis/TopAxisView";
import {RightAxisView} from "../axis/RightAxisView";
import {BottomAxisView} from "../axis/BottomAxisView";
import {LeftAxisView} from "../axis/LeftAxisView";
/** @public */
export type AnyChartView<X = unknown, Y = unknown> = ChartView<X, Y> | ChartViewInit<X, Y>;
/** @public */
export interface ChartViewInit<X = unknown, Y = unknown> extends ScaledViewInit<X, Y> {
graph?: AnyGraphView<X, Y>;
topAxis?: AnyAxisView<X> | true;
rightAxis?: AnyAxisView<Y> | true;
bottomAxis?: AnyAxisView<X> | true;
leftAxis?: AnyAxisView<Y> | true;
gutterTop?: AnyLength;
gutterRight?: AnyLength;
gutterBottom?: AnyLength;
gutterLeft?: AnyLength;
borderColor?: AnyColor;
borderWidth?: number;
borderSerif?: number;
tickMarkColor?: AnyColor;
tickMarkWidth?: number;
tickMarkLength?: number;
tickLabelPadding?: number;
tickTransition?: AnyTiming;
gridLineColor?: AnyColor;
gridLineWidth?: number;
font?: AnyFont;
textColor?: AnyColor;
}
/** @public */
export class ChartView<X = unknown, Y = unknown> extends ScaledView<X, Y> {
override readonly observerType?: Class<ChartViewObserver<X, Y>>;
@ThemeAnimator({type: Length, value: Length.px(20)})
readonly gutterTop!: ThemeAnimator<this, Length, AnyLength>;
@ThemeAnimator({type: Length, value: Length.px(40)})
readonly gutterRight!: ThemeAnimator<this, Length, AnyLength>;
@ThemeAnimator({type: Length, value: Length.px(20)})
readonly gutterBottom!: ThemeAnimator<this, Length, AnyLength>;
@ThemeAnimator({type: Length, value: Length.px(40)})
readonly gutterLeft!: ThemeAnimator<this, Length, AnyLength>;
@ThemeAnimator({type: Color, value: null, look: Look.neutralColor})
readonly borderColor!: ThemeAnimator<this, Color | null, AnyColor | null>;
@ThemeAnimator({type: Number, value: 1})
readonly borderWidth!: ThemeAnimator<this, number>;
@ThemeAnimator({type: Number, value: 6})
readonly borderSerif!: ThemeAnimator<this, number>;
@ThemeAnimator({type: Color, value: null, look: Look.neutralColor})
readonly tickMarkColor!: ThemeAnimator<this, Color | null, AnyColor | null>;
@ThemeAnimator({type: Number, value: 1})
readonly tickMarkWidth!: ThemeAnimator<this, number>;
@ThemeAnimator({type: Number, value: 6})
readonly tickMarkLength!: ThemeAnimator<this, number>;
@ThemeAnimator({type: Number, value: 2})
readonly tickLabelPadding!: ThemeAnimator<this, number>;
@Property({
type: Timing,
initValue(): Timing {
return Easing.cubicOut.withDuration(250);
},
})
readonly tickTransition!: Property<this, Timing, AnyTiming>;
@ThemeAnimator({type: Color, value: null, look: Look.subduedColor})
readonly gridLineColor!: ThemeAnimator<this, Color | null, AnyColor | null>;
@ThemeAnimator({type: Number, value: 0})
readonly gridLineWidth!: ThemeAnimator<this, number>;
@ThemeAnimator({type: Font, value: null, inherits: true})
readonly font!: ThemeAnimator<this, Font | null, AnyFont | null>;
@ThemeAnimator({type: Color, value: null, look: Look.mutedColor})
readonly textColor!: ThemeAnimator<this, Color | null, AnyColor | null>;
override xRange(): Range<number> | null {
const frame = this.viewFrame;
const gutterLeft = this.gutterLeft.getValue().pxValue(frame.width);
const gutterRight = this.gutterRight.getValue().pxValue(frame.width);
const xRangePadding = this.xRangePadding.value;
const xRangeMin = xRangePadding[0];
const xRangeMax = this.viewFrame.width - gutterRight - gutterLeft - xRangePadding[1];
return LinearRange(xRangeMin, xRangeMax);
}
override yRange(): Range<number> | null {
const frame = this.viewFrame;
const gutterTop = this.gutterTop.getValue().pxValue(frame.height);
const gutterBottom = this.gutterBottom.getValue().pxValue(frame.height);
const yRangePadding = this.yRangePadding.value;
const yRangeMin = yRangePadding[0];
const yRangeMax = this.viewFrame.height - gutterBottom - gutterTop - yRangePadding[1];
return LinearRange(yRangeMax, yRangeMin);
}
@ViewRef<ChartView<X, Y>, GraphView<X, Y>>({
key: true,
type: GraphView,
binds: true,
willAttachView(graphView: GraphView<X, Y>): void {
this.owner.callObservers("viewWillAttachGraph", graphView, this.owner);
},
didDetachView(graphView: GraphView<X, Y>): void {
this.owner.callObservers("viewDidDetachGraph", graphView, this.owner);
},
detectView(view: View): GraphView<X, Y> | null {
return view instanceof GraphView ? view : null;
},
})
readonly graph!: ViewRef<this, GraphView<X, Y>>;
static readonly graph: MemberFastenerClass<ChartView, "graph">;
@ViewRef<ChartView<X, Y>, AxisView<X> & Initable<AxisViewInit<X> | true>>({
key: true,
type: TopAxisView,
binds: true,
willAttachView(topAxisView: AxisView<X>): void {
this.owner.callObservers("viewWillAttachTopAxis", topAxisView, this.owner);
},
didDetachView(topAxisView: AxisView<X>): void {
this.owner.callObservers("viewDidDetachTopAxis", topAxisView, this.owner);
},
detectView(view: View): AxisView<X> | null {
return view instanceof TopAxisView ? view : null;
},
})
readonly topAxis!: ViewRef<this, AxisView<X> & Initable<AxisViewInit<X> | true>>;
static readonly topAxis: MemberFastenerClass<ChartView, "topAxis">;
@ViewRef<ChartView<X, Y>, AxisView<Y> & Initable<AxisViewInit<Y> | true>>({
key: true,
type: RightAxisView,
binds: true,
willAttachView(rightAxisView: AxisView<Y>): void {
this.owner.callObservers("viewWillAttachRightAxis", rightAxisView, this.owner);
},
didDetachView(rightAxisView: AxisView<Y>): void {
this.owner.callObservers("viewDidDetachRightAxis", rightAxisView, this.owner);
},
detectView(view: View): AxisView<Y> | null {
return view instanceof RightAxisView ? view : null;
},
})
readonly rightAxis!: ViewRef<this, AxisView<Y> & Initable<AxisViewInit<Y> | true>>;
static readonly rightAxis: MemberFastenerClass<ChartView, "rightAxis">;
@ViewRef<ChartView<X, Y>, AxisView<X> & Initable<AxisViewInit<X> | true>>({
key: true,
type: BottomAxisView,
binds: true,
willAttachView(bottomAxisView: AxisView<X>): void {
this.owner.callObservers("viewWillAttachBottomAxis", bottomAxisView, this.owner);
},
didDetachView(bottomAxisView: AxisView<X>): void {
this.owner.callObservers("viewDidDetachBottomAxis", bottomAxisView, this.owner);
},
detectView(view: View): AxisView<X> | null {
return view instanceof BottomAxisView ? view : null;
},
})
readonly bottomAxis!: ViewRef<this, AxisView<X> & Initable<AxisViewInit<X> | true>>;
static readonly bottomAxis: MemberFastenerClass<ChartView, "bottomAxis">;
@ViewRef<ChartView<X, Y>, AxisView<Y> & Initable<AxisViewInit<Y> | true>>({
key: true,
type: LeftAxisView,
binds: true,
willAttachView(leftAxisView: AxisView<Y>): void {
this.owner.callObservers("viewWillAttachLeftAxis", leftAxisView, this.owner);
},
didDetachView(leftAxisView: AxisView<Y>): void {
this.owner.callObservers("viewDidDetachLeftAxis", leftAxisView, this.owner);
},
detectView(view: View): AxisView<Y> | null {
return view instanceof LeftAxisView ? view : null;
},
})
readonly leftAxis!: ViewRef<this, AxisView<Y> & Initable<AxisViewInit<Y> | true>>;
static readonly leftAxis: MemberFastenerClass<ChartView, "leftAxis">;
protected override updateScales(): void {
this.layoutChart(this.viewFrame);
super.updateScales();
}
protected layoutChart(frame: R2Box): void {
const gutterTop = this.gutterTop.getValue().pxValue(frame.height);
const gutterRight = this.gutterRight.getValue().pxValue(frame.width);
const gutterBottom = this.gutterBottom.getValue().pxValue(frame.height);
const gutterLeft = this.gutterLeft.getValue().pxValue(frame.width);
const graphTop = frame.yMin + gutterTop;
const graphRight = frame.xMax - gutterRight;
const graphBottom = frame.yMax - gutterBottom;
const graphLeft = frame.xMin + gutterLeft;
const topAxisView = this.topAxis.view;
if (topAxisView !== null) {
topAxisView.setViewFrame(new R2Box(graphLeft, frame.yMin, graphRight, graphBottom));
topAxisView.origin.setState(new R2Point(graphLeft, graphTop), Affinity.Intrinsic);
}
const rightAxisView = this.rightAxis.view;
if (rightAxisView !== null) {
rightAxisView.setViewFrame(new R2Box(graphLeft, graphTop, frame.xMax, graphBottom));
rightAxisView.origin.setState(new R2Point(Math.max(graphLeft, graphRight), graphBottom), Affinity.Intrinsic);
}
const bottomAxisView = this.bottomAxis.view;
if (bottomAxisView !== null) {
bottomAxisView.setViewFrame(new R2Box(graphLeft, graphTop, graphRight, frame.yMax));
bottomAxisView.origin.setState(new R2Point(graphLeft, Math.max(graphTop, graphBottom)), Affinity.Intrinsic);
}
const leftAxisView = this.leftAxis.view;
if (leftAxisView !== null) {
leftAxisView.setViewFrame(new R2Box(frame.xMin, graphTop, graphRight, graphBottom));
leftAxisView.origin.setState(new R2Point(graphLeft, graphBottom), Affinity.Intrinsic);
}
const graphView = this.graph.view;
if (graphView !== null) {
graphView.setViewFrame(new R2Box(graphLeft, graphTop, graphRight, graphBottom));
}
}
override init(init: ChartViewInit<X, Y>): void {
super.init(init);
if (init.graph !== void 0) {
this.graph(init.graph);
}
if (init.topAxis !== void 0) {
this.topAxis(init.topAxis);
}
if (init.rightAxis !== void 0) {
this.rightAxis(init.rightAxis);
}
if (init.bottomAxis !== void 0) {
this.bottomAxis(init.bottomAxis);
}
if (init.leftAxis !== void 0) {
this.leftAxis(init.leftAxis);
}
if (init.gutterTop !== void 0) {
this.gutterTop(init.gutterTop);
}
if (init.gutterRight !== void 0) {
this.gutterRight(init.gutterRight);
}
if (init.gutterBottom !== void 0) {
this.gutterBottom(init.gutterBottom);
}
if (init.gutterLeft !== void 0) {
this.gutterLeft(init.gutterLeft);
}
if (init.borderColor !== void 0) {
this.borderColor(init.borderColor);
}
if (init.borderWidth !== void 0) {
this.borderWidth(init.borderWidth);
}
if (init.borderSerif !== void 0) {
this.borderSerif(init.borderSerif);
}
if (init.tickMarkColor !== void 0) {
this.tickMarkColor(init.tickMarkColor);
}
if (init.tickMarkWidth !== void 0) {
this.tickMarkWidth(init.tickMarkWidth);
}
if (init.tickMarkLength !== void 0) {
this.tickMarkLength(init.tickMarkLength);
}
if (init.tickLabelPadding !== void 0) {
this.tickLabelPadding(init.tickLabelPadding);
}
if (init.tickTransition !== void 0) {
this.tickTransition(init.tickTransition);
}
if (init.gridLineColor !== void 0) {
this.gridLineColor(init.gridLineColor);
}
if (init.gridLineWidth !== void 0) {
this.gridLineWidth(init.gridLineWidth);
}
if (init.font !== void 0) {
this.font(init.font);
}
if (init.textColor !== void 0) {
this.textColor(init.textColor);
}
}
} | the_stack |
interface SccLanguages {
/** A map of file extension to language name. */
extensions: Record<string, string>;
/** An array of language names. */
languages: string[];
}
/** Process the output of `scc --languages`. */
function processSccLanguages(out: string): SccLanguages {
const extensions: Record<string, string> = {};
const languages: string[] = [];
// All lines are in the form of 'Languages (ext1,ext2,...)'
const matches = out.matchAll(/^(.*) \((.*)\)$/gm);
for (const match of matches) {
const language = match[1];
languages.push(language);
const extensions = match[2].split(",");
for (const extension of extensions) {
extensions[extension] = language;
}
}
return { extensions, languages };
}
/** Get the index of the last `:` or `,` in a string, or -1 if not found. */
function lastColonOrCommaIndex(token: string): number {
const colon = token.lastIndexOf(":");
const comma = token.lastIndexOf(",");
return Math.max(colon, comma);
}
/** Trigger when the index of the last colon or comma has changed. */
const triggerColonComma: Fig.Generator["trigger"] = (newToken, oldToken) => {
const newTokenIdx = lastColonOrCommaIndex(newToken);
const oldTokenIdx = lastColonOrCommaIndex(oldToken);
return newTokenIdx !== oldTokenIdx;
};
/** Make the query term everything after the last colon or comma. */
const getQueryTermColonComma: Fig.Generator["getQueryTerm"] = (token) => {
const lastPunctuationIdx = lastColonOrCommaIndex(token);
return token.slice(lastPunctuationIdx + 1);
};
/**
* In a comma-separated key:value string, check if the user is writing a key.
*
* Some test cases:
* ```javascript
* isWritingKey("") === true;
* isWritingKey("key") === true;
* isWritingKey("key:") === false;
* isWritingKey("key:value") === false;
* isWritingKey("key:value,") === true;
* ```
*/
function isWritingKey(token: string) {
const idx = lastColonOrCommaIndex(token);
return idx === -1 || token[idx] === ",";
}
/**
* Generate suggestions for a comma-separated key:value list where the keys
* are arbitrary strings and the values are language names.
*
* Used for --remap-all and --remap-unknown. This is factored out into its
* own value because it is shared by those two options.
*
* Even though the user is entering an arbitrary string, it's okay
* to be dumb about parsing colons and commas because SCC just calls
* `strings.Split` on the input.
* https://github.com/boyter/scc/blob/cb04a8d/processor/workers.go#L500-L501
*/
const generateStringToLanguage: Fig.Generator = {
trigger: triggerColonComma,
getQueryTerm: getQueryTermColonComma,
script: "scc --languages",
postProcess: (out, tokens) => {
const { languages } = processSccLanguages(out);
const lastToken = tokens[tokens.length - 1];
// If we're writing a string, suggest nothing
if (isWritingKey(lastToken)) {
return [];
}
// We're writing a language name, suggest names
return languages.map((language) => ({ name: language }));
},
};
/** The formats that SCC can output. */
const suggestOutputFormats: Fig.Suggestion[] = [
{ name: "tabular", icon: "fig://icon?type=string" },
{ name: "wide", icon: "fig://icon?type=string" },
{ name: "json", icon: "fig://icon?type=string" },
{ name: "csv", icon: "fig://icon?type=string" },
{ name: "csv-stream", icon: "fig://icon?type=string" },
{ name: "cloc-yaml", icon: "fig://icon?type=string" },
{ name: "html", icon: "fig://icon?type=string" },
{ name: "html-table", icon: "fig://icon?type=string" },
{ name: "sql", icon: "fig://icon?type=string" },
{ name: "sql-insert", icon: "fig://icon?type=string" },
];
/**
* Get the size of the Drivemaker's Kilobyte. It shrinks by 4 bytes each year,
* for marketing reasons.
*
* @see https://xkcd.com/394
*
* Test cases:
* ```
* getDriveKB(1984) === 1024;
* getDriveKB(2013) === 908;
* ```
*/
function getDriveKB(year: number): number {
// What's the significance of 1984? That's Randall's birth year. Possibly a
// coincidence, but he does love hiding little easter eggs in his comics.
return 1024 - (year - 1984) * 4;
}
/** The current size of the Drivemaker's Kilobyte */
const driveKB = getDriveKB(new Date().getFullYear());
const completionSpec: Fig.Spec = {
name: "scc",
description:
"Sloc, Cloc and Code. Count lines of code in a directory with complexity estimation",
options: [
{
name: "--avg-wage",
description: "Average salary value used for COCOMO calculations",
args: {
name: "int",
default: "56286",
},
},
{
name: "--binary",
description: "Disable binary file detection",
},
{
name: "--by-file",
description: "Display output for every file",
},
{
name: "--ci",
description: "Enable CI output settings where stdout is ASCII",
},
{
name: "--cocomo-project-type",
description:
'Change the COCOMO model type (allows custom models, eg. "name,1,1,1,1")',
args: {
name: "string",
default: "organic",
suggestions: [
{ name: "organic", icon: "fig://icon?type=string" },
{ name: "semi-detached", icon: "fig://icon?type=string" },
{ name: "embedded", icon: "fig://icon?type=string" },
],
},
},
{
name: "--count-as",
description:
"Count a file extension as a language (comma-separated key:value list, eg. jst:js,tpl:Markdown)",
args: {
name: "string",
generators: {
trigger: triggerColonComma,
getQueryTerm: getQueryTermColonComma,
script: "scc --languages",
postProcess: (out, tokens) => {
const { extensions, languages } = processSccLanguages(out);
const lastToken = tokens[tokens.length - 1];
// If we're writing a file extension, suggest known extensions
if (isWritingKey(lastToken)) {
return Object.entries(extensions).map(
([extension, language]) => ({
name: extension,
description: language,
})
);
}
// We're writing a language name
return languages.map((language) => ({ name: language }));
},
},
},
},
{
name: "--debug",
description: "Enable debug output",
},
{
name: "--exclude-dir",
description: "Directories to exclude",
args: {
name: "strings",
generators: {
template: "folders",
getQueryTerm: ",",
},
},
},
{
name: "--file-gc-count",
description: "Number of files to parse before turning the GC on",
args: {
name: "int",
default: "10000",
},
},
{
name: ["-f", "--format"],
description: "Set output format",
args: {
name: "string",
default: "tabular",
suggestions: suggestOutputFormats,
},
},
{
name: "--format-multi",
description:
"Multiple outputs with different formats (comma-separated key:value list, eg. tabular:stdout,csv:scc.csv)",
args: {
name: "string",
generators: {
trigger: triggerColonComma,
getQueryTerm: getQueryTermColonComma,
custom: async (tokens, executeShellCommand) => {
const lastToken = tokens[tokens.length - 1];
// If we're writing a format, suggest supported formats
if (isWritingKey(lastToken)) {
return suggestOutputFormats;
}
// We're writing an output, suggest stdout
const out = await executeShellCommand("ls -lAF1");
const suggestions: Fig.Suggestion[] = out
.split("\n")
.map((path) => ({
name: path.slice(path.lastIndexOf("/") + 1),
icon: `fig://${path}`,
}));
suggestions.push({ name: "stdout", priority: 75 });
return suggestions;
},
},
},
},
{
name: "--gen",
description: "Identify generated files",
},
{
name: "--generated-markers",
insertValue: "--generated-markers '{cursor}'",
description:
"Identify generated files by the presence of a string (comma-separated list)",
args: {
name: "strings",
default: "do not edit,<auto-generated />",
},
},
{
name: ["-h", "--help"],
description: "Help for scc",
},
{
name: ["-i", "--include-ext"],
description: "Limit to these file extensions (comma-separated list)",
args: {
name: "strings",
generators: {
getQueryTerm: ",",
script: "scc --languages",
postProcess: (out) => {
const { extensions } = processSccLanguages(out);
return Object.entries(extensions).map(([extension, language]) => ({
name: extension,
description: language,
icon: "fig://icon?type=string",
}));
},
},
},
},
{
name: "--include-symlinks",
description: "Count symbolic links",
},
{
name: ["-l", "--languages"],
description: "Print supported languages and extensions",
},
{
name: "--large-byte-count",
description: "Number of bytes a file can contain before being omitted",
args: {
name: "int",
default: "1000000",
},
},
{
name: "--large-line-count",
description: "Number of lines a file can contain before being omitted",
args: {
name: "int",
default: "40000",
},
},
{
name: "--min",
description: "Identify minified files",
},
{
name: ["-z", "--min-gen"],
description: "Identify minified or generated files",
},
{
name: "--min-gen-line-length",
description:
"Number of bytes per average line for file to be considered minified or generated",
args: {
name: "int",
default: "255",
},
},
{
name: "--no-cocomo",
description: "Skip COCOMO calculation",
},
{
name: ["-c", "--no-complexity"],
description: "Skip code complexity calculation",
},
{
name: ["-d", "--no-duplicates"],
description: "Remove duplicate files from stats and output",
},
{
name: "--no-gen",
description: "Ignore generated files in output (implies --gen)",
},
{
name: "--no-gitignore",
description: "Disables .gitignore file logic",
},
{
name: "--no-ignore",
description: "Disables .ignore file logic",
},
{
name: "--no-large",
description:
"Ignore files over certain byte and line size set by --max-line-count and --max-byte-count",
},
{
name: "--no-min",
description: "Ignore minified files in output (implies --min)",
},
{
name: "--no-min-gen",
description:
"Ignore minified or generated files in output (implies --min-gen)",
},
{
name: "--no-size",
description: "Remove size calculation output",
},
{
name: ["-M", "--not-match"],
insertValue: "-M '{cursor}'",
description: "Ignore files and directories matching regular expression",
args: {
name: "regex",
},
},
{
name: ["-o", "--output"],
description: "Output filename (defaults to stdout if not provided)",
args: {
name: "string",
template: "filepaths",
},
},
{
name: "--remap-all",
description:
'Inspect every file and set its type by checking for a string (comma-separated key:value list, eg. "-*- C++ -*-":"C Header")',
args: {
name: "string",
generators: generateStringToLanguage,
},
},
{
name: "--remap-unknown",
description:
'Inspect files of unknown type and set its type by checking for a string (comma-separated key:value list, eg. "-*- C++ -*-":"C Header")',
args: {
name: "string",
generators: generateStringToLanguage,
},
},
{
name: "--size-unit",
description: "Set the unit used for file size output",
args: {
name: "string",
description: "See https://xkcd.com/394/",
default: "si",
suggestions: [
{
name: "si",
icon: "fig://icon?type=string",
description: "1000^2 bytes",
},
{
name: "binary",
icon: "fig://icon?type=string",
description: "1024^2 bytes",
},
{
name: "mixed",
icon: "fig://icon?type=string",
description: "1,024,000 bytes (Binary kilobytes, SI megabytes)",
},
{
name: "xkcd-kb",
icon: "fig://icon?type=string",
description: "1000 bytes during leap years, 1024 otherwise",
},
{
name: "xkcd-kelly",
icon: "fig://icon?type=string",
description:
"1012 bytes (a compromise between 1000 and 1024 bytes)",
},
{
name: "xkcd-imaginary",
icon: "fig://icon?type=string",
description: "1024*sqrt(-1) bytes (used in quantum computing)",
},
{
name: "xkcd-intel",
icon: "fig://icon?type=string",
description: "1023.937528 bytes (calculated on Pentium FPU)",
},
{
name: "xkcd-drive",
icon: "fig://icon?type=string",
description: `Currently ${driveKB} bytes (shrinks by 4 each year for marketing reasons)`,
},
{
name: "xkcd-bakers",
icon: "fig://icon?type=string",
description:
"1152 bytes (9 bits per byte, because you're such a good customer)",
},
],
},
},
{
name: ["-s", "--sort"],
description: "Column to sort by",
args: {
name: "string",
default: "files",
suggestions: [
{ name: "files", icon: "fig://icon?type=string" },
{ name: "name", icon: "fig://icon?type=string" },
{ name: "lines", icon: "fig://icon?type=string" },
{ name: "blanks", icon: "fig://icon?type=string" },
{ name: "code", icon: "fig://icon?type=string" },
{ name: "comments", icon: "fig://icon?type=string" },
{ name: "complexity", icon: "fig://icon?type=string" },
],
},
},
{
name: "--sql-project",
description:
"Use supplied name as the project identifier for the current run. Only valid with the '--format sql' or '--format sql-insert' option",
args: {
name: "string",
},
},
{
name: ["-t", "--trace"],
description:
"Enable trace output (not recommended when processing multiple files)",
},
{
name: ["-v", "--verbose"],
description: "Verbose output",
},
{
name: "--version",
description: "Version for scc",
},
{
name: ["-w", "--wide"],
description:
"Wider output with additional statistics (implies --complexity)",
},
],
args: {
name: "files or directories",
template: ["filepaths", "folders"],
isOptional: true,
isVariadic: true,
},
};
export default completionSpec; | the_stack |
import Long from "long";
import _m0 from "protobufjs/minimal";
import { Params } from "../../gravity/v1/genesis";
import {
SignerSetTx,
BatchTx,
ContractCallTx,
SendToEthereum,
} from "../../gravity/v1/gravity";
import {
PageRequest,
PageResponse,
} from "../../cosmos/base/query/v1beta1/pagination";
import {
SignerSetTxConfirmation,
ContractCallTxConfirmation,
BatchTxConfirmation,
} from "../../gravity/v1/msgs";
import { Coin } from "../../cosmos/base/v1beta1/coin";
export const protobufPackage = "gravity.v1";
/** rpc Params */
export interface ParamsRequest {}
export interface ParamsResponse {
params?: Params;
}
/** rpc SignerSetTx */
export interface SignerSetTxRequest {
signerSetNonce: Long;
}
export interface LatestSignerSetTxRequest {}
export interface SignerSetTxResponse {
signerSet?: SignerSetTx;
}
/** rpc BatchTx */
export interface BatchTxRequest {
tokenContract: string;
batchNonce: Long;
}
export interface BatchTxResponse {
batch?: BatchTx;
}
/** rpc ContractCallTx */
export interface ContractCallTxRequest {
invalidationScope: Uint8Array;
invalidationNonce: Long;
}
export interface ContractCallTxResponse {
logicCall?: ContractCallTx;
}
/** rpc SignerSetTxConfirmations */
export interface SignerSetTxConfirmationsRequest {
signerSetNonce: Long;
}
export interface SignerSetTxConfirmationsResponse {
signatures: SignerSetTxConfirmation[];
}
/** rpc SignerSetTxs */
export interface SignerSetTxsRequest {
pagination?: PageRequest;
}
export interface SignerSetTxsResponse {
signerSets: SignerSetTx[];
pagination?: PageResponse;
}
/** rpc BatchTxs */
export interface BatchTxsRequest {
pagination?: PageRequest;
}
export interface BatchTxsResponse {
batches: BatchTx[];
pagination?: PageResponse;
}
/** rpc ContractCallTxs */
export interface ContractCallTxsRequest {
pagination?: PageRequest;
}
export interface ContractCallTxsResponse {
calls: ContractCallTx[];
pagination?: PageResponse;
}
/** rpc UnsignedSignerSetTxs */
export interface UnsignedSignerSetTxsRequest {
/**
* NOTE: this is an sdk.AccAddress and can represent either the
* orchestartor address or the cooresponding validator address
*/
address: string;
}
export interface UnsignedSignerSetTxsResponse {
signerSets: SignerSetTx[];
}
export interface UnsignedBatchTxsRequest {
/**
* NOTE: this is an sdk.AccAddress and can represent either the
* orchestrator address or the cooresponding validator address
*/
address: string;
}
export interface UnsignedBatchTxsResponse {
/** Note these are returned with the signature empty */
batches: BatchTx[];
}
/** rpc UnsignedContractCallTxs */
export interface UnsignedContractCallTxsRequest {
address: string;
}
export interface UnsignedContractCallTxsResponse {
calls: ContractCallTx[];
}
export interface BatchTxFeesRequest {}
export interface BatchTxFeesResponse {
fees: Coin[];
}
export interface ContractCallTxConfirmationsRequest {
invalidationScope: Uint8Array;
invalidationNonce: Long;
}
export interface ContractCallTxConfirmationsResponse {
signatures: ContractCallTxConfirmation[];
}
export interface BatchTxConfirmationsRequest {
batchNonce: Long;
tokenContract: string;
}
export interface BatchTxConfirmationsResponse {
signatures: BatchTxConfirmation[];
}
export interface LastSubmittedEthereumEventRequest {
address: string;
}
export interface LastSubmittedEthereumEventResponse {
eventNonce: Long;
}
export interface ERC20ToDenomRequest {
erc20: string;
}
export interface ERC20ToDenomResponse {
denom: string;
cosmosOriginated: boolean;
}
export interface DenomToERC20Request {
denom: string;
}
export interface DenomToERC20Response {
erc20: string;
cosmosOriginated: boolean;
}
export interface DelegateKeysByValidatorRequest {
validatorAddress: string;
}
export interface DelegateKeysByValidatorResponse {
ethAddress: string;
orchestratorAddress: string;
}
export interface DelegateKeysByEthereumSignerRequest {
ethereumSigner: string;
}
export interface DelegateKeysByEthereumSignerResponse {
validatorAddress: string;
orchestratorAddress: string;
}
export interface DelegateKeysByOrchestratorRequest {
orchestratorAddress: string;
}
export interface DelegateKeysByOrchestratorResponse {
validatorAddress: string;
ethereumSigner: string;
}
/** NOTE: if there is no sender address, return all */
export interface BatchedSendToEthereumsRequest {
/**
* todo: figure out how to paginate given n Batches with m Send To Ethereums
* cosmos.base.query.v1beta1.PageRequest pagination = 2;
*/
senderAddress: string;
}
export interface BatchedSendToEthereumsResponse {
/** cosmos.base.query.v1beta1.PageResponse pagination = 2; */
sendToEthereums: SendToEthereum[];
}
export interface UnbatchedSendToEthereumsRequest {
senderAddress: string;
pagination?: PageRequest;
}
export interface UnbatchedSendToEthereumsResponse {
sendToEthereums: SendToEthereum[];
pagination?: PageResponse;
}
const baseParamsRequest: object = {};
export const ParamsRequest = {
encode(
_: ParamsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): ParamsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseParamsRequest } as ParamsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_: any): ParamsRequest {
const message = { ...baseParamsRequest } as ParamsRequest;
return message;
},
toJSON(_: ParamsRequest): unknown {
const obj: any = {};
return obj;
},
fromPartial(_: DeepPartial<ParamsRequest>): ParamsRequest {
const message = { ...baseParamsRequest } as ParamsRequest;
return message;
},
};
const baseParamsResponse: object = {};
export const ParamsResponse = {
encode(
message: ParamsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.params !== undefined) {
Params.encode(message.params, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): ParamsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseParamsResponse } as ParamsResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.params = Params.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ParamsResponse {
const message = { ...baseParamsResponse } as ParamsResponse;
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromJSON(object.params);
} else {
message.params = undefined;
}
return message;
},
toJSON(message: ParamsResponse): unknown {
const obj: any = {};
message.params !== undefined &&
(obj.params = message.params ? Params.toJSON(message.params) : undefined);
return obj;
},
fromPartial(object: DeepPartial<ParamsResponse>): ParamsResponse {
const message = { ...baseParamsResponse } as ParamsResponse;
if (object.params !== undefined && object.params !== null) {
message.params = Params.fromPartial(object.params);
} else {
message.params = undefined;
}
return message;
},
};
const baseSignerSetTxRequest: object = { signerSetNonce: Long.UZERO };
export const SignerSetTxRequest = {
encode(
message: SignerSetTxRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (!message.signerSetNonce.isZero()) {
writer.uint32(8).uint64(message.signerSetNonce);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): SignerSetTxRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSignerSetTxRequest } as SignerSetTxRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.signerSetNonce = reader.uint64() as Long;
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SignerSetTxRequest {
const message = { ...baseSignerSetTxRequest } as SignerSetTxRequest;
if (object.signerSetNonce !== undefined && object.signerSetNonce !== null) {
message.signerSetNonce = Long.fromString(object.signerSetNonce);
} else {
message.signerSetNonce = Long.UZERO;
}
return message;
},
toJSON(message: SignerSetTxRequest): unknown {
const obj: any = {};
message.signerSetNonce !== undefined &&
(obj.signerSetNonce = (message.signerSetNonce || Long.UZERO).toString());
return obj;
},
fromPartial(object: DeepPartial<SignerSetTxRequest>): SignerSetTxRequest {
const message = { ...baseSignerSetTxRequest } as SignerSetTxRequest;
if (object.signerSetNonce !== undefined && object.signerSetNonce !== null) {
message.signerSetNonce = object.signerSetNonce as Long;
} else {
message.signerSetNonce = Long.UZERO;
}
return message;
},
};
const baseLatestSignerSetTxRequest: object = {};
export const LatestSignerSetTxRequest = {
encode(
_: LatestSignerSetTxRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): LatestSignerSetTxRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseLatestSignerSetTxRequest,
} as LatestSignerSetTxRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_: any): LatestSignerSetTxRequest {
const message = {
...baseLatestSignerSetTxRequest,
} as LatestSignerSetTxRequest;
return message;
},
toJSON(_: LatestSignerSetTxRequest): unknown {
const obj: any = {};
return obj;
},
fromPartial(
_: DeepPartial<LatestSignerSetTxRequest>
): LatestSignerSetTxRequest {
const message = {
...baseLatestSignerSetTxRequest,
} as LatestSignerSetTxRequest;
return message;
},
};
const baseSignerSetTxResponse: object = {};
export const SignerSetTxResponse = {
encode(
message: SignerSetTxResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.signerSet !== undefined) {
SignerSetTx.encode(message.signerSet, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): SignerSetTxResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSignerSetTxResponse } as SignerSetTxResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.signerSet = SignerSetTx.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SignerSetTxResponse {
const message = { ...baseSignerSetTxResponse } as SignerSetTxResponse;
if (object.signerSet !== undefined && object.signerSet !== null) {
message.signerSet = SignerSetTx.fromJSON(object.signerSet);
} else {
message.signerSet = undefined;
}
return message;
},
toJSON(message: SignerSetTxResponse): unknown {
const obj: any = {};
message.signerSet !== undefined &&
(obj.signerSet = message.signerSet
? SignerSetTx.toJSON(message.signerSet)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<SignerSetTxResponse>): SignerSetTxResponse {
const message = { ...baseSignerSetTxResponse } as SignerSetTxResponse;
if (object.signerSet !== undefined && object.signerSet !== null) {
message.signerSet = SignerSetTx.fromPartial(object.signerSet);
} else {
message.signerSet = undefined;
}
return message;
},
};
const baseBatchTxRequest: object = {
tokenContract: "",
batchNonce: Long.UZERO,
};
export const BatchTxRequest = {
encode(
message: BatchTxRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.tokenContract !== "") {
writer.uint32(10).string(message.tokenContract);
}
if (!message.batchNonce.isZero()) {
writer.uint32(16).uint64(message.batchNonce);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): BatchTxRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseBatchTxRequest } as BatchTxRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.tokenContract = reader.string();
break;
case 2:
message.batchNonce = reader.uint64() as Long;
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): BatchTxRequest {
const message = { ...baseBatchTxRequest } as BatchTxRequest;
if (object.tokenContract !== undefined && object.tokenContract !== null) {
message.tokenContract = String(object.tokenContract);
} else {
message.tokenContract = "";
}
if (object.batchNonce !== undefined && object.batchNonce !== null) {
message.batchNonce = Long.fromString(object.batchNonce);
} else {
message.batchNonce = Long.UZERO;
}
return message;
},
toJSON(message: BatchTxRequest): unknown {
const obj: any = {};
message.tokenContract !== undefined &&
(obj.tokenContract = message.tokenContract);
message.batchNonce !== undefined &&
(obj.batchNonce = (message.batchNonce || Long.UZERO).toString());
return obj;
},
fromPartial(object: DeepPartial<BatchTxRequest>): BatchTxRequest {
const message = { ...baseBatchTxRequest } as BatchTxRequest;
if (object.tokenContract !== undefined && object.tokenContract !== null) {
message.tokenContract = object.tokenContract;
} else {
message.tokenContract = "";
}
if (object.batchNonce !== undefined && object.batchNonce !== null) {
message.batchNonce = object.batchNonce as Long;
} else {
message.batchNonce = Long.UZERO;
}
return message;
},
};
const baseBatchTxResponse: object = {};
export const BatchTxResponse = {
encode(
message: BatchTxResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.batch !== undefined) {
BatchTx.encode(message.batch, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): BatchTxResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseBatchTxResponse } as BatchTxResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.batch = BatchTx.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): BatchTxResponse {
const message = { ...baseBatchTxResponse } as BatchTxResponse;
if (object.batch !== undefined && object.batch !== null) {
message.batch = BatchTx.fromJSON(object.batch);
} else {
message.batch = undefined;
}
return message;
},
toJSON(message: BatchTxResponse): unknown {
const obj: any = {};
message.batch !== undefined &&
(obj.batch = message.batch ? BatchTx.toJSON(message.batch) : undefined);
return obj;
},
fromPartial(object: DeepPartial<BatchTxResponse>): BatchTxResponse {
const message = { ...baseBatchTxResponse } as BatchTxResponse;
if (object.batch !== undefined && object.batch !== null) {
message.batch = BatchTx.fromPartial(object.batch);
} else {
message.batch = undefined;
}
return message;
},
};
const baseContractCallTxRequest: object = { invalidationNonce: Long.UZERO };
export const ContractCallTxRequest = {
encode(
message: ContractCallTxRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.invalidationScope.length !== 0) {
writer.uint32(10).bytes(message.invalidationScope);
}
if (!message.invalidationNonce.isZero()) {
writer.uint32(16).uint64(message.invalidationNonce);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): ContractCallTxRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseContractCallTxRequest } as ContractCallTxRequest;
message.invalidationScope = new Uint8Array();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.invalidationScope = reader.bytes();
break;
case 2:
message.invalidationNonce = reader.uint64() as Long;
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ContractCallTxRequest {
const message = { ...baseContractCallTxRequest } as ContractCallTxRequest;
message.invalidationScope = new Uint8Array();
if (
object.invalidationScope !== undefined &&
object.invalidationScope !== null
) {
message.invalidationScope = bytesFromBase64(object.invalidationScope);
}
if (
object.invalidationNonce !== undefined &&
object.invalidationNonce !== null
) {
message.invalidationNonce = Long.fromString(object.invalidationNonce);
} else {
message.invalidationNonce = Long.UZERO;
}
return message;
},
toJSON(message: ContractCallTxRequest): unknown {
const obj: any = {};
message.invalidationScope !== undefined &&
(obj.invalidationScope = base64FromBytes(
message.invalidationScope !== undefined
? message.invalidationScope
: new Uint8Array()
));
message.invalidationNonce !== undefined &&
(obj.invalidationNonce = (
message.invalidationNonce || Long.UZERO
).toString());
return obj;
},
fromPartial(
object: DeepPartial<ContractCallTxRequest>
): ContractCallTxRequest {
const message = { ...baseContractCallTxRequest } as ContractCallTxRequest;
if (
object.invalidationScope !== undefined &&
object.invalidationScope !== null
) {
message.invalidationScope = object.invalidationScope;
} else {
message.invalidationScope = new Uint8Array();
}
if (
object.invalidationNonce !== undefined &&
object.invalidationNonce !== null
) {
message.invalidationNonce = object.invalidationNonce as Long;
} else {
message.invalidationNonce = Long.UZERO;
}
return message;
},
};
const baseContractCallTxResponse: object = {};
export const ContractCallTxResponse = {
encode(
message: ContractCallTxResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.logicCall !== undefined) {
ContractCallTx.encode(
message.logicCall,
writer.uint32(10).fork()
).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): ContractCallTxResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseContractCallTxResponse } as ContractCallTxResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.logicCall = ContractCallTx.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ContractCallTxResponse {
const message = { ...baseContractCallTxResponse } as ContractCallTxResponse;
if (object.logicCall !== undefined && object.logicCall !== null) {
message.logicCall = ContractCallTx.fromJSON(object.logicCall);
} else {
message.logicCall = undefined;
}
return message;
},
toJSON(message: ContractCallTxResponse): unknown {
const obj: any = {};
message.logicCall !== undefined &&
(obj.logicCall = message.logicCall
? ContractCallTx.toJSON(message.logicCall)
: undefined);
return obj;
},
fromPartial(
object: DeepPartial<ContractCallTxResponse>
): ContractCallTxResponse {
const message = { ...baseContractCallTxResponse } as ContractCallTxResponse;
if (object.logicCall !== undefined && object.logicCall !== null) {
message.logicCall = ContractCallTx.fromPartial(object.logicCall);
} else {
message.logicCall = undefined;
}
return message;
},
};
const baseSignerSetTxConfirmationsRequest: object = {
signerSetNonce: Long.UZERO,
};
export const SignerSetTxConfirmationsRequest = {
encode(
message: SignerSetTxConfirmationsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (!message.signerSetNonce.isZero()) {
writer.uint32(8).uint64(message.signerSetNonce);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): SignerSetTxConfirmationsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseSignerSetTxConfirmationsRequest,
} as SignerSetTxConfirmationsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.signerSetNonce = reader.uint64() as Long;
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SignerSetTxConfirmationsRequest {
const message = {
...baseSignerSetTxConfirmationsRequest,
} as SignerSetTxConfirmationsRequest;
if (object.signerSetNonce !== undefined && object.signerSetNonce !== null) {
message.signerSetNonce = Long.fromString(object.signerSetNonce);
} else {
message.signerSetNonce = Long.UZERO;
}
return message;
},
toJSON(message: SignerSetTxConfirmationsRequest): unknown {
const obj: any = {};
message.signerSetNonce !== undefined &&
(obj.signerSetNonce = (message.signerSetNonce || Long.UZERO).toString());
return obj;
},
fromPartial(
object: DeepPartial<SignerSetTxConfirmationsRequest>
): SignerSetTxConfirmationsRequest {
const message = {
...baseSignerSetTxConfirmationsRequest,
} as SignerSetTxConfirmationsRequest;
if (object.signerSetNonce !== undefined && object.signerSetNonce !== null) {
message.signerSetNonce = object.signerSetNonce as Long;
} else {
message.signerSetNonce = Long.UZERO;
}
return message;
},
};
const baseSignerSetTxConfirmationsResponse: object = {};
export const SignerSetTxConfirmationsResponse = {
encode(
message: SignerSetTxConfirmationsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.signatures) {
SignerSetTxConfirmation.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): SignerSetTxConfirmationsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseSignerSetTxConfirmationsResponse,
} as SignerSetTxConfirmationsResponse;
message.signatures = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.signatures.push(
SignerSetTxConfirmation.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SignerSetTxConfirmationsResponse {
const message = {
...baseSignerSetTxConfirmationsResponse,
} as SignerSetTxConfirmationsResponse;
message.signatures = [];
if (object.signatures !== undefined && object.signatures !== null) {
for (const e of object.signatures) {
message.signatures.push(SignerSetTxConfirmation.fromJSON(e));
}
}
return message;
},
toJSON(message: SignerSetTxConfirmationsResponse): unknown {
const obj: any = {};
if (message.signatures) {
obj.signatures = message.signatures.map((e) =>
e ? SignerSetTxConfirmation.toJSON(e) : undefined
);
} else {
obj.signatures = [];
}
return obj;
},
fromPartial(
object: DeepPartial<SignerSetTxConfirmationsResponse>
): SignerSetTxConfirmationsResponse {
const message = {
...baseSignerSetTxConfirmationsResponse,
} as SignerSetTxConfirmationsResponse;
message.signatures = [];
if (object.signatures !== undefined && object.signatures !== null) {
for (const e of object.signatures) {
message.signatures.push(SignerSetTxConfirmation.fromPartial(e));
}
}
return message;
},
};
const baseSignerSetTxsRequest: object = {};
export const SignerSetTxsRequest = {
encode(
message: SignerSetTxsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.pagination !== undefined) {
PageRequest.encode(message.pagination, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): SignerSetTxsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSignerSetTxsRequest } as SignerSetTxsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.pagination = PageRequest.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SignerSetTxsRequest {
const message = { ...baseSignerSetTxsRequest } as SignerSetTxsRequest;
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageRequest.fromJSON(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
toJSON(message: SignerSetTxsRequest): unknown {
const obj: any = {};
message.pagination !== undefined &&
(obj.pagination = message.pagination
? PageRequest.toJSON(message.pagination)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<SignerSetTxsRequest>): SignerSetTxsRequest {
const message = { ...baseSignerSetTxsRequest } as SignerSetTxsRequest;
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageRequest.fromPartial(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
};
const baseSignerSetTxsResponse: object = {};
export const SignerSetTxsResponse = {
encode(
message: SignerSetTxsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.signerSets) {
SignerSetTx.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.pagination !== undefined) {
PageResponse.encode(
message.pagination,
writer.uint32(18).fork()
).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): SignerSetTxsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSignerSetTxsResponse } as SignerSetTxsResponse;
message.signerSets = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.signerSets.push(SignerSetTx.decode(reader, reader.uint32()));
break;
case 2:
message.pagination = PageResponse.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SignerSetTxsResponse {
const message = { ...baseSignerSetTxsResponse } as SignerSetTxsResponse;
message.signerSets = [];
if (object.signerSets !== undefined && object.signerSets !== null) {
for (const e of object.signerSets) {
message.signerSets.push(SignerSetTx.fromJSON(e));
}
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageResponse.fromJSON(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
toJSON(message: SignerSetTxsResponse): unknown {
const obj: any = {};
if (message.signerSets) {
obj.signerSets = message.signerSets.map((e) =>
e ? SignerSetTx.toJSON(e) : undefined
);
} else {
obj.signerSets = [];
}
message.pagination !== undefined &&
(obj.pagination = message.pagination
? PageResponse.toJSON(message.pagination)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<SignerSetTxsResponse>): SignerSetTxsResponse {
const message = { ...baseSignerSetTxsResponse } as SignerSetTxsResponse;
message.signerSets = [];
if (object.signerSets !== undefined && object.signerSets !== null) {
for (const e of object.signerSets) {
message.signerSets.push(SignerSetTx.fromPartial(e));
}
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageResponse.fromPartial(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
};
const baseBatchTxsRequest: object = {};
export const BatchTxsRequest = {
encode(
message: BatchTxsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.pagination !== undefined) {
PageRequest.encode(message.pagination, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): BatchTxsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseBatchTxsRequest } as BatchTxsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.pagination = PageRequest.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): BatchTxsRequest {
const message = { ...baseBatchTxsRequest } as BatchTxsRequest;
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageRequest.fromJSON(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
toJSON(message: BatchTxsRequest): unknown {
const obj: any = {};
message.pagination !== undefined &&
(obj.pagination = message.pagination
? PageRequest.toJSON(message.pagination)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<BatchTxsRequest>): BatchTxsRequest {
const message = { ...baseBatchTxsRequest } as BatchTxsRequest;
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageRequest.fromPartial(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
};
const baseBatchTxsResponse: object = {};
export const BatchTxsResponse = {
encode(
message: BatchTxsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.batches) {
BatchTx.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.pagination !== undefined) {
PageResponse.encode(
message.pagination,
writer.uint32(18).fork()
).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): BatchTxsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseBatchTxsResponse } as BatchTxsResponse;
message.batches = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.batches.push(BatchTx.decode(reader, reader.uint32()));
break;
case 2:
message.pagination = PageResponse.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): BatchTxsResponse {
const message = { ...baseBatchTxsResponse } as BatchTxsResponse;
message.batches = [];
if (object.batches !== undefined && object.batches !== null) {
for (const e of object.batches) {
message.batches.push(BatchTx.fromJSON(e));
}
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageResponse.fromJSON(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
toJSON(message: BatchTxsResponse): unknown {
const obj: any = {};
if (message.batches) {
obj.batches = message.batches.map((e) =>
e ? BatchTx.toJSON(e) : undefined
);
} else {
obj.batches = [];
}
message.pagination !== undefined &&
(obj.pagination = message.pagination
? PageResponse.toJSON(message.pagination)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<BatchTxsResponse>): BatchTxsResponse {
const message = { ...baseBatchTxsResponse } as BatchTxsResponse;
message.batches = [];
if (object.batches !== undefined && object.batches !== null) {
for (const e of object.batches) {
message.batches.push(BatchTx.fromPartial(e));
}
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageResponse.fromPartial(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
};
const baseContractCallTxsRequest: object = {};
export const ContractCallTxsRequest = {
encode(
message: ContractCallTxsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.pagination !== undefined) {
PageRequest.encode(message.pagination, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): ContractCallTxsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseContractCallTxsRequest } as ContractCallTxsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.pagination = PageRequest.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ContractCallTxsRequest {
const message = { ...baseContractCallTxsRequest } as ContractCallTxsRequest;
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageRequest.fromJSON(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
toJSON(message: ContractCallTxsRequest): unknown {
const obj: any = {};
message.pagination !== undefined &&
(obj.pagination = message.pagination
? PageRequest.toJSON(message.pagination)
: undefined);
return obj;
},
fromPartial(
object: DeepPartial<ContractCallTxsRequest>
): ContractCallTxsRequest {
const message = { ...baseContractCallTxsRequest } as ContractCallTxsRequest;
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageRequest.fromPartial(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
};
const baseContractCallTxsResponse: object = {};
export const ContractCallTxsResponse = {
encode(
message: ContractCallTxsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.calls) {
ContractCallTx.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.pagination !== undefined) {
PageResponse.encode(
message.pagination,
writer.uint32(18).fork()
).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): ContractCallTxsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseContractCallTxsResponse,
} as ContractCallTxsResponse;
message.calls = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.calls.push(ContractCallTx.decode(reader, reader.uint32()));
break;
case 2:
message.pagination = PageResponse.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ContractCallTxsResponse {
const message = {
...baseContractCallTxsResponse,
} as ContractCallTxsResponse;
message.calls = [];
if (object.calls !== undefined && object.calls !== null) {
for (const e of object.calls) {
message.calls.push(ContractCallTx.fromJSON(e));
}
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageResponse.fromJSON(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
toJSON(message: ContractCallTxsResponse): unknown {
const obj: any = {};
if (message.calls) {
obj.calls = message.calls.map((e) =>
e ? ContractCallTx.toJSON(e) : undefined
);
} else {
obj.calls = [];
}
message.pagination !== undefined &&
(obj.pagination = message.pagination
? PageResponse.toJSON(message.pagination)
: undefined);
return obj;
},
fromPartial(
object: DeepPartial<ContractCallTxsResponse>
): ContractCallTxsResponse {
const message = {
...baseContractCallTxsResponse,
} as ContractCallTxsResponse;
message.calls = [];
if (object.calls !== undefined && object.calls !== null) {
for (const e of object.calls) {
message.calls.push(ContractCallTx.fromPartial(e));
}
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageResponse.fromPartial(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
};
const baseUnsignedSignerSetTxsRequest: object = { address: "" };
export const UnsignedSignerSetTxsRequest = {
encode(
message: UnsignedSignerSetTxsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.address !== "") {
writer.uint32(10).string(message.address);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): UnsignedSignerSetTxsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUnsignedSignerSetTxsRequest,
} as UnsignedSignerSetTxsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.address = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): UnsignedSignerSetTxsRequest {
const message = {
...baseUnsignedSignerSetTxsRequest,
} as UnsignedSignerSetTxsRequest;
if (object.address !== undefined && object.address !== null) {
message.address = String(object.address);
} else {
message.address = "";
}
return message;
},
toJSON(message: UnsignedSignerSetTxsRequest): unknown {
const obj: any = {};
message.address !== undefined && (obj.address = message.address);
return obj;
},
fromPartial(
object: DeepPartial<UnsignedSignerSetTxsRequest>
): UnsignedSignerSetTxsRequest {
const message = {
...baseUnsignedSignerSetTxsRequest,
} as UnsignedSignerSetTxsRequest;
if (object.address !== undefined && object.address !== null) {
message.address = object.address;
} else {
message.address = "";
}
return message;
},
};
const baseUnsignedSignerSetTxsResponse: object = {};
export const UnsignedSignerSetTxsResponse = {
encode(
message: UnsignedSignerSetTxsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.signerSets) {
SignerSetTx.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): UnsignedSignerSetTxsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUnsignedSignerSetTxsResponse,
} as UnsignedSignerSetTxsResponse;
message.signerSets = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.signerSets.push(SignerSetTx.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): UnsignedSignerSetTxsResponse {
const message = {
...baseUnsignedSignerSetTxsResponse,
} as UnsignedSignerSetTxsResponse;
message.signerSets = [];
if (object.signerSets !== undefined && object.signerSets !== null) {
for (const e of object.signerSets) {
message.signerSets.push(SignerSetTx.fromJSON(e));
}
}
return message;
},
toJSON(message: UnsignedSignerSetTxsResponse): unknown {
const obj: any = {};
if (message.signerSets) {
obj.signerSets = message.signerSets.map((e) =>
e ? SignerSetTx.toJSON(e) : undefined
);
} else {
obj.signerSets = [];
}
return obj;
},
fromPartial(
object: DeepPartial<UnsignedSignerSetTxsResponse>
): UnsignedSignerSetTxsResponse {
const message = {
...baseUnsignedSignerSetTxsResponse,
} as UnsignedSignerSetTxsResponse;
message.signerSets = [];
if (object.signerSets !== undefined && object.signerSets !== null) {
for (const e of object.signerSets) {
message.signerSets.push(SignerSetTx.fromPartial(e));
}
}
return message;
},
};
const baseUnsignedBatchTxsRequest: object = { address: "" };
export const UnsignedBatchTxsRequest = {
encode(
message: UnsignedBatchTxsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.address !== "") {
writer.uint32(10).string(message.address);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): UnsignedBatchTxsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUnsignedBatchTxsRequest,
} as UnsignedBatchTxsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.address = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): UnsignedBatchTxsRequest {
const message = {
...baseUnsignedBatchTxsRequest,
} as UnsignedBatchTxsRequest;
if (object.address !== undefined && object.address !== null) {
message.address = String(object.address);
} else {
message.address = "";
}
return message;
},
toJSON(message: UnsignedBatchTxsRequest): unknown {
const obj: any = {};
message.address !== undefined && (obj.address = message.address);
return obj;
},
fromPartial(
object: DeepPartial<UnsignedBatchTxsRequest>
): UnsignedBatchTxsRequest {
const message = {
...baseUnsignedBatchTxsRequest,
} as UnsignedBatchTxsRequest;
if (object.address !== undefined && object.address !== null) {
message.address = object.address;
} else {
message.address = "";
}
return message;
},
};
const baseUnsignedBatchTxsResponse: object = {};
export const UnsignedBatchTxsResponse = {
encode(
message: UnsignedBatchTxsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.batches) {
BatchTx.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): UnsignedBatchTxsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUnsignedBatchTxsResponse,
} as UnsignedBatchTxsResponse;
message.batches = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.batches.push(BatchTx.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): UnsignedBatchTxsResponse {
const message = {
...baseUnsignedBatchTxsResponse,
} as UnsignedBatchTxsResponse;
message.batches = [];
if (object.batches !== undefined && object.batches !== null) {
for (const e of object.batches) {
message.batches.push(BatchTx.fromJSON(e));
}
}
return message;
},
toJSON(message: UnsignedBatchTxsResponse): unknown {
const obj: any = {};
if (message.batches) {
obj.batches = message.batches.map((e) =>
e ? BatchTx.toJSON(e) : undefined
);
} else {
obj.batches = [];
}
return obj;
},
fromPartial(
object: DeepPartial<UnsignedBatchTxsResponse>
): UnsignedBatchTxsResponse {
const message = {
...baseUnsignedBatchTxsResponse,
} as UnsignedBatchTxsResponse;
message.batches = [];
if (object.batches !== undefined && object.batches !== null) {
for (const e of object.batches) {
message.batches.push(BatchTx.fromPartial(e));
}
}
return message;
},
};
const baseUnsignedContractCallTxsRequest: object = { address: "" };
export const UnsignedContractCallTxsRequest = {
encode(
message: UnsignedContractCallTxsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.address !== "") {
writer.uint32(10).string(message.address);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): UnsignedContractCallTxsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUnsignedContractCallTxsRequest,
} as UnsignedContractCallTxsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.address = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): UnsignedContractCallTxsRequest {
const message = {
...baseUnsignedContractCallTxsRequest,
} as UnsignedContractCallTxsRequest;
if (object.address !== undefined && object.address !== null) {
message.address = String(object.address);
} else {
message.address = "";
}
return message;
},
toJSON(message: UnsignedContractCallTxsRequest): unknown {
const obj: any = {};
message.address !== undefined && (obj.address = message.address);
return obj;
},
fromPartial(
object: DeepPartial<UnsignedContractCallTxsRequest>
): UnsignedContractCallTxsRequest {
const message = {
...baseUnsignedContractCallTxsRequest,
} as UnsignedContractCallTxsRequest;
if (object.address !== undefined && object.address !== null) {
message.address = object.address;
} else {
message.address = "";
}
return message;
},
};
const baseUnsignedContractCallTxsResponse: object = {};
export const UnsignedContractCallTxsResponse = {
encode(
message: UnsignedContractCallTxsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.calls) {
ContractCallTx.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): UnsignedContractCallTxsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUnsignedContractCallTxsResponse,
} as UnsignedContractCallTxsResponse;
message.calls = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.calls.push(ContractCallTx.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): UnsignedContractCallTxsResponse {
const message = {
...baseUnsignedContractCallTxsResponse,
} as UnsignedContractCallTxsResponse;
message.calls = [];
if (object.calls !== undefined && object.calls !== null) {
for (const e of object.calls) {
message.calls.push(ContractCallTx.fromJSON(e));
}
}
return message;
},
toJSON(message: UnsignedContractCallTxsResponse): unknown {
const obj: any = {};
if (message.calls) {
obj.calls = message.calls.map((e) =>
e ? ContractCallTx.toJSON(e) : undefined
);
} else {
obj.calls = [];
}
return obj;
},
fromPartial(
object: DeepPartial<UnsignedContractCallTxsResponse>
): UnsignedContractCallTxsResponse {
const message = {
...baseUnsignedContractCallTxsResponse,
} as UnsignedContractCallTxsResponse;
message.calls = [];
if (object.calls !== undefined && object.calls !== null) {
for (const e of object.calls) {
message.calls.push(ContractCallTx.fromPartial(e));
}
}
return message;
},
};
const baseBatchTxFeesRequest: object = {};
export const BatchTxFeesRequest = {
encode(
_: BatchTxFeesRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): BatchTxFeesRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseBatchTxFeesRequest } as BatchTxFeesRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(_: any): BatchTxFeesRequest {
const message = { ...baseBatchTxFeesRequest } as BatchTxFeesRequest;
return message;
},
toJSON(_: BatchTxFeesRequest): unknown {
const obj: any = {};
return obj;
},
fromPartial(_: DeepPartial<BatchTxFeesRequest>): BatchTxFeesRequest {
const message = { ...baseBatchTxFeesRequest } as BatchTxFeesRequest;
return message;
},
};
const baseBatchTxFeesResponse: object = {};
export const BatchTxFeesResponse = {
encode(
message: BatchTxFeesResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.fees) {
Coin.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): BatchTxFeesResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseBatchTxFeesResponse } as BatchTxFeesResponse;
message.fees = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.fees.push(Coin.decode(reader, reader.uint32()));
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): BatchTxFeesResponse {
const message = { ...baseBatchTxFeesResponse } as BatchTxFeesResponse;
message.fees = [];
if (object.fees !== undefined && object.fees !== null) {
for (const e of object.fees) {
message.fees.push(Coin.fromJSON(e));
}
}
return message;
},
toJSON(message: BatchTxFeesResponse): unknown {
const obj: any = {};
if (message.fees) {
obj.fees = message.fees.map((e) => (e ? Coin.toJSON(e) : undefined));
} else {
obj.fees = [];
}
return obj;
},
fromPartial(object: DeepPartial<BatchTxFeesResponse>): BatchTxFeesResponse {
const message = { ...baseBatchTxFeesResponse } as BatchTxFeesResponse;
message.fees = [];
if (object.fees !== undefined && object.fees !== null) {
for (const e of object.fees) {
message.fees.push(Coin.fromPartial(e));
}
}
return message;
},
};
const baseContractCallTxConfirmationsRequest: object = {
invalidationNonce: Long.UZERO,
};
export const ContractCallTxConfirmationsRequest = {
encode(
message: ContractCallTxConfirmationsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.invalidationScope.length !== 0) {
writer.uint32(10).bytes(message.invalidationScope);
}
if (!message.invalidationNonce.isZero()) {
writer.uint32(16).uint64(message.invalidationNonce);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): ContractCallTxConfirmationsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseContractCallTxConfirmationsRequest,
} as ContractCallTxConfirmationsRequest;
message.invalidationScope = new Uint8Array();
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.invalidationScope = reader.bytes();
break;
case 2:
message.invalidationNonce = reader.uint64() as Long;
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ContractCallTxConfirmationsRequest {
const message = {
...baseContractCallTxConfirmationsRequest,
} as ContractCallTxConfirmationsRequest;
message.invalidationScope = new Uint8Array();
if (
object.invalidationScope !== undefined &&
object.invalidationScope !== null
) {
message.invalidationScope = bytesFromBase64(object.invalidationScope);
}
if (
object.invalidationNonce !== undefined &&
object.invalidationNonce !== null
) {
message.invalidationNonce = Long.fromString(object.invalidationNonce);
} else {
message.invalidationNonce = Long.UZERO;
}
return message;
},
toJSON(message: ContractCallTxConfirmationsRequest): unknown {
const obj: any = {};
message.invalidationScope !== undefined &&
(obj.invalidationScope = base64FromBytes(
message.invalidationScope !== undefined
? message.invalidationScope
: new Uint8Array()
));
message.invalidationNonce !== undefined &&
(obj.invalidationNonce = (
message.invalidationNonce || Long.UZERO
).toString());
return obj;
},
fromPartial(
object: DeepPartial<ContractCallTxConfirmationsRequest>
): ContractCallTxConfirmationsRequest {
const message = {
...baseContractCallTxConfirmationsRequest,
} as ContractCallTxConfirmationsRequest;
if (
object.invalidationScope !== undefined &&
object.invalidationScope !== null
) {
message.invalidationScope = object.invalidationScope;
} else {
message.invalidationScope = new Uint8Array();
}
if (
object.invalidationNonce !== undefined &&
object.invalidationNonce !== null
) {
message.invalidationNonce = object.invalidationNonce as Long;
} else {
message.invalidationNonce = Long.UZERO;
}
return message;
},
};
const baseContractCallTxConfirmationsResponse: object = {};
export const ContractCallTxConfirmationsResponse = {
encode(
message: ContractCallTxConfirmationsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.signatures) {
ContractCallTxConfirmation.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): ContractCallTxConfirmationsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseContractCallTxConfirmationsResponse,
} as ContractCallTxConfirmationsResponse;
message.signatures = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.signatures.push(
ContractCallTxConfirmation.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ContractCallTxConfirmationsResponse {
const message = {
...baseContractCallTxConfirmationsResponse,
} as ContractCallTxConfirmationsResponse;
message.signatures = [];
if (object.signatures !== undefined && object.signatures !== null) {
for (const e of object.signatures) {
message.signatures.push(ContractCallTxConfirmation.fromJSON(e));
}
}
return message;
},
toJSON(message: ContractCallTxConfirmationsResponse): unknown {
const obj: any = {};
if (message.signatures) {
obj.signatures = message.signatures.map((e) =>
e ? ContractCallTxConfirmation.toJSON(e) : undefined
);
} else {
obj.signatures = [];
}
return obj;
},
fromPartial(
object: DeepPartial<ContractCallTxConfirmationsResponse>
): ContractCallTxConfirmationsResponse {
const message = {
...baseContractCallTxConfirmationsResponse,
} as ContractCallTxConfirmationsResponse;
message.signatures = [];
if (object.signatures !== undefined && object.signatures !== null) {
for (const e of object.signatures) {
message.signatures.push(ContractCallTxConfirmation.fromPartial(e));
}
}
return message;
},
};
const baseBatchTxConfirmationsRequest: object = {
batchNonce: Long.UZERO,
tokenContract: "",
};
export const BatchTxConfirmationsRequest = {
encode(
message: BatchTxConfirmationsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (!message.batchNonce.isZero()) {
writer.uint32(8).uint64(message.batchNonce);
}
if (message.tokenContract !== "") {
writer.uint32(18).string(message.tokenContract);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): BatchTxConfirmationsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseBatchTxConfirmationsRequest,
} as BatchTxConfirmationsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.batchNonce = reader.uint64() as Long;
break;
case 2:
message.tokenContract = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): BatchTxConfirmationsRequest {
const message = {
...baseBatchTxConfirmationsRequest,
} as BatchTxConfirmationsRequest;
if (object.batchNonce !== undefined && object.batchNonce !== null) {
message.batchNonce = Long.fromString(object.batchNonce);
} else {
message.batchNonce = Long.UZERO;
}
if (object.tokenContract !== undefined && object.tokenContract !== null) {
message.tokenContract = String(object.tokenContract);
} else {
message.tokenContract = "";
}
return message;
},
toJSON(message: BatchTxConfirmationsRequest): unknown {
const obj: any = {};
message.batchNonce !== undefined &&
(obj.batchNonce = (message.batchNonce || Long.UZERO).toString());
message.tokenContract !== undefined &&
(obj.tokenContract = message.tokenContract);
return obj;
},
fromPartial(
object: DeepPartial<BatchTxConfirmationsRequest>
): BatchTxConfirmationsRequest {
const message = {
...baseBatchTxConfirmationsRequest,
} as BatchTxConfirmationsRequest;
if (object.batchNonce !== undefined && object.batchNonce !== null) {
message.batchNonce = object.batchNonce as Long;
} else {
message.batchNonce = Long.UZERO;
}
if (object.tokenContract !== undefined && object.tokenContract !== null) {
message.tokenContract = object.tokenContract;
} else {
message.tokenContract = "";
}
return message;
},
};
const baseBatchTxConfirmationsResponse: object = {};
export const BatchTxConfirmationsResponse = {
encode(
message: BatchTxConfirmationsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.signatures) {
BatchTxConfirmation.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): BatchTxConfirmationsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseBatchTxConfirmationsResponse,
} as BatchTxConfirmationsResponse;
message.signatures = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.signatures.push(
BatchTxConfirmation.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): BatchTxConfirmationsResponse {
const message = {
...baseBatchTxConfirmationsResponse,
} as BatchTxConfirmationsResponse;
message.signatures = [];
if (object.signatures !== undefined && object.signatures !== null) {
for (const e of object.signatures) {
message.signatures.push(BatchTxConfirmation.fromJSON(e));
}
}
return message;
},
toJSON(message: BatchTxConfirmationsResponse): unknown {
const obj: any = {};
if (message.signatures) {
obj.signatures = message.signatures.map((e) =>
e ? BatchTxConfirmation.toJSON(e) : undefined
);
} else {
obj.signatures = [];
}
return obj;
},
fromPartial(
object: DeepPartial<BatchTxConfirmationsResponse>
): BatchTxConfirmationsResponse {
const message = {
...baseBatchTxConfirmationsResponse,
} as BatchTxConfirmationsResponse;
message.signatures = [];
if (object.signatures !== undefined && object.signatures !== null) {
for (const e of object.signatures) {
message.signatures.push(BatchTxConfirmation.fromPartial(e));
}
}
return message;
},
};
const baseLastSubmittedEthereumEventRequest: object = { address: "" };
export const LastSubmittedEthereumEventRequest = {
encode(
message: LastSubmittedEthereumEventRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.address !== "") {
writer.uint32(10).string(message.address);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): LastSubmittedEthereumEventRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseLastSubmittedEthereumEventRequest,
} as LastSubmittedEthereumEventRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.address = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): LastSubmittedEthereumEventRequest {
const message = {
...baseLastSubmittedEthereumEventRequest,
} as LastSubmittedEthereumEventRequest;
if (object.address !== undefined && object.address !== null) {
message.address = String(object.address);
} else {
message.address = "";
}
return message;
},
toJSON(message: LastSubmittedEthereumEventRequest): unknown {
const obj: any = {};
message.address !== undefined && (obj.address = message.address);
return obj;
},
fromPartial(
object: DeepPartial<LastSubmittedEthereumEventRequest>
): LastSubmittedEthereumEventRequest {
const message = {
...baseLastSubmittedEthereumEventRequest,
} as LastSubmittedEthereumEventRequest;
if (object.address !== undefined && object.address !== null) {
message.address = object.address;
} else {
message.address = "";
}
return message;
},
};
const baseLastSubmittedEthereumEventResponse: object = {
eventNonce: Long.UZERO,
};
export const LastSubmittedEthereumEventResponse = {
encode(
message: LastSubmittedEthereumEventResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (!message.eventNonce.isZero()) {
writer.uint32(8).uint64(message.eventNonce);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): LastSubmittedEthereumEventResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseLastSubmittedEthereumEventResponse,
} as LastSubmittedEthereumEventResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.eventNonce = reader.uint64() as Long;
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): LastSubmittedEthereumEventResponse {
const message = {
...baseLastSubmittedEthereumEventResponse,
} as LastSubmittedEthereumEventResponse;
if (object.eventNonce !== undefined && object.eventNonce !== null) {
message.eventNonce = Long.fromString(object.eventNonce);
} else {
message.eventNonce = Long.UZERO;
}
return message;
},
toJSON(message: LastSubmittedEthereumEventResponse): unknown {
const obj: any = {};
message.eventNonce !== undefined &&
(obj.eventNonce = (message.eventNonce || Long.UZERO).toString());
return obj;
},
fromPartial(
object: DeepPartial<LastSubmittedEthereumEventResponse>
): LastSubmittedEthereumEventResponse {
const message = {
...baseLastSubmittedEthereumEventResponse,
} as LastSubmittedEthereumEventResponse;
if (object.eventNonce !== undefined && object.eventNonce !== null) {
message.eventNonce = object.eventNonce as Long;
} else {
message.eventNonce = Long.UZERO;
}
return message;
},
};
const baseERC20ToDenomRequest: object = { erc20: "" };
export const ERC20ToDenomRequest = {
encode(
message: ERC20ToDenomRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.erc20 !== "") {
writer.uint32(10).string(message.erc20);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): ERC20ToDenomRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseERC20ToDenomRequest } as ERC20ToDenomRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.erc20 = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ERC20ToDenomRequest {
const message = { ...baseERC20ToDenomRequest } as ERC20ToDenomRequest;
if (object.erc20 !== undefined && object.erc20 !== null) {
message.erc20 = String(object.erc20);
} else {
message.erc20 = "";
}
return message;
},
toJSON(message: ERC20ToDenomRequest): unknown {
const obj: any = {};
message.erc20 !== undefined && (obj.erc20 = message.erc20);
return obj;
},
fromPartial(object: DeepPartial<ERC20ToDenomRequest>): ERC20ToDenomRequest {
const message = { ...baseERC20ToDenomRequest } as ERC20ToDenomRequest;
if (object.erc20 !== undefined && object.erc20 !== null) {
message.erc20 = object.erc20;
} else {
message.erc20 = "";
}
return message;
},
};
const baseERC20ToDenomResponse: object = { denom: "", cosmosOriginated: false };
export const ERC20ToDenomResponse = {
encode(
message: ERC20ToDenomResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.denom !== "") {
writer.uint32(10).string(message.denom);
}
if (message.cosmosOriginated === true) {
writer.uint32(16).bool(message.cosmosOriginated);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): ERC20ToDenomResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseERC20ToDenomResponse } as ERC20ToDenomResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.denom = reader.string();
break;
case 2:
message.cosmosOriginated = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ERC20ToDenomResponse {
const message = { ...baseERC20ToDenomResponse } as ERC20ToDenomResponse;
if (object.denom !== undefined && object.denom !== null) {
message.denom = String(object.denom);
} else {
message.denom = "";
}
if (
object.cosmosOriginated !== undefined &&
object.cosmosOriginated !== null
) {
message.cosmosOriginated = Boolean(object.cosmosOriginated);
} else {
message.cosmosOriginated = false;
}
return message;
},
toJSON(message: ERC20ToDenomResponse): unknown {
const obj: any = {};
message.denom !== undefined && (obj.denom = message.denom);
message.cosmosOriginated !== undefined &&
(obj.cosmosOriginated = message.cosmosOriginated);
return obj;
},
fromPartial(object: DeepPartial<ERC20ToDenomResponse>): ERC20ToDenomResponse {
const message = { ...baseERC20ToDenomResponse } as ERC20ToDenomResponse;
if (object.denom !== undefined && object.denom !== null) {
message.denom = object.denom;
} else {
message.denom = "";
}
if (
object.cosmosOriginated !== undefined &&
object.cosmosOriginated !== null
) {
message.cosmosOriginated = object.cosmosOriginated;
} else {
message.cosmosOriginated = false;
}
return message;
},
};
const baseDenomToERC20Request: object = { denom: "" };
export const DenomToERC20Request = {
encode(
message: DenomToERC20Request,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.denom !== "") {
writer.uint32(10).string(message.denom);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): DenomToERC20Request {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseDenomToERC20Request } as DenomToERC20Request;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.denom = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DenomToERC20Request {
const message = { ...baseDenomToERC20Request } as DenomToERC20Request;
if (object.denom !== undefined && object.denom !== null) {
message.denom = String(object.denom);
} else {
message.denom = "";
}
return message;
},
toJSON(message: DenomToERC20Request): unknown {
const obj: any = {};
message.denom !== undefined && (obj.denom = message.denom);
return obj;
},
fromPartial(object: DeepPartial<DenomToERC20Request>): DenomToERC20Request {
const message = { ...baseDenomToERC20Request } as DenomToERC20Request;
if (object.denom !== undefined && object.denom !== null) {
message.denom = object.denom;
} else {
message.denom = "";
}
return message;
},
};
const baseDenomToERC20Response: object = { erc20: "", cosmosOriginated: false };
export const DenomToERC20Response = {
encode(
message: DenomToERC20Response,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.erc20 !== "") {
writer.uint32(10).string(message.erc20);
}
if (message.cosmosOriginated === true) {
writer.uint32(16).bool(message.cosmosOriginated);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): DenomToERC20Response {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseDenomToERC20Response } as DenomToERC20Response;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.erc20 = reader.string();
break;
case 2:
message.cosmosOriginated = reader.bool();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DenomToERC20Response {
const message = { ...baseDenomToERC20Response } as DenomToERC20Response;
if (object.erc20 !== undefined && object.erc20 !== null) {
message.erc20 = String(object.erc20);
} else {
message.erc20 = "";
}
if (
object.cosmosOriginated !== undefined &&
object.cosmosOriginated !== null
) {
message.cosmosOriginated = Boolean(object.cosmosOriginated);
} else {
message.cosmosOriginated = false;
}
return message;
},
toJSON(message: DenomToERC20Response): unknown {
const obj: any = {};
message.erc20 !== undefined && (obj.erc20 = message.erc20);
message.cosmosOriginated !== undefined &&
(obj.cosmosOriginated = message.cosmosOriginated);
return obj;
},
fromPartial(object: DeepPartial<DenomToERC20Response>): DenomToERC20Response {
const message = { ...baseDenomToERC20Response } as DenomToERC20Response;
if (object.erc20 !== undefined && object.erc20 !== null) {
message.erc20 = object.erc20;
} else {
message.erc20 = "";
}
if (
object.cosmosOriginated !== undefined &&
object.cosmosOriginated !== null
) {
message.cosmosOriginated = object.cosmosOriginated;
} else {
message.cosmosOriginated = false;
}
return message;
},
};
const baseDelegateKeysByValidatorRequest: object = { validatorAddress: "" };
export const DelegateKeysByValidatorRequest = {
encode(
message: DelegateKeysByValidatorRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.validatorAddress !== "") {
writer.uint32(10).string(message.validatorAddress);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): DelegateKeysByValidatorRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseDelegateKeysByValidatorRequest,
} as DelegateKeysByValidatorRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.validatorAddress = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DelegateKeysByValidatorRequest {
const message = {
...baseDelegateKeysByValidatorRequest,
} as DelegateKeysByValidatorRequest;
if (
object.validatorAddress !== undefined &&
object.validatorAddress !== null
) {
message.validatorAddress = String(object.validatorAddress);
} else {
message.validatorAddress = "";
}
return message;
},
toJSON(message: DelegateKeysByValidatorRequest): unknown {
const obj: any = {};
message.validatorAddress !== undefined &&
(obj.validatorAddress = message.validatorAddress);
return obj;
},
fromPartial(
object: DeepPartial<DelegateKeysByValidatorRequest>
): DelegateKeysByValidatorRequest {
const message = {
...baseDelegateKeysByValidatorRequest,
} as DelegateKeysByValidatorRequest;
if (
object.validatorAddress !== undefined &&
object.validatorAddress !== null
) {
message.validatorAddress = object.validatorAddress;
} else {
message.validatorAddress = "";
}
return message;
},
};
const baseDelegateKeysByValidatorResponse: object = {
ethAddress: "",
orchestratorAddress: "",
};
export const DelegateKeysByValidatorResponse = {
encode(
message: DelegateKeysByValidatorResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.ethAddress !== "") {
writer.uint32(10).string(message.ethAddress);
}
if (message.orchestratorAddress !== "") {
writer.uint32(18).string(message.orchestratorAddress);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): DelegateKeysByValidatorResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseDelegateKeysByValidatorResponse,
} as DelegateKeysByValidatorResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.ethAddress = reader.string();
break;
case 2:
message.orchestratorAddress = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DelegateKeysByValidatorResponse {
const message = {
...baseDelegateKeysByValidatorResponse,
} as DelegateKeysByValidatorResponse;
if (object.ethAddress !== undefined && object.ethAddress !== null) {
message.ethAddress = String(object.ethAddress);
} else {
message.ethAddress = "";
}
if (
object.orchestratorAddress !== undefined &&
object.orchestratorAddress !== null
) {
message.orchestratorAddress = String(object.orchestratorAddress);
} else {
message.orchestratorAddress = "";
}
return message;
},
toJSON(message: DelegateKeysByValidatorResponse): unknown {
const obj: any = {};
message.ethAddress !== undefined && (obj.ethAddress = message.ethAddress);
message.orchestratorAddress !== undefined &&
(obj.orchestratorAddress = message.orchestratorAddress);
return obj;
},
fromPartial(
object: DeepPartial<DelegateKeysByValidatorResponse>
): DelegateKeysByValidatorResponse {
const message = {
...baseDelegateKeysByValidatorResponse,
} as DelegateKeysByValidatorResponse;
if (object.ethAddress !== undefined && object.ethAddress !== null) {
message.ethAddress = object.ethAddress;
} else {
message.ethAddress = "";
}
if (
object.orchestratorAddress !== undefined &&
object.orchestratorAddress !== null
) {
message.orchestratorAddress = object.orchestratorAddress;
} else {
message.orchestratorAddress = "";
}
return message;
},
};
const baseDelegateKeysByEthereumSignerRequest: object = { ethereumSigner: "" };
export const DelegateKeysByEthereumSignerRequest = {
encode(
message: DelegateKeysByEthereumSignerRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.ethereumSigner !== "") {
writer.uint32(10).string(message.ethereumSigner);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): DelegateKeysByEthereumSignerRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseDelegateKeysByEthereumSignerRequest,
} as DelegateKeysByEthereumSignerRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.ethereumSigner = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DelegateKeysByEthereumSignerRequest {
const message = {
...baseDelegateKeysByEthereumSignerRequest,
} as DelegateKeysByEthereumSignerRequest;
if (object.ethereumSigner !== undefined && object.ethereumSigner !== null) {
message.ethereumSigner = String(object.ethereumSigner);
} else {
message.ethereumSigner = "";
}
return message;
},
toJSON(message: DelegateKeysByEthereumSignerRequest): unknown {
const obj: any = {};
message.ethereumSigner !== undefined &&
(obj.ethereumSigner = message.ethereumSigner);
return obj;
},
fromPartial(
object: DeepPartial<DelegateKeysByEthereumSignerRequest>
): DelegateKeysByEthereumSignerRequest {
const message = {
...baseDelegateKeysByEthereumSignerRequest,
} as DelegateKeysByEthereumSignerRequest;
if (object.ethereumSigner !== undefined && object.ethereumSigner !== null) {
message.ethereumSigner = object.ethereumSigner;
} else {
message.ethereumSigner = "";
}
return message;
},
};
const baseDelegateKeysByEthereumSignerResponse: object = {
validatorAddress: "",
orchestratorAddress: "",
};
export const DelegateKeysByEthereumSignerResponse = {
encode(
message: DelegateKeysByEthereumSignerResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.validatorAddress !== "") {
writer.uint32(10).string(message.validatorAddress);
}
if (message.orchestratorAddress !== "") {
writer.uint32(18).string(message.orchestratorAddress);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): DelegateKeysByEthereumSignerResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseDelegateKeysByEthereumSignerResponse,
} as DelegateKeysByEthereumSignerResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.validatorAddress = reader.string();
break;
case 2:
message.orchestratorAddress = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DelegateKeysByEthereumSignerResponse {
const message = {
...baseDelegateKeysByEthereumSignerResponse,
} as DelegateKeysByEthereumSignerResponse;
if (
object.validatorAddress !== undefined &&
object.validatorAddress !== null
) {
message.validatorAddress = String(object.validatorAddress);
} else {
message.validatorAddress = "";
}
if (
object.orchestratorAddress !== undefined &&
object.orchestratorAddress !== null
) {
message.orchestratorAddress = String(object.orchestratorAddress);
} else {
message.orchestratorAddress = "";
}
return message;
},
toJSON(message: DelegateKeysByEthereumSignerResponse): unknown {
const obj: any = {};
message.validatorAddress !== undefined &&
(obj.validatorAddress = message.validatorAddress);
message.orchestratorAddress !== undefined &&
(obj.orchestratorAddress = message.orchestratorAddress);
return obj;
},
fromPartial(
object: DeepPartial<DelegateKeysByEthereumSignerResponse>
): DelegateKeysByEthereumSignerResponse {
const message = {
...baseDelegateKeysByEthereumSignerResponse,
} as DelegateKeysByEthereumSignerResponse;
if (
object.validatorAddress !== undefined &&
object.validatorAddress !== null
) {
message.validatorAddress = object.validatorAddress;
} else {
message.validatorAddress = "";
}
if (
object.orchestratorAddress !== undefined &&
object.orchestratorAddress !== null
) {
message.orchestratorAddress = object.orchestratorAddress;
} else {
message.orchestratorAddress = "";
}
return message;
},
};
const baseDelegateKeysByOrchestratorRequest: object = {
orchestratorAddress: "",
};
export const DelegateKeysByOrchestratorRequest = {
encode(
message: DelegateKeysByOrchestratorRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.orchestratorAddress !== "") {
writer.uint32(10).string(message.orchestratorAddress);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): DelegateKeysByOrchestratorRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseDelegateKeysByOrchestratorRequest,
} as DelegateKeysByOrchestratorRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.orchestratorAddress = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DelegateKeysByOrchestratorRequest {
const message = {
...baseDelegateKeysByOrchestratorRequest,
} as DelegateKeysByOrchestratorRequest;
if (
object.orchestratorAddress !== undefined &&
object.orchestratorAddress !== null
) {
message.orchestratorAddress = String(object.orchestratorAddress);
} else {
message.orchestratorAddress = "";
}
return message;
},
toJSON(message: DelegateKeysByOrchestratorRequest): unknown {
const obj: any = {};
message.orchestratorAddress !== undefined &&
(obj.orchestratorAddress = message.orchestratorAddress);
return obj;
},
fromPartial(
object: DeepPartial<DelegateKeysByOrchestratorRequest>
): DelegateKeysByOrchestratorRequest {
const message = {
...baseDelegateKeysByOrchestratorRequest,
} as DelegateKeysByOrchestratorRequest;
if (
object.orchestratorAddress !== undefined &&
object.orchestratorAddress !== null
) {
message.orchestratorAddress = object.orchestratorAddress;
} else {
message.orchestratorAddress = "";
}
return message;
},
};
const baseDelegateKeysByOrchestratorResponse: object = {
validatorAddress: "",
ethereumSigner: "",
};
export const DelegateKeysByOrchestratorResponse = {
encode(
message: DelegateKeysByOrchestratorResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.validatorAddress !== "") {
writer.uint32(10).string(message.validatorAddress);
}
if (message.ethereumSigner !== "") {
writer.uint32(18).string(message.ethereumSigner);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): DelegateKeysByOrchestratorResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseDelegateKeysByOrchestratorResponse,
} as DelegateKeysByOrchestratorResponse;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.validatorAddress = reader.string();
break;
case 2:
message.ethereumSigner = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): DelegateKeysByOrchestratorResponse {
const message = {
...baseDelegateKeysByOrchestratorResponse,
} as DelegateKeysByOrchestratorResponse;
if (
object.validatorAddress !== undefined &&
object.validatorAddress !== null
) {
message.validatorAddress = String(object.validatorAddress);
} else {
message.validatorAddress = "";
}
if (object.ethereumSigner !== undefined && object.ethereumSigner !== null) {
message.ethereumSigner = String(object.ethereumSigner);
} else {
message.ethereumSigner = "";
}
return message;
},
toJSON(message: DelegateKeysByOrchestratorResponse): unknown {
const obj: any = {};
message.validatorAddress !== undefined &&
(obj.validatorAddress = message.validatorAddress);
message.ethereumSigner !== undefined &&
(obj.ethereumSigner = message.ethereumSigner);
return obj;
},
fromPartial(
object: DeepPartial<DelegateKeysByOrchestratorResponse>
): DelegateKeysByOrchestratorResponse {
const message = {
...baseDelegateKeysByOrchestratorResponse,
} as DelegateKeysByOrchestratorResponse;
if (
object.validatorAddress !== undefined &&
object.validatorAddress !== null
) {
message.validatorAddress = object.validatorAddress;
} else {
message.validatorAddress = "";
}
if (object.ethereumSigner !== undefined && object.ethereumSigner !== null) {
message.ethereumSigner = object.ethereumSigner;
} else {
message.ethereumSigner = "";
}
return message;
},
};
const baseBatchedSendToEthereumsRequest: object = { senderAddress: "" };
export const BatchedSendToEthereumsRequest = {
encode(
message: BatchedSendToEthereumsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.senderAddress !== "") {
writer.uint32(10).string(message.senderAddress);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): BatchedSendToEthereumsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseBatchedSendToEthereumsRequest,
} as BatchedSendToEthereumsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.senderAddress = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): BatchedSendToEthereumsRequest {
const message = {
...baseBatchedSendToEthereumsRequest,
} as BatchedSendToEthereumsRequest;
if (object.senderAddress !== undefined && object.senderAddress !== null) {
message.senderAddress = String(object.senderAddress);
} else {
message.senderAddress = "";
}
return message;
},
toJSON(message: BatchedSendToEthereumsRequest): unknown {
const obj: any = {};
message.senderAddress !== undefined &&
(obj.senderAddress = message.senderAddress);
return obj;
},
fromPartial(
object: DeepPartial<BatchedSendToEthereumsRequest>
): BatchedSendToEthereumsRequest {
const message = {
...baseBatchedSendToEthereumsRequest,
} as BatchedSendToEthereumsRequest;
if (object.senderAddress !== undefined && object.senderAddress !== null) {
message.senderAddress = object.senderAddress;
} else {
message.senderAddress = "";
}
return message;
},
};
const baseBatchedSendToEthereumsResponse: object = {};
export const BatchedSendToEthereumsResponse = {
encode(
message: BatchedSendToEthereumsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.sendToEthereums) {
SendToEthereum.encode(v!, writer.uint32(10).fork()).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): BatchedSendToEthereumsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseBatchedSendToEthereumsResponse,
} as BatchedSendToEthereumsResponse;
message.sendToEthereums = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.sendToEthereums.push(
SendToEthereum.decode(reader, reader.uint32())
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): BatchedSendToEthereumsResponse {
const message = {
...baseBatchedSendToEthereumsResponse,
} as BatchedSendToEthereumsResponse;
message.sendToEthereums = [];
if (
object.sendToEthereums !== undefined &&
object.sendToEthereums !== null
) {
for (const e of object.sendToEthereums) {
message.sendToEthereums.push(SendToEthereum.fromJSON(e));
}
}
return message;
},
toJSON(message: BatchedSendToEthereumsResponse): unknown {
const obj: any = {};
if (message.sendToEthereums) {
obj.sendToEthereums = message.sendToEthereums.map((e) =>
e ? SendToEthereum.toJSON(e) : undefined
);
} else {
obj.sendToEthereums = [];
}
return obj;
},
fromPartial(
object: DeepPartial<BatchedSendToEthereumsResponse>
): BatchedSendToEthereumsResponse {
const message = {
...baseBatchedSendToEthereumsResponse,
} as BatchedSendToEthereumsResponse;
message.sendToEthereums = [];
if (
object.sendToEthereums !== undefined &&
object.sendToEthereums !== null
) {
for (const e of object.sendToEthereums) {
message.sendToEthereums.push(SendToEthereum.fromPartial(e));
}
}
return message;
},
};
const baseUnbatchedSendToEthereumsRequest: object = { senderAddress: "" };
export const UnbatchedSendToEthereumsRequest = {
encode(
message: UnbatchedSendToEthereumsRequest,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
if (message.senderAddress !== "") {
writer.uint32(10).string(message.senderAddress);
}
if (message.pagination !== undefined) {
PageRequest.encode(message.pagination, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): UnbatchedSendToEthereumsRequest {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUnbatchedSendToEthereumsRequest,
} as UnbatchedSendToEthereumsRequest;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.senderAddress = reader.string();
break;
case 2:
message.pagination = PageRequest.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): UnbatchedSendToEthereumsRequest {
const message = {
...baseUnbatchedSendToEthereumsRequest,
} as UnbatchedSendToEthereumsRequest;
if (object.senderAddress !== undefined && object.senderAddress !== null) {
message.senderAddress = String(object.senderAddress);
} else {
message.senderAddress = "";
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageRequest.fromJSON(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
toJSON(message: UnbatchedSendToEthereumsRequest): unknown {
const obj: any = {};
message.senderAddress !== undefined &&
(obj.senderAddress = message.senderAddress);
message.pagination !== undefined &&
(obj.pagination = message.pagination
? PageRequest.toJSON(message.pagination)
: undefined);
return obj;
},
fromPartial(
object: DeepPartial<UnbatchedSendToEthereumsRequest>
): UnbatchedSendToEthereumsRequest {
const message = {
...baseUnbatchedSendToEthereumsRequest,
} as UnbatchedSendToEthereumsRequest;
if (object.senderAddress !== undefined && object.senderAddress !== null) {
message.senderAddress = object.senderAddress;
} else {
message.senderAddress = "";
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageRequest.fromPartial(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
};
const baseUnbatchedSendToEthereumsResponse: object = {};
export const UnbatchedSendToEthereumsResponse = {
encode(
message: UnbatchedSendToEthereumsResponse,
writer: _m0.Writer = _m0.Writer.create()
): _m0.Writer {
for (const v of message.sendToEthereums) {
SendToEthereum.encode(v!, writer.uint32(10).fork()).ldelim();
}
if (message.pagination !== undefined) {
PageResponse.encode(
message.pagination,
writer.uint32(18).fork()
).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number
): UnbatchedSendToEthereumsResponse {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseUnbatchedSendToEthereumsResponse,
} as UnbatchedSendToEthereumsResponse;
message.sendToEthereums = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.sendToEthereums.push(
SendToEthereum.decode(reader, reader.uint32())
);
break;
case 2:
message.pagination = PageResponse.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): UnbatchedSendToEthereumsResponse {
const message = {
...baseUnbatchedSendToEthereumsResponse,
} as UnbatchedSendToEthereumsResponse;
message.sendToEthereums = [];
if (
object.sendToEthereums !== undefined &&
object.sendToEthereums !== null
) {
for (const e of object.sendToEthereums) {
message.sendToEthereums.push(SendToEthereum.fromJSON(e));
}
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageResponse.fromJSON(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
toJSON(message: UnbatchedSendToEthereumsResponse): unknown {
const obj: any = {};
if (message.sendToEthereums) {
obj.sendToEthereums = message.sendToEthereums.map((e) =>
e ? SendToEthereum.toJSON(e) : undefined
);
} else {
obj.sendToEthereums = [];
}
message.pagination !== undefined &&
(obj.pagination = message.pagination
? PageResponse.toJSON(message.pagination)
: undefined);
return obj;
},
fromPartial(
object: DeepPartial<UnbatchedSendToEthereumsResponse>
): UnbatchedSendToEthereumsResponse {
const message = {
...baseUnbatchedSendToEthereumsResponse,
} as UnbatchedSendToEthereumsResponse;
message.sendToEthereums = [];
if (
object.sendToEthereums !== undefined &&
object.sendToEthereums !== null
) {
for (const e of object.sendToEthereums) {
message.sendToEthereums.push(SendToEthereum.fromPartial(e));
}
}
if (object.pagination !== undefined && object.pagination !== null) {
message.pagination = PageResponse.fromPartial(object.pagination);
} else {
message.pagination = undefined;
}
return message;
},
};
/** Query defines the gRPC querier service */
export interface Query {
/** Module parameters query */
Params(request: ParamsRequest): Promise<ParamsResponse>;
/** get info on individual outgoing data */
SignerSetTx(request: SignerSetTxRequest): Promise<SignerSetTxResponse>;
LatestSignerSetTx(
request: LatestSignerSetTxRequest
): Promise<SignerSetTxResponse>;
BatchTx(request: BatchTxRequest): Promise<BatchTxResponse>;
ContractCallTx(
request: ContractCallTxRequest
): Promise<ContractCallTxResponse>;
/** get collections of outgoing traffic from the bridge */
SignerSetTxs(request: SignerSetTxsRequest): Promise<SignerSetTxsResponse>;
BatchTxs(request: BatchTxsRequest): Promise<BatchTxsResponse>;
ContractCallTxs(
request: ContractCallTxsRequest
): Promise<ContractCallTxsResponse>;
/** TODO: can/should we group these into one endpoint? */
SignerSetTxConfirmations(
request: SignerSetTxConfirmationsRequest
): Promise<SignerSetTxConfirmationsResponse>;
BatchTxConfirmations(
request: BatchTxConfirmationsRequest
): Promise<BatchTxConfirmationsResponse>;
ContractCallTxConfirmations(
request: ContractCallTxConfirmationsRequest
): Promise<ContractCallTxConfirmationsResponse>;
/**
* pending ethereum signature queries for orchestrators to figure out which
* signatures they are missing
* TODO: can/should we group this into one endpoint?
*/
UnsignedSignerSetTxs(
request: UnsignedSignerSetTxsRequest
): Promise<UnsignedSignerSetTxsResponse>;
UnsignedBatchTxs(
request: UnsignedBatchTxsRequest
): Promise<UnsignedBatchTxsResponse>;
UnsignedContractCallTxs(
request: UnsignedContractCallTxsRequest
): Promise<UnsignedContractCallTxsResponse>;
LastSubmittedEthereumEvent(
request: LastSubmittedEthereumEventRequest
): Promise<LastSubmittedEthereumEventResponse>;
/**
* Queries the fees for all pending batches, results are returned in sdk.Coin
* (fee_amount_int)(contract_address) style
*/
BatchTxFees(request: BatchTxFeesRequest): Promise<BatchTxFeesResponse>;
/** Query for info about denoms tracked by gravity */
ERC20ToDenom(request: ERC20ToDenomRequest): Promise<ERC20ToDenomResponse>;
/** Query for info about denoms tracked by gravity */
DenomToERC20(request: DenomToERC20Request): Promise<DenomToERC20Response>;
/** Query for batch send to ethereums */
BatchedSendToEthereums(
request: BatchedSendToEthereumsRequest
): Promise<BatchedSendToEthereumsResponse>;
/** Query for unbatched send to ethereums */
UnbatchedSendToEthereums(
request: UnbatchedSendToEthereumsRequest
): Promise<UnbatchedSendToEthereumsResponse>;
/** delegate keys */
DelegateKeysByValidator(
request: DelegateKeysByValidatorRequest
): Promise<DelegateKeysByValidatorResponse>;
DelegateKeysByEthereumSigner(
request: DelegateKeysByEthereumSignerRequest
): Promise<DelegateKeysByEthereumSignerResponse>;
DelegateKeysByOrchestrator(
request: DelegateKeysByOrchestratorRequest
): Promise<DelegateKeysByOrchestratorResponse>;
}
export class QueryClientImpl implements Query {
private readonly rpc: Rpc;
constructor(rpc: Rpc) {
this.rpc = rpc;
this.Params = this.Params.bind(this);
this.SignerSetTx = this.SignerSetTx.bind(this);
this.LatestSignerSetTx = this.LatestSignerSetTx.bind(this);
this.BatchTx = this.BatchTx.bind(this);
this.ContractCallTx = this.ContractCallTx.bind(this);
this.SignerSetTxs = this.SignerSetTxs.bind(this);
this.BatchTxs = this.BatchTxs.bind(this);
this.ContractCallTxs = this.ContractCallTxs.bind(this);
this.SignerSetTxConfirmations = this.SignerSetTxConfirmations.bind(this);
this.BatchTxConfirmations = this.BatchTxConfirmations.bind(this);
this.ContractCallTxConfirmations = this.ContractCallTxConfirmations.bind(
this
);
this.UnsignedSignerSetTxs = this.UnsignedSignerSetTxs.bind(this);
this.UnsignedBatchTxs = this.UnsignedBatchTxs.bind(this);
this.UnsignedContractCallTxs = this.UnsignedContractCallTxs.bind(this);
this.LastSubmittedEthereumEvent = this.LastSubmittedEthereumEvent.bind(
this
);
this.BatchTxFees = this.BatchTxFees.bind(this);
this.ERC20ToDenom = this.ERC20ToDenom.bind(this);
this.DenomToERC20 = this.DenomToERC20.bind(this);
this.BatchedSendToEthereums = this.BatchedSendToEthereums.bind(this);
this.UnbatchedSendToEthereums = this.UnbatchedSendToEthereums.bind(this);
this.DelegateKeysByValidator = this.DelegateKeysByValidator.bind(this);
this.DelegateKeysByEthereumSigner = this.DelegateKeysByEthereumSigner.bind(
this
);
this.DelegateKeysByOrchestrator = this.DelegateKeysByOrchestrator.bind(
this
);
}
Params(request: ParamsRequest): Promise<ParamsResponse> {
const data = ParamsRequest.encode(request).finish();
const promise = this.rpc.request("gravity.v1.Query", "Params", data);
return promise.then((data) => ParamsResponse.decode(new _m0.Reader(data)));
}
SignerSetTx(request: SignerSetTxRequest): Promise<SignerSetTxResponse> {
const data = SignerSetTxRequest.encode(request).finish();
const promise = this.rpc.request("gravity.v1.Query", "SignerSetTx", data);
return promise.then((data) =>
SignerSetTxResponse.decode(new _m0.Reader(data))
);
}
LatestSignerSetTx(
request: LatestSignerSetTxRequest
): Promise<SignerSetTxResponse> {
const data = LatestSignerSetTxRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"LatestSignerSetTx",
data
);
return promise.then((data) =>
SignerSetTxResponse.decode(new _m0.Reader(data))
);
}
BatchTx(request: BatchTxRequest): Promise<BatchTxResponse> {
const data = BatchTxRequest.encode(request).finish();
const promise = this.rpc.request("gravity.v1.Query", "BatchTx", data);
return promise.then((data) => BatchTxResponse.decode(new _m0.Reader(data)));
}
ContractCallTx(
request: ContractCallTxRequest
): Promise<ContractCallTxResponse> {
const data = ContractCallTxRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"ContractCallTx",
data
);
return promise.then((data) =>
ContractCallTxResponse.decode(new _m0.Reader(data))
);
}
SignerSetTxs(request: SignerSetTxsRequest): Promise<SignerSetTxsResponse> {
const data = SignerSetTxsRequest.encode(request).finish();
const promise = this.rpc.request("gravity.v1.Query", "SignerSetTxs", data);
return promise.then((data) =>
SignerSetTxsResponse.decode(new _m0.Reader(data))
);
}
BatchTxs(request: BatchTxsRequest): Promise<BatchTxsResponse> {
const data = BatchTxsRequest.encode(request).finish();
const promise = this.rpc.request("gravity.v1.Query", "BatchTxs", data);
return promise.then((data) =>
BatchTxsResponse.decode(new _m0.Reader(data))
);
}
ContractCallTxs(
request: ContractCallTxsRequest
): Promise<ContractCallTxsResponse> {
const data = ContractCallTxsRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"ContractCallTxs",
data
);
return promise.then((data) =>
ContractCallTxsResponse.decode(new _m0.Reader(data))
);
}
SignerSetTxConfirmations(
request: SignerSetTxConfirmationsRequest
): Promise<SignerSetTxConfirmationsResponse> {
const data = SignerSetTxConfirmationsRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"SignerSetTxConfirmations",
data
);
return promise.then((data) =>
SignerSetTxConfirmationsResponse.decode(new _m0.Reader(data))
);
}
BatchTxConfirmations(
request: BatchTxConfirmationsRequest
): Promise<BatchTxConfirmationsResponse> {
const data = BatchTxConfirmationsRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"BatchTxConfirmations",
data
);
return promise.then((data) =>
BatchTxConfirmationsResponse.decode(new _m0.Reader(data))
);
}
ContractCallTxConfirmations(
request: ContractCallTxConfirmationsRequest
): Promise<ContractCallTxConfirmationsResponse> {
const data = ContractCallTxConfirmationsRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"ContractCallTxConfirmations",
data
);
return promise.then((data) =>
ContractCallTxConfirmationsResponse.decode(new _m0.Reader(data))
);
}
UnsignedSignerSetTxs(
request: UnsignedSignerSetTxsRequest
): Promise<UnsignedSignerSetTxsResponse> {
const data = UnsignedSignerSetTxsRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"UnsignedSignerSetTxs",
data
);
return promise.then((data) =>
UnsignedSignerSetTxsResponse.decode(new _m0.Reader(data))
);
}
UnsignedBatchTxs(
request: UnsignedBatchTxsRequest
): Promise<UnsignedBatchTxsResponse> {
const data = UnsignedBatchTxsRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"UnsignedBatchTxs",
data
);
return promise.then((data) =>
UnsignedBatchTxsResponse.decode(new _m0.Reader(data))
);
}
UnsignedContractCallTxs(
request: UnsignedContractCallTxsRequest
): Promise<UnsignedContractCallTxsResponse> {
const data = UnsignedContractCallTxsRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"UnsignedContractCallTxs",
data
);
return promise.then((data) =>
UnsignedContractCallTxsResponse.decode(new _m0.Reader(data))
);
}
LastSubmittedEthereumEvent(
request: LastSubmittedEthereumEventRequest
): Promise<LastSubmittedEthereumEventResponse> {
const data = LastSubmittedEthereumEventRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"LastSubmittedEthereumEvent",
data
);
return promise.then((data) =>
LastSubmittedEthereumEventResponse.decode(new _m0.Reader(data))
);
}
BatchTxFees(request: BatchTxFeesRequest): Promise<BatchTxFeesResponse> {
const data = BatchTxFeesRequest.encode(request).finish();
const promise = this.rpc.request("gravity.v1.Query", "BatchTxFees", data);
return promise.then((data) =>
BatchTxFeesResponse.decode(new _m0.Reader(data))
);
}
ERC20ToDenom(request: ERC20ToDenomRequest): Promise<ERC20ToDenomResponse> {
const data = ERC20ToDenomRequest.encode(request).finish();
const promise = this.rpc.request("gravity.v1.Query", "ERC20ToDenom", data);
return promise.then((data) =>
ERC20ToDenomResponse.decode(new _m0.Reader(data))
);
}
DenomToERC20(request: DenomToERC20Request): Promise<DenomToERC20Response> {
const data = DenomToERC20Request.encode(request).finish();
const promise = this.rpc.request("gravity.v1.Query", "DenomToERC20", data);
return promise.then((data) =>
DenomToERC20Response.decode(new _m0.Reader(data))
);
}
BatchedSendToEthereums(
request: BatchedSendToEthereumsRequest
): Promise<BatchedSendToEthereumsResponse> {
const data = BatchedSendToEthereumsRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"BatchedSendToEthereums",
data
);
return promise.then((data) =>
BatchedSendToEthereumsResponse.decode(new _m0.Reader(data))
);
}
UnbatchedSendToEthereums(
request: UnbatchedSendToEthereumsRequest
): Promise<UnbatchedSendToEthereumsResponse> {
const data = UnbatchedSendToEthereumsRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"UnbatchedSendToEthereums",
data
);
return promise.then((data) =>
UnbatchedSendToEthereumsResponse.decode(new _m0.Reader(data))
);
}
DelegateKeysByValidator(
request: DelegateKeysByValidatorRequest
): Promise<DelegateKeysByValidatorResponse> {
const data = DelegateKeysByValidatorRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"DelegateKeysByValidator",
data
);
return promise.then((data) =>
DelegateKeysByValidatorResponse.decode(new _m0.Reader(data))
);
}
DelegateKeysByEthereumSigner(
request: DelegateKeysByEthereumSignerRequest
): Promise<DelegateKeysByEthereumSignerResponse> {
const data = DelegateKeysByEthereumSignerRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"DelegateKeysByEthereumSigner",
data
);
return promise.then((data) =>
DelegateKeysByEthereumSignerResponse.decode(new _m0.Reader(data))
);
}
DelegateKeysByOrchestrator(
request: DelegateKeysByOrchestratorRequest
): Promise<DelegateKeysByOrchestratorResponse> {
const data = DelegateKeysByOrchestratorRequest.encode(request).finish();
const promise = this.rpc.request(
"gravity.v1.Query",
"DelegateKeysByOrchestrator",
data
);
return promise.then((data) =>
DelegateKeysByOrchestratorResponse.decode(new _m0.Reader(data))
);
}
}
interface Rpc {
request(
service: string,
method: string,
data: Uint8Array
): Promise<Uint8Array>;
}
declare var self: any | undefined;
declare var window: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
const atob: (b64: string) => string =
globalThis.atob ||
((b64) => globalThis.Buffer.from(b64, "base64").toString("binary"));
function bytesFromBase64(b64: string): Uint8Array {
const bin = atob(b64);
const arr = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; ++i) {
arr[i] = bin.charCodeAt(i);
}
return arr;
}
const btoa: (bin: string) => string =
globalThis.btoa ||
((bin) => globalThis.Buffer.from(bin, "binary").toString("base64"));
function base64FromBytes(arr: Uint8Array): string {
const bin: string[] = [];
for (let i = 0; i < arr.byteLength; ++i) {
bin.push(String.fromCharCode(arr[i]));
}
return btoa(bin.join(""));
}
type Builtin =
| Date
| Function
| Uint8Array
| string
| number
| boolean
| undefined
| Long;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
if (_m0.util.Long !== Long) {
_m0.util.Long = Long as any;
_m0.configure();
} | the_stack |
// The MIT License (MIT)
//
// vs-deploy (https://github.com/mkloubert/vs-deploy)
// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
import * as deploy_compilers from './compilers';
import * as deploy_contracts from './contracts';
import * as deploy_helpers from './helpers';
import * as deploy_sql from './sql';
import * as deploy_workspace from './workspace';
import * as HTTP from 'http';
import * as HTTPs from 'https';
import * as i18 from './i18';
import * as Path from 'path';
import * as Url from 'url';
import * as vs_deploy from './deploy';
import * as vscode from 'vscode';
/**
* A module for getting the request body for a HTTP operation.
*/
export interface HttpBodyModule {
/**
* Gets the request body data.
*/
getBody: HttpBodyModuleExecutor;
}
/**
* The function / method that gets the request body data.
*
* @param {HttpBodyModuleExecutorArguments} args The arguments for the execution.
*
* @return {any} The data to send.
*/
export type HttpBodyModuleExecutor = (args: HttpBodyModuleExecutorArguments) => any;
/**
* Arguments for the function / method that gets the request body data.
*/
export interface HttpBodyModuleExecutorArguments {
/**
* The underlying operation context.
*/
readonly context: OperationContext<deploy_contracts.DeployHttpOperation>;
/**
* The global data from the settings.
*/
readonly globals?: any;
/**
* The options for the execution of the underlying script.
*/
readonly options?: any;
/**
* Handles a value as string and replaces placeholders.
*
* @param {any} val The value to parse.
*
* @return {string} The parsed value.
*/
readonly replaceWithValues: (val: any) => string;
/**
* Gets or sets a value that will be available
* for the underlying script while the current session.
*/
state: any;
/**
* The request URL.
*/
readonly url: Url.Url;
}
let httpOperationStates: { [script: string]: any };
/**
* An operation context.
*/
export interface OperationContext<T extends deploy_contracts.DeployOperation> {
/**
* The app configuration.
*/
readonly config: deploy_contracts.DeployConfiguration;
/**
* Can store the error that is raised while the execution.
*/
error?: any;
/**
* The files to deploy / the deployed files.
*/
readonly files: string[];
/**
* The global data from the settings.
*/
readonly globals: Object;
/**
* Operation has been handled or not.
*/
handled?: boolean;
/**
* Kind of operation.
*/
readonly kind: deploy_contracts.DeployOperationKind;
/**
* The operation settings.
*/
readonly operation: T;
/**
* The output channel.
*/
readonly outputChannel: vscode.OutputChannel;
}
/**
* Describes something that executes on operation.
*
* @param {OperationContext<T>} ctx The execution context.
*
* @returns {Promise<boolean>|boolean|void} The result.
*/
export type OperationExecutor<T extends deploy_contracts.DeployOperation> = (ctx: OperationContext<T>) => Promise<boolean> | void | boolean;
/**
* Compiles files.
*
* @param {OperationContext<T>} ctx The execution context.
*
* @returns {Promise<boolean>} The promise.
*/
export function compile(ctx: OperationContext<deploy_contracts.DeployCompileOperation>): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
let completed = (err?: any) => {
if (err) {
reject(err);
}
else {
resolve();
}
};
try {
let compileOp = deploy_helpers.cloneObject(ctx.operation);
let updateFilesProperty = (property = "files") => {
if (!deploy_helpers.toBooleanSafe(compileOp.useFilesOfDeployment)) {
return; // do not use files of deployment
}
if (deploy_helpers.isNullOrUndefined(compileOp.options)) {
compileOp.options = {}; // initialize
}
if (deploy_helpers.isNullOrUndefined(compileOp.options[property])) {
// only if not explicit defined
compileOp.options[property] = ctx.files.map(x => x); // create copy
}
};
let compilerName = deploy_helpers.normalizeString(compileOp.compiler);
let compiler: deploy_compilers.Compiler;
let compilerArgs: any[];
switch (compilerName) {
case 'coffeescript':
updateFilesProperty();
compiler = deploy_compilers.Compiler.CoffeeScript;
compilerArgs = [ compileOp.options ];
break;
case 'htmlminifier':
updateFilesProperty();
compiler = deploy_compilers.Compiler.HtmlMinifier;
compilerArgs = [ compileOp.options ];
break;
case 'less':
updateFilesProperty();
compiler = deploy_compilers.Compiler.Less;
compilerArgs = [ compileOp.options ];
break;
case 'pug':
updateFilesProperty();
compiler = deploy_compilers.Compiler.Pug;
compilerArgs = [ compileOp.options ];
break;
case 'script':
updateFilesProperty();
compiler = deploy_compilers.Compiler.Script;
compilerArgs = [ ctx.config, compileOp.options ];
break;
case 'typescript':
updateFilesProperty();
compiler = deploy_compilers.Compiler.TypeScript;
compilerArgs = [ compileOp.options ];
break;
case 'uglifyjs':
updateFilesProperty();
compiler = deploy_compilers.Compiler.UglifyJS;
compilerArgs = [ compileOp.options ];
break;
}
if (deploy_helpers.isNullOrUndefined(compiler)) {
// unknown compiler
completed(new Error(i18.t('deploy.operations.unknownCompiler', compilerName)));
}
else {
deploy_compilers.compile(compiler, compilerArgs).then((result) => {
let sourceFiles: string[] = [];
if (result.files) {
sourceFiles = result.files
.filter(x => !deploy_helpers.isEmptyString(x))
.map(x => Path.resolve(x));
}
sourceFiles = deploy_helpers.distinctArray(sourceFiles);
let compilerErrors: deploy_compilers.CompilerError[] = [];
if (result.errors) {
compilerErrors = result.errors
.filter(x => x);
}
let err: Error;
if (compilerErrors.length > 0) {
ctx.outputChannel.appendLine('');
result.errors.forEach(x => {
ctx.outputChannel.appendLine(`[${x.file}] ${x.error}`);
});
let failedFiles = compilerErrors.map(x => x.file)
.filter(x => !deploy_helpers.isEmptyString(x))
.map(x => Path.resolve(x));
failedFiles = deploy_helpers.distinctArray(failedFiles);
if (failedFiles.length > 0) {
let errMsg: string;
if (failedFiles.length >= sourceFiles.length) {
// all failed
errMsg = i18.t("deploy.operations.noFileCompiled",
sourceFiles.length);
}
else {
// some failed
errMsg = i18.t("deploy.operations.someFilesNotCompiled",
failedFiles.length, sourceFiles.length);
}
err = new Error(errMsg);
}
}
completed(err);
}).catch((err) => {
completed(err);
});
}
}
catch (e) {
completed(e);
}
});
}
/**
* Returns the (display) name of an operation.
*
* @param {deploy_contracts.DeployOperation} operation The operation.
*
* @return {string} The (display) name.
*/
export function getOperationName(operation: deploy_contracts.DeployOperation): string {
let operationName: string;
if (operation) {
operationName = deploy_helpers.toStringSafe(operation.name).trim();
if (!operationName) {
operationName = deploy_helpers.normalizeString(operation.type);
if (!operationName) {
operationName = 'open';
}
}
}
return operationName;
}
/**
* Does a HTTP request.
*
* @param {OperationContext<deploy_contracts.DeployHttpOperation>} ctx The execution context.
*
* @returns {Promise<boolean>} The promise.
*/
export function http(ctx: OperationContext<deploy_contracts.DeployHttpOperation>): Promise<boolean> {
let me: vs_deploy.Deployer = this;
return new Promise<boolean>((resolve, reject) => {
let completed = deploy_helpers.createSimplePromiseCompletedAction<boolean>(resolve, reject);
try {
let operation = ctx.operation;
let u = deploy_helpers.toStringSafe(operation.url);
if (deploy_helpers.isEmptyString(u)) {
u = 'http://localhost/';
}
let url = Url.parse(u);
let host = deploy_helpers.normalizeString(url.hostname);
if ('' === host) {
host = 'localhost';
}
let method = deploy_helpers.normalizeString(operation.method, x => x.toUpperCase().trim());
if ('' === method) {
method = 'GET';
}
let headers = deploy_helpers.cloneObject(operation.headers);
if (!deploy_helpers.isEmptyString(operation.username)) {
// Basic Auth
let username = deploy_helpers.toStringSafe(operation.username);
let password = deploy_helpers.toStringSafe(operation.password);
headers = headers || {};
headers['Authorization'] = 'Basic ' + (new Buffer(username + ':' + password, 'ascii').toString('base64'));
}
if (headers) {
for (let prop in headers) {
let name = deploy_helpers.normalizeString(prop);
let value = headers[prop];
let usePlaceholders: boolean;
if ('boolean' === typeof operation.noPlaceholdersForTheseHeaders) {
usePlaceholders = !operation.noPlaceholdersForTheseHeaders;
}
else {
usePlaceholders = deploy_helpers.asArray(operation.noPlaceholdersForTheseHeaders)
.map(x => deploy_helpers.normalizeString(prop))
.indexOf(name) < 0;
}
if (usePlaceholders) {
value = me.replaceWithValues(value);
}
headers[prop] = value;
}
}
let port = deploy_helpers.toStringSafe(url.port);
let opts: HTTP.RequestOptions = {
host: host,
headers: headers,
method: method,
path: url.path,
protocol: url.protocol,
};
let callback = (resp: HTTP.IncomingMessage) => {
if (resp.statusCode > 399 && resp.statusCode < 500) {
completed(new Error(`Client error: [${resp.statusCode}] '${resp.statusMessage}'`));
return;
}
if (resp.statusCode > 499 && resp.statusCode < 600) {
completed(new Error(`Server error: [${resp.statusCode}] '${resp.statusMessage}'`));
return;
}
if (resp.statusCode > 599) {
completed(new Error(`Error: [${resp.statusCode}] '${resp.statusMessage}'`));
return;
}
if (!(resp.statusCode > 199 && resp.statusCode < 300)) {
completed(new Error(`No success: [${resp.statusCode}] '${resp.statusMessage}'`));
return;
}
completed();
};
let httpModule: any;
let req: HTTP.ClientRequest;
switch (deploy_helpers.normalizeString(url.protocol)) {
case 'https:':
httpModule = HTTPs;
if ('' === port) {
port = '443';
}
break;
default:
httpModule = HTTP;
if ('' === port) {
port = '80';
}
break;
}
opts.port = parseInt(port);
req = httpModule.request(opts, callback);
let startRequest = () => {
try {
req.end();
}
catch (e) {
completed(e);
}
};
if (deploy_helpers.isNullOrUndefined(operation.body)) {
startRequest();
}
else {
// send request body
let body = deploy_helpers.toStringSafe(operation.body);
if (deploy_helpers.toBooleanSafe(operation.isBodyBase64)) {
body = (new Buffer(body, 'base64')).toString('ascii'); // is Base64
}
if (deploy_helpers.toBooleanSafe(operation.isBodyScript)) {
// 'body' is path to a script
let bodyScript = body;
bodyScript = me.replaceWithValues(bodyScript);
if (deploy_helpers.isEmptyString(bodyScript)) {
bodyScript = './getBody.js';
}
if (!Path.isAbsolute(bodyScript)) {
bodyScript = Path.join(deploy_workspace.getRootPath(), bodyScript);
}
bodyScript = Path.resolve(bodyScript);
let bodyModule = deploy_helpers.loadModule<HttpBodyModule>(bodyScript);
if (bodyModule) {
if (bodyModule.getBody) {
let args: HttpBodyModuleExecutorArguments = {
context: ctx,
globals: me.getGlobals(),
replaceWithValues: (val) => {
return me.replaceWithValues(val);
},
state: undefined,
url: url,
};
// args.state
Object.defineProperty(args, 'state', {
get: () => { return httpOperationStates[bodyScript]; },
set: (newValue) => {
httpOperationStates[bodyScript] = newValue;
},
});
Promise.resolve( bodyModule.getBody(args) ).then((r) => {
try {
let bodyData: Buffer = r;
if (deploy_helpers.isNullOrUndefined(bodyData)) {
bodyData = Buffer.alloc(0);
}
if (!Buffer.isBuffer(bodyData)) {
// handle as string
bodyData = new Buffer(deploy_helpers.toStringSafe(bodyData), 'ascii');
}
if (bodyData.length > 0) {
req.write(bodyData);
}
startRequest();
}
catch (e) {
completed(e);
}
}).catch((err) => {
completed(err);
});
}
else {
startRequest();
}
}
else {
startRequest();
}
}
else {
startRequest();
}
}
}
catch (e) {
completed(e);
}
});
}
/**
* Opens something.
*
* @param {OperationContext<deploy_contracts.DeployOpenOperation>} ctx The execution context.
*
* @returns {Promise<boolean>} The promise.
*/
export function open(ctx: OperationContext<deploy_contracts.DeployOpenOperation>): Promise<boolean> {
let me: vs_deploy.Deployer = this;
const GET_FINAL_ARGS = (argList: string[]) => {
if (deploy_helpers.toBooleanSafe(ctx.operation.usePlaceholdersInArguments)) {
argList = argList.map(a => {
return me.replaceWithValues(a);
});
}
return argList;
};
return new Promise<boolean>((resolve, reject) => {
let completed = deploy_helpers.createSimplePromiseCompletedAction<boolean>(resolve, reject);
try {
let openOperation = ctx.operation;
let operationTarget = deploy_helpers.toStringSafe(openOperation.target);
let waitForExit = deploy_helpers.toBooleanSafe(openOperation.wait, true);
if (deploy_helpers.toBooleanSafe(openOperation.runInTerminal)) {
// run in terminal
let args = deploy_helpers.asArray(openOperation.arguments)
.map(x => deploy_helpers.toStringSafe(x))
.filter(x => '' !== x);
let terminalName = '[vs-deploy]';
if (!deploy_helpers.isEmptyString(openOperation.name)) {
terminalName += ' ' + deploy_helpers.toStringSafe(openOperation.name).trim();
}
let app = deploy_helpers.toStringSafe(openOperation.target);
app = me.replaceWithValues(app);
if (!Path.isAbsolute(app)) {
app = Path.join(deploy_workspace.getRootPath(), app);
}
app = Path.resolve(app);
let terminal = vscode.window.createTerminal(terminalName,
app, GET_FINAL_ARGS(args));
terminal.show();
}
else {
let openArgs = [];
if (openOperation.arguments) {
openArgs = openArgs.concat(deploy_helpers.asArray(openOperation.arguments));
}
openArgs = openArgs.map(x => deploy_helpers.toStringSafe(x))
.filter(x => '' !== x);
if (openArgs.length > 0) {
let app = operationTarget;
app = me.replaceWithValues(app);
operationTarget = GET_FINAL_ARGS([ openArgs.pop() ])[0];
openArgs = [ app ].concat( GET_FINAL_ARGS(openArgs) );
}
ctx.outputChannel.append(i18.t('deploy.operations.open', operationTarget));
deploy_helpers.open(operationTarget, {
app: openArgs,
env: deploy_helpers.makeEnvVarsForProcess(openOperation, me.getValues()),
wait: waitForExit,
}).then(function() {
ctx.outputChannel.appendLine(i18.t('ok'));
completed();
}).catch((err) => {
completed(err);
});
}
}
catch (e) {
completed(e);
}
});
}
/**
* Resets all operations and their state values.
*/
export function resetOperations() {
httpOperationStates = {};
}
/**
* Executes SQL statements.
*
* @param {OperationContext<deploy_contracts.DeploySqlOperation>} ctx The execution context.
*
* @returns {Promise<boolean>} The promise.
*/
export function sql(ctx: OperationContext<deploy_contracts.DeploySqlOperation>): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
let completed = deploy_helpers.createSimplePromiseCompletedAction<boolean>(resolve, reject);
try {
//TODO: password prompt
let sqlOp = ctx.operation;
let type: deploy_sql.SqlConnectionType;
let args: any[];
let engineName = deploy_helpers.normalizeString(sqlOp.engine);
switch (engineName) {
case '':
case 'mysql':
// MySQL
type = deploy_sql.SqlConnectionType.MySql;
args = [
sqlOp.options,
];
break;
case 'sql':
// Microsoft SQL
type = deploy_sql.SqlConnectionType.MSSql;
args = [
sqlOp.options,
];
break;
}
if (deploy_helpers.isNullOrUndefined(type)) {
// unknown SQL engine
completed(new Error(i18.t('deploy.operations.unknownSqlEngine',
engineName)));
}
else {
let queries = deploy_helpers.asArray(sqlOp.queries)
.filter(x => x);
deploy_sql.createSqlConnection(type, args).then((conn) => {
let queriesCompleted = (err?: any) => {
conn.close().then(() => {
completed(err);
}).then((err2) => {
//TODO: log
completed(err);
});
};
let invokeNextQuery: () => void;
invokeNextQuery = () => {
if (queries.length < 1) {
queriesCompleted();
return;
}
let q = queries.shift();
conn.query(q).then(() => {
invokeNextQuery();
}).catch((err) => {
queriesCompleted(err);
});
};
invokeNextQuery();
}).catch((err) => {
completed(err);
});
}
}
catch (e) {
completed(e);
}
});
}
/**
* Executes Visual Studio Code commands.
*
* @param {OperationContext<deploy_contracts.DeployVSCommandOperation>} ctx The execution context.
*
* @returns {Promise<boolean>} The promise.
*/
export function vscommand(ctx: OperationContext<deploy_contracts.DeployVSCommandOperation>): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
let completed = deploy_helpers.createSimplePromiseCompletedAction<boolean>(resolve, reject);
try {
let vsCmdOp = ctx.operation;
let commandId = deploy_helpers.toStringSafe(vsCmdOp.command).trim();
if (!deploy_helpers.isEmptyString(commandId)) {
let args = vsCmdOp.arguments;
if (!args) {
args = [];
}
if (deploy_helpers.toBooleanSafe(vsCmdOp.submitContext)) {
// submit DeployVSCommandOperationContext object
// as first argument
let cmdCtx: deploy_contracts.DeployVSCommandOperationContext = {
command: commandId,
globals: ctx.globals,
files: ctx.files,
kind: ctx.kind,
operation: vsCmdOp,
options: vsCmdOp.contextOptions,
require: (id) => {
return require(id);
}
};
args = [ cmdCtx ].concat(args);
}
args = [ commandId ].concat(args);
vscode.commands.executeCommand.apply(null, args).then(() => {
completed();
}, (err) => {
completed(err);
});
}
}
catch (e) {
completed(e);
}
});
}
/**
* Waits.
*
* @param {OperationContext<deploy_contracts.DeployWaitOperation>} ctx The execution context.
*
* @returns {Promise<boolean>} The promise.
*/
export function wait(ctx: OperationContext<deploy_contracts.DeployWaitOperation>): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
let completed = deploy_helpers.createSimplePromiseCompletedAction<boolean>(resolve, reject);
try {
let waitTime = parseFloat(deploy_helpers.toStringSafe(ctx.operation.time).trim());
if (isNaN(waitTime)) {
waitTime = 1000;
}
setTimeout(() => {
completed();
}, waitTime);
}
catch (e) {
completed(e);
}
});
}
/**
* Runs Microsoft's WebDeploy.
*
* @param {OperationContext<deploy_contracts.DeployWebDeployOperation>} ctx The execution context.
*
* @returns {Promise<boolean>} The promise.
*/
export function webdeploy(ctx: OperationContext<deploy_contracts.DeployWebDeployOperation>): Promise<boolean> {
let me: vs_deploy.Deployer = this;
return new Promise<boolean>((resolve, reject) => {
let completed = deploy_helpers.createSimplePromiseCompletedAction<boolean>(resolve, reject);
try {
let webDeployOp = ctx.operation;
let msDeploy = 'msdeploy.exe';
if (!deploy_helpers.isEmptyString(webDeployOp.exec)) {
msDeploy = deploy_helpers.toStringSafe(webDeployOp.exec);
}
let args = [
// -source
`-source:${deploy_helpers.toStringSafe(webDeployOp.source)}`,
];
// -<param>:<value>
let paramsWithValues = [
'dest', 'declareParam', 'setParam', 'setParamFile', 'declareParamFile',
'removeParam', 'disableLink', 'enableLink', 'disableRule', 'enableRule',
'replace', 'skip', 'disableSkipDirective', 'enableSkipDirective',
'preSync', 'postSync',
'retryAttempts', 'retryInterval',
'appHostConfigDir', 'webServerDir', 'xpath',
];
for (let i = 0; i < paramsWithValues.length; i++) {
let p = paramsWithValues[i];
if (!deploy_helpers.isEmptyString(webDeployOp[p])) {
args.push(`-${p}:${deploy_helpers.toStringSafe(webDeployOp[p])}`);
}
}
// -<param>
let boolParams = [
'whatif', 'disableAppStore', 'allowUntrusted',
'showSecure', 'xml', 'unicode', 'useCheckSum',
'verbose',
];
for (let i = 0; i < boolParams.length; i++) {
let p = boolParams[i];
if (deploy_helpers.toBooleanSafe(webDeployOp[p])) {
args.push(`-${p}`);
}
}
if (deploy_helpers.toBooleanSafe(webDeployOp.runInTerminal)) {
// run in terminal
let terminalName = '[vs-deploy :: WebDeploy]';
if (!deploy_helpers.isEmptyString(webDeployOp.name)) {
terminalName += ' ' + deploy_helpers.toStringSafe(webDeployOp.name).trim();
}
let app = msDeploy;
if (!Path.isAbsolute(app)) {
app = Path.join(deploy_workspace.getRootPath(), app);
}
app = Path.resolve(app);
let terminal = vscode.window.createTerminal(terminalName,
app, args);
terminal.show();
}
else {
let openOpts: deploy_helpers.OpenOptions = {
app: [ msDeploy ].concat(args)
.map(x => deploy_helpers.toStringSafe(x))
.filter(x => x),
cwd: webDeployOp.dir,
env: deploy_helpers.makeEnvVarsForProcess(webDeployOp, me.getValues()),
wait: deploy_helpers.toBooleanSafe(webDeployOp.wait, true),
};
let target = `-verb:${deploy_helpers.toStringSafe(webDeployOp.verb)}`;
deploy_helpers.open(target, openOpts).then(() => {
ctx.outputChannel.appendLine(i18.t('ok'));
completed();
}).catch((err) => {
completed(err);
});
}
}
catch (e) {
completed(e);
}
});
} | the_stack |
export const series = {
id: 'tv-and-radio/series/tv-review',
displayname: 'TV review',
description:
'<p>The best critics on the TV shows everyone is talking about</p>',
url: 'https://www.theguardian.com/tv-and-radio/series/tv-review',
trails: [
{
url: 'https://www.theguardian.com/tv-and-radio/2021/nov/19/the-wheel-of-time-review-amazon-robert-jordan',
linkText:
'The Wheel of Time review – Jeff Bezos’s Game of Thrones is destined to be forgotten',
showByline: false,
byline: 'Lucy Mangan',
image: 'https://i.guim.co.uk/img/media/5a7e6839af51133135d7d9ec31c5e877ce0b2476/0_219_5257_3154/master/5257.jpg?width=300&quality=85&auto=format&fit=max&s=6b75cd7eb3163baeda06eaa0cfdc73c9',
carouselImages: {
'300': 'https://i.guim.co.uk/img/media/5a7e6839af51133135d7d9ec31c5e877ce0b2476/0_219_5257_3154/master/5257.jpg?width=300&quality=85&auto=format&fit=max&s=6b75cd7eb3163baeda06eaa0cfdc73c9',
'460': 'https://i.guim.co.uk/img/media/5a7e6839af51133135d7d9ec31c5e877ce0b2476/0_219_5257_3154/master/5257.jpg?width=460&quality=85&auto=format&fit=max&s=0442c69d6b850969551a4e02e5d03daf',
},
isLiveBlog: false,
pillar: 'culture',
designType: 'Review',
format: {
design: 'ReviewDesign',
theme: 'CulturePillar',
display: 'StandardDisplay',
},
webPublicationDate: '2021-11-19T11:00:32.000Z',
headline:
'The Wheel of Time review – Jeff Bezos’s Game of Thrones is destined to be forgotten',
shortUrl: 'https://www.theguardian.com/p/jjven',
starRating: 3,
},
{
url: 'https://www.theguardian.com/tv-and-radio/2021/nov/19/cowboy-bebop-review-a-slick-and-spirited-slice-of-tv-cyberpunk',
linkText:
'Cowboy Bebop review – a slick and spirited slice of TV cyberpunk',
showByline: false,
byline: 'Graeme Virtue',
image: 'https://i.guim.co.uk/img/media/59aa6e52ac9c57f58fa996d637547704dbb40001/0_146_3600_2162/master/3600.jpg?width=300&quality=85&auto=format&fit=max&s=237bbf41b5502e44cacbb9168d6ca63d',
carouselImages: {
'300': 'https://i.guim.co.uk/img/media/59aa6e52ac9c57f58fa996d637547704dbb40001/0_146_3600_2162/master/3600.jpg?width=300&quality=85&auto=format&fit=max&s=237bbf41b5502e44cacbb9168d6ca63d',
'460': 'https://i.guim.co.uk/img/media/59aa6e52ac9c57f58fa996d637547704dbb40001/0_146_3600_2162/master/3600.jpg?width=460&quality=85&auto=format&fit=max&s=6f698fe41058952988b87eee23a6222a',
},
isLiveBlog: false,
pillar: 'culture',
designType: 'Review',
format: {
design: 'ReviewDesign',
theme: 'CulturePillar',
display: 'StandardDisplay',
},
webPublicationDate: '2021-11-19T09:00:31.000Z',
headline:
'Cowboy Bebop review – a slick and spirited slice of TV cyberpunk',
shortUrl: 'https://www.theguardian.com/p/jj9ck',
starRating: 4,
},
{
url: 'https://www.theguardian.com/tv-and-radio/2021/nov/18/review-irvine-welsh-tv-drama-dreich-plodding-deathly',
linkText:
'Crime review – Irvine Welsh’s first TV drama is a dreich and plodding affair',
showByline: false,
byline: 'Lucy Mangan',
image: 'https://i.guim.co.uk/img/media/bc5ea205c2d461980b1ab999a9019f55dc833bc7/0_416_6240_3744/master/6240.jpg?width=300&quality=85&auto=format&fit=max&s=c8bad126897ed36b44aef8a0ea3ebe1a',
carouselImages: {
'300': 'https://i.guim.co.uk/img/media/bc5ea205c2d461980b1ab999a9019f55dc833bc7/0_416_6240_3744/master/6240.jpg?width=300&quality=85&auto=format&fit=max&s=c8bad126897ed36b44aef8a0ea3ebe1a',
'460': 'https://i.guim.co.uk/img/media/bc5ea205c2d461980b1ab999a9019f55dc833bc7/0_416_6240_3744/master/6240.jpg?width=460&quality=85&auto=format&fit=max&s=d98c24e57ba306d124253e034d5bd82f',
},
isLiveBlog: false,
pillar: 'culture',
designType: 'Review',
format: {
design: 'ReviewDesign',
theme: 'CulturePillar',
display: 'StandardDisplay',
},
webPublicationDate: '2021-11-18T12:54:16.000Z',
headline:
'Crime review – Irvine Welsh’s first TV drama is a dreich and plodding affair',
shortUrl: 'https://www.theguardian.com/p/jjht4',
starRating: 3,
},
{
url: 'https://www.theguardian.com/tv-and-radio/2021/nov/18/the-sex-lives-of-college-girls-review-mindy-kaling',
linkText:
'The Sex Lives of College Girls review – Mindy Kaling’s uneven comedy has promise',
showByline: false,
byline: 'Adrian Horton',
image: 'https://i.guim.co.uk/img/media/2cfc066b61959ba6a1a1f7286242553c4f979a86/0_60_1920_1152/master/1920.jpg?width=300&quality=85&auto=format&fit=max&s=c39a2e269d7f9da3354ff38c0fddf4d0',
carouselImages: {
'300': 'https://i.guim.co.uk/img/media/2cfc066b61959ba6a1a1f7286242553c4f979a86/0_60_1920_1152/master/1920.jpg?width=300&quality=85&auto=format&fit=max&s=c39a2e269d7f9da3354ff38c0fddf4d0',
'460': 'https://i.guim.co.uk/img/media/2cfc066b61959ba6a1a1f7286242553c4f979a86/0_60_1920_1152/master/1920.jpg?width=460&quality=85&auto=format&fit=max&s=958935122425e4fcb18d01f5e8c2ccdc',
},
isLiveBlog: false,
pillar: 'culture',
designType: 'Review',
format: {
design: 'ReviewDesign',
theme: 'CulturePillar',
display: 'StandardDisplay',
},
webPublicationDate: '2021-11-18T06:31:04.000Z',
headline:
'The Sex Lives of College Girls review – Mindy Kaling’s uneven comedy has promise',
shortUrl: 'https://www.theguardian.com/p/jjgpb',
starRating: 3,
},
{
url: 'https://www.theguardian.com/tv-and-radio/2021/nov/17/tiger-king-2-review-joe-exotic-causes-big-cat-chaos-minus-carole-baskin',
linkText:
'Tiger King 2 review: Joe Exotic causes big cat chaos – minus Carole Baskin',
showByline: false,
byline: 'Jack Seale',
image: 'https://i.guim.co.uk/img/media/53ac0bc4197e421ef8d05e22aaa58664b5b68c7c/285_0_3274_1964/master/3274.jpg?width=300&quality=85&auto=format&fit=max&s=ed0abab9c62311515f13483337a3718f',
carouselImages: {
'300': 'https://i.guim.co.uk/img/media/53ac0bc4197e421ef8d05e22aaa58664b5b68c7c/285_0_3274_1964/master/3274.jpg?width=300&quality=85&auto=format&fit=max&s=ed0abab9c62311515f13483337a3718f',
'460': 'https://i.guim.co.uk/img/media/53ac0bc4197e421ef8d05e22aaa58664b5b68c7c/285_0_3274_1964/master/3274.jpg?width=460&quality=85&auto=format&fit=max&s=9a79d5f6ad60b21b7eb9d0519f8199b6',
},
isLiveBlog: false,
pillar: 'culture',
designType: 'Review',
format: {
design: 'ReviewDesign',
theme: 'CulturePillar',
display: 'StandardDisplay',
},
webPublicationDate: '2021-11-17T12:15:15.000Z',
headline:
'Tiger King 2 review: Joe Exotic causes big cat chaos – minus Carole Baskin',
shortUrl: 'https://www.theguardian.com/p/jja7b',
starRating: 3,
},
{
url: 'https://www.theguardian.com/tv-and-radio/2021/nov/16/miriam-and-alan-lost-in-scotland-review-a-large-pile-of-anticlimaxes',
linkText:
'Miriam and Alan: Lost in Scotland review – a large pile of anticlimaxes',
showByline: false,
byline: 'Lucy Mangan',
image: 'https://i.guim.co.uk/img/media/03ed99971452dd022b71de360d9a8883ae0bedc4/0_311_3050_1830/master/3050.jpg?width=300&quality=85&auto=format&fit=max&s=61ad98597ffcce7503c575971d258d83',
carouselImages: {
'300': 'https://i.guim.co.uk/img/media/03ed99971452dd022b71de360d9a8883ae0bedc4/0_311_3050_1830/master/3050.jpg?width=300&quality=85&auto=format&fit=max&s=61ad98597ffcce7503c575971d258d83',
'460': 'https://i.guim.co.uk/img/media/03ed99971452dd022b71de360d9a8883ae0bedc4/0_311_3050_1830/master/3050.jpg?width=460&quality=85&auto=format&fit=max&s=f6337fffeb6b71796abdb6960fe073a2',
},
isLiveBlog: false,
pillar: 'culture',
designType: 'Review',
format: {
design: 'ReviewDesign',
theme: 'CulturePillar',
display: 'StandardDisplay',
},
webPublicationDate: '2021-11-16T22:15:19.000Z',
headline:
'Miriam and Alan: Lost in Scotland review – a large pile of anticlimaxes',
shortUrl: 'https://www.theguardian.com/p/jtqnv',
starRating: 2,
},
{
url: 'https://www.theguardian.com/tv-and-radio/2021/nov/15/diana-queen-of-style-review-englands-biggest-punk-i-think-not',
linkText:
'Diana: Queen of Style review – ‘England’s biggest punk’? I think not',
showByline: false,
byline: 'Lucy Mangan',
image: 'https://i.guim.co.uk/img/media/9980b467e9780e8e9acd85bc3b12f71661396980/0_61_2435_1461/master/2435.jpg?width=300&quality=85&auto=format&fit=max&s=22c5431923342348c6f1278d7607137d',
carouselImages: {
'300': 'https://i.guim.co.uk/img/media/9980b467e9780e8e9acd85bc3b12f71661396980/0_61_2435_1461/master/2435.jpg?width=300&quality=85&auto=format&fit=max&s=22c5431923342348c6f1278d7607137d',
'460': 'https://i.guim.co.uk/img/media/9980b467e9780e8e9acd85bc3b12f71661396980/0_61_2435_1461/master/2435.jpg?width=460&quality=85&auto=format&fit=max&s=e9dd874b96afb91b795bc8f7cb4650cb',
},
isLiveBlog: false,
pillar: 'culture',
designType: 'Review',
format: {
design: 'ReviewDesign',
theme: 'CulturePillar',
display: 'StandardDisplay',
},
webPublicationDate: '2021-11-15T23:05:14.000Z',
headline:
'Diana: Queen of Style review – ‘England’s biggest punk’? I think not',
shortUrl: 'https://www.theguardian.com/p/jjv2c',
starRating: 2,
},
{
url: 'https://www.theguardian.com/tv-and-radio/2021/nov/14/top-gear-review-boy-racers-go-full-throttle-in-the-wrong-kind-of-drag-race',
linkText:
'Top Gear review – boy racers go full-throttle in the wrong kind of drag race',
showByline: false,
byline: 'Stuart Jeffries',
image: 'https://i.guim.co.uk/img/media/1df35cfea25173b76ab66b3960ea944cfa7dbded/0_143_4285_2571/master/4285.jpg?width=300&quality=85&auto=format&fit=max&s=d3580a6293f7e6d83c10040317e1936c',
carouselImages: {
'300': 'https://i.guim.co.uk/img/media/1df35cfea25173b76ab66b3960ea944cfa7dbded/0_143_4285_2571/master/4285.jpg?width=300&quality=85&auto=format&fit=max&s=d3580a6293f7e6d83c10040317e1936c',
'460': 'https://i.guim.co.uk/img/media/1df35cfea25173b76ab66b3960ea944cfa7dbded/0_143_4285_2571/master/4285.jpg?width=460&quality=85&auto=format&fit=max&s=a8f0369296d817e1b9d2e0acfb34938f',
},
isLiveBlog: false,
pillar: 'culture',
designType: 'Review',
format: {
design: 'ReviewDesign',
theme: 'CulturePillar',
display: 'StandardDisplay',
},
webPublicationDate: '2021-11-14T21:00:10.000Z',
headline:
'Top Gear review – boy racers go full-throttle in the wrong kind of drag race',
shortUrl: 'https://www.theguardian.com/p/jhken',
starRating: 3,
},
{
url: 'https://www.theguardian.com/tv-and-radio/2021/nov/12/the-shrink-next-door-review-paul-rudd-will-ferrell',
linkText:
'The Shrink Next Door review – Paul Rudd traps Will Ferrell in a cult of two',
showByline: false,
byline: 'Lucy Mangan',
image: 'https://i.guim.co.uk/img/media/8c7b55556d2529a14ed09f32d6dd115063770d18/158_0_3301_1981/master/3301.png?width=300&quality=85&auto=format&fit=max&s=4789737efa812992a183f272dd925e17',
carouselImages: {
'300': 'https://i.guim.co.uk/img/media/8c7b55556d2529a14ed09f32d6dd115063770d18/158_0_3301_1981/master/3301.png?width=300&quality=85&auto=format&fit=max&s=4789737efa812992a183f272dd925e17',
'460': 'https://i.guim.co.uk/img/media/8c7b55556d2529a14ed09f32d6dd115063770d18/158_0_3301_1981/master/3301.png?width=460&quality=85&auto=format&fit=max&s=96d2dcd50caaf9c57214c9193bdeb12b',
},
isLiveBlog: false,
pillar: 'culture',
designType: 'Review',
format: {
design: 'ReviewDesign',
theme: 'CulturePillar',
display: 'StandardDisplay',
},
webPublicationDate: '2021-11-12T11:00:01.000Z',
headline:
'The Shrink Next Door review – Paul Rudd traps Will Ferrell in a cult of two',
shortUrl: 'https://www.theguardian.com/p/jhjcx',
starRating: 3,
},
{
url: 'https://www.theguardian.com/tv-and-radio/2021/nov/12/dopesick-review-the-heinous-truth-behind-americas-opioid-emergency',
linkText:
'Dopesick review – the heinous truth behind America’s opioid emergency',
showByline: false,
byline: 'Lucy Mangan',
image: 'https://i.guim.co.uk/img/media/ad812d75102afa8ab1ad1797ddbc7e142b8e4fdf/0_5_8256_4954/master/8256.jpg?width=300&quality=85&auto=format&fit=max&s=ba5179f7a1352f0f12970d8ad999e547',
carouselImages: {
'300': 'https://i.guim.co.uk/img/media/ad812d75102afa8ab1ad1797ddbc7e142b8e4fdf/0_5_8256_4954/master/8256.jpg?width=300&quality=85&auto=format&fit=max&s=ba5179f7a1352f0f12970d8ad999e547',
'460': 'https://i.guim.co.uk/img/media/ad812d75102afa8ab1ad1797ddbc7e142b8e4fdf/0_5_8256_4954/master/8256.jpg?width=460&quality=85&auto=format&fit=max&s=1f2c5b2ab0e93041f50214a93430ca3d',
},
isLiveBlog: false,
pillar: 'culture',
designType: 'Review',
format: {
design: 'ReviewDesign',
theme: 'CulturePillar',
display: 'StandardDisplay',
},
webPublicationDate: '2021-11-12T09:00:31.000Z',
headline:
'Dopesick review – the heinous truth behind America’s opioid emergency',
shortUrl: 'https://www.theguardian.com/p/jhxnk',
starRating: 3,
},
],
}; | the_stack |
import { Canvas as GCanvas, Group } from '@antv/g-canvas';
import { Event as GraphEvent, Point } from '@antv/g-base';
import { isNil, each, debounce } from '@antv/util';
import { Matrix, ShapeStyle, IAbstractGraph as IGraph } from '@antv/f6-core';
import { ext } from '@antv/matrix-util';
import Base, { IPluginBaseConfig } from '../base';
import { createUI } from '@antv/f6-ui';
const { max } = Math;
const { transform } = ext;
const DEFAULT_MODE = 'default';
const KEYSHAPE_MODE = 'keyShape';
const DELEGATE_MODE = 'delegate';
interface MiniMapConfig extends IPluginBaseConfig {
viewportClassName?: string;
className?: string;
type?: 'default' | 'keyShape' | 'delegate';
size?: number[];
delegateStyle?: ShapeStyle;
refresh?: boolean;
padding?: number;
getCss?: Function;
}
export default class MiniMap extends Base {
constructor(config?: MiniMapConfig) {
super(config);
}
this: IGraph;
public getDefaultCfgs(): MiniMapConfig {
return {
container: null,
className: '',
viewportClassName: '',
// Minimap 中默认展示和主图一样的内容,KeyShape 只展示节点和边的 key shape 部分,delegate表示展示自定义的rect,用户可自定义样式
type: 'default',
padding: 50,
size: [200, 120],
delegateStyle: {
fill: '#40a9ff',
stroke: '#096dd9',
},
refresh: true,
};
}
public getEvents() {
return {
beforepaint: 'updateViewport',
beforeanimate: 'disableRefresh',
afteranimate: 'enableRefresh',
viewportchange: 'disableOneRefresh',
};
}
// 若是正在进行动画,不刷新缩略图
protected disableRefresh() {
this.set('refresh', false);
}
protected enableRefresh() {
this.set('refresh', true);
this.updateCanvas();
}
protected disableOneRefresh() {
this.set('viewportChange', true);
}
private initViewport() {
const cfgs: MiniMapConfig = this._cfgs as MiniMapConfig;
const { size, graph } = cfgs;
if (this.destroyed) return;
// viewport 就是minimap的缩略图 拖拽方框 小程序模式下 不能使用createDom 使用createUi替代
const handleUI = this.get('container').query('.viewport');
// 计算拖拽水平方向距离
let x = 0;
// 计算拖拽垂直方向距离
let y = 0;
// 是否在拖拽minimap的视口
let dragging = false;
// 缓存viewport当前对于画布的x
let left = 0;
// 缓存viewport当前对于画布的y
let top = 0;
// 缓存viewport当前宽度
let width = 0;
// 缓存viewport当前高度
let height = 0;
let ratio = 0;
let zoom = 0;
// 拖拽start事件
handleUI.on('panstart', (e: GraphEvent) => {
cfgs.refresh = false;
// 如果视口已经最大了,不需要拖拽
left = parseInt(handleUI.getStyle('left'), 10);
top = parseInt(handleUI.getStyle('top'), 10);
width = parseInt(handleUI.getStyle('width'), 10);
height = parseInt(handleUI.getStyle('height'), 10);
if (width > size[0] || height > size[1]) {
return;
}
zoom = graph!.getZoom();
ratio = this.get('ratio');
dragging = true;
x = e.x;
y = e.y;
});
handleUI.on(
'panmove',
(e: GraphEvent) => {
if (!dragging || isNil(e.x) || isNil(e.y)) {
return;
}
let dx = x - e.x;
let dy = y - e.y;
// 若视口移动到最左边或最右边了,仅移动到边界
if (left - dx < 0 || left - dx + width >= size[0]) {
dx = 0;
}
// 若视口移动到最上或最下边了,仅移动到边界
if (top - dy < 0 || top - dy + height >= size[1]) {
dy = 0;
}
left -= dx;
top -= dy;
// graph 移动需要偏移量 dx/dy * 缩放比例才会得到正确的移动距离
graph!.translate((dx * zoom) / ratio, (dy * zoom) / ratio);
x = e.x;
y = e.y;
},
false,
);
handleUI.on(
'panend',
() => {
dragging = false;
cfgs.refresh = true;
},
false,
);
this.set('viewport', handleUI); // 这里viewport的 key 先保留,下面继续使用
}
/**
* 更新 viewport 视图
*/
private updateViewport() {
if (this.destroyed) return;
const ratio: number = this.get('ratio');
const totaldx: number = this.get('totaldx');
const totaldy: number = this.get('totaldy');
const graph: IGraph = this.get('graph');
const size: number[] = this.get('size');
const graphWidth = graph.get('width');
const graphHeight = graph.get('height');
const topLeft: Point = graph.getPointByCanvas(0, 0);
const bottomRight: Point = graph.getPointByCanvas(graphWidth, graphHeight);
const viewport = this.get('viewport');
// viewport宽高,左上角点的计算
let width = (bottomRight.x - topLeft.x) * ratio;
let height = (bottomRight.y - topLeft.y) * ratio;
let left = topLeft.x * ratio + totaldx;
let top = topLeft.y * ratio + totaldy;
const right = left + width;
const bottom = top + height;
if (left < 0) {
width += left;
left = 0;
}
if (right >= size[0]) {
width = width - (right - size[0]);
}
if (top < 0) {
height += top;
top = 0;
}
if (bottom > size[1]) {
height = height - (bottom - size[1]);
}
// 缓存目前缩放比,在移动 minimap 视窗时就不用再计算大图的移动量
this.set('ratio', ratio);
if (viewport) {
const borderWidth = viewport.getStyle('borderWidth');
if (Math.floor(width) >= borderWidth * 2) {
viewport.setStyle('left', left);
viewport.setStyle('width', width);
}
if (Math.floor(height) >= borderWidth * 2) {
viewport.setStyle('top', top);
viewport.setStyle('height', height);
}
}
}
/**
* 将主图上的图形完全复制到小图
*/
private updateGraphShapes() {
const { graph } = this._cfgs;
const graphGroup = graph!.get('group');
if (graphGroup.destroyed) return;
const clonedGroup = graphGroup.clone();
const groupCanvas = this.get('groupCanvas');
clonedGroup.resetMatrix();
groupCanvas.clear();
groupCanvas.add(clonedGroup);
}
// 仅在 minimap 上绘制 keyShape
// FIXME 如果用户自定义绘制了其他内容,minimap上就无法画出
private updateKeyShapes() {
const { graph } = this._cfgs;
const group = this.get('groupCanvas'); // canvas.get('children')[0] || canvas.addGroup();
each(graph!.getEdges(), (edge) => {
this.updateOneEdgeKeyShape(edge, group);
});
each(graph!.getNodes(), (node) => {
this.updateOneNodeKeyShape(node, group);
});
const combos = graph!.getCombos();
if (combos && combos.length) {
const comboGroup =
group.find((e) => e.get('name') === 'comboGroup') ||
group.addGroup({
name: 'comboGroup',
});
setTimeout(() => {
if (this.destroyed) return;
each(combos, (combo) => {
this.updateOneComboKeyShape(combo, comboGroup);
});
comboGroup?.sort();
comboGroup?.toBack();
this.updateCanvas();
}, 250);
}
this.clearDestroyedShapes();
}
/**
* 增加/更新单个元素的 keyShape
* @param item ICombo 实例
*/
private updateOneComboKeyShape(item, comboGroup) {
if (this.destroyed) return;
const itemMap = this.get('itemMap') || {};
// 差量更新 minimap 上的一个节点,对应主图的 item
let mappedItem = itemMap[item.get('id')];
const bbox = item.getBBox(); // 计算了节点父组矩阵的 bbox
const cKeyShape = item.get('keyShape').clone();
const keyShapeStyle = cKeyShape.attr();
let attrs: any = {
x: bbox.centerX,
y: bbox.centerY,
};
if (!mappedItem) {
mappedItem = cKeyShape;
comboGroup.add(mappedItem);
} else {
attrs = Object.assign(keyShapeStyle, attrs);
}
const shapeType = mappedItem.get('type');
if (shapeType === 'rect' || shapeType === 'image') {
attrs.x = bbox.minX;
attrs.y = bbox.minY;
}
mappedItem.attr(attrs);
if (!item.isVisible()) mappedItem.hide();
else mappedItem.show();
mappedItem.exist = true;
const zIndex = item.getModel().depth;
if (!isNaN(zIndex)) mappedItem.set('zIndex', zIndex);
itemMap[item.get('id')] = mappedItem;
this.set('itemMap', itemMap);
}
/**
* 增加/更新单个元素的 keyShape
* @param item INode 实例
*/
private updateOneNodeKeyShape(item, group) {
const itemMap = this.get('itemMap') || {};
// 差量更新 minimap 上的一个节点,对应主图的 item
let mappedItem = itemMap[item.get('id')];
const bbox = item.getBBox(); // 计算了节点父组矩阵的 bbox
const cKeyShape = item.get('keyShape').clone();
const keyShapeStyle = cKeyShape.attr();
let attrs: any = {
x: bbox.centerX,
y: bbox.centerY,
};
if (!mappedItem) {
mappedItem = cKeyShape;
group.add(mappedItem);
} else {
attrs = Object.assign(keyShapeStyle, attrs);
}
const shapeType = mappedItem.get('type');
if (shapeType === 'rect' || shapeType === 'image') {
attrs.x = bbox.minX;
attrs.y = bbox.minY;
}
mappedItem.attr(attrs);
if (!item.isVisible()) mappedItem.hide();
else mappedItem.show();
mappedItem.exist = true;
const zIndex = item.getModel().depth;
if (!isNaN(zIndex)) mappedItem.set('zIndex', zIndex);
itemMap[item.get('id')] = mappedItem;
this.set('itemMap', itemMap);
}
/**
* Minimap 中展示自定义的rect,支持用户自定义样式和节点大小
*/
private updateDelegateShapes() {
const { graph } = this._cfgs;
const group = this.get('groupCanvas');
// 差量更新 minimap 上的节点和边
each(graph!.getEdges(), (edge) => {
this.updateOneEdgeKeyShape(edge, group);
});
each(graph!.getNodes(), (node) => {
this.updateOneNodeDelegateShape(node, group);
});
const combos = graph!.getCombos();
if (combos && combos.length) {
const comboGroup =
group.find((e) => e.get('name') === 'comboGroup') ||
group.addGroup({
name: 'comboGroup',
});
setTimeout(() => {
if (this.destroyed) return;
each(combos, (combo) => {
this.updateOneComboKeyShape(combo, comboGroup);
});
comboGroup?.sort();
comboGroup?.toBack();
this.updateCanvas();
}, 250);
}
this.clearDestroyedShapes();
}
private clearDestroyedShapes() {
const itemMap = this.get('itemMap') || {};
const keys = Object.keys(itemMap);
if (!keys || keys.length === 0) return;
for (let i = keys.length - 1; i >= 0; i--) {
const shape = itemMap[keys[i]];
const exist = shape.exist;
shape.exist = false;
if (!exist) {
shape.remove();
delete itemMap[keys[i]];
}
}
}
/**
* 设置只显示 edge 的 keyShape
* @param item IEdge 实例
*/
private updateOneEdgeKeyShape(item, group) {
const itemMap = this.get('itemMap') || {};
// 差量更新 minimap 上的一个节点,对应主图的 item
let mappedItem = itemMap[item.get('id')];
if (mappedItem) {
const path = item.get('keyShape').attr('path');
mappedItem.attr('path', path);
} else {
mappedItem = item.get('keyShape').clone();
group.add(mappedItem);
}
if (!item.isVisible()) mappedItem.hide();
else mappedItem.show();
mappedItem.exist = true;
itemMap[item.get('id')] = mappedItem;
this.set('itemMap', itemMap);
}
/**
* Minimap 中展示自定义的 rect,支持用户自定义样式和节点大小
* 增加/更新单个元素
* @param item INode 实例
*/
private updateOneNodeDelegateShape(item, group) {
const delegateStyle = this.get('delegateStyle');
const itemMap = this.get('itemMap') || {};
// 差量更新 minimap 上的一个节点,对应主图的 item
let mappedItem = itemMap[item.get('id')];
const bbox = item.getBBox(); // 计算了节点父组矩阵的 bbox
if (mappedItem) {
const attrs = {
x: bbox.minX,
y: bbox.minY,
width: bbox.width,
height: bbox.height,
};
mappedItem.attr(attrs);
} else {
mappedItem = group.addShape('rect', {
attrs: {
x: bbox.minX,
y: bbox.minY,
width: bbox.width,
height: bbox.height,
...delegateStyle,
},
name: 'minimap-node-shape',
});
}
if (!item.isVisible()) mappedItem.hide();
else mappedItem.show();
mappedItem.exist = true;
itemMap[item.get('id')] = mappedItem;
this.set('itemMap', itemMap);
}
/**
* 主图更新的监听函数,使用 debounce 减少渲染频率
* e.g. 拖拽节点只会在松手后的 100ms 后执行 updateCanvas
* e.g. render 时大量 addItem 也只会执行一次 updateCanvas
*/
private handleUpdateCanvas = debounce(
(event) => {
const self = this;
if (self.destroyed) return;
self.updateCanvas();
},
100,
false,
);
public init() {
this.get('graph').on('afterupdateitem', this.handleUpdateCanvas);
this.get('graph').on('afteritemstatechange', this.handleUpdateCanvas);
this.get('graph').on('afteradditem', this.handleUpdateCanvas);
this.get('graph').on('afterremoveitem', this.handleUpdateCanvas);
this.get('graph').on('afterrender', this.handleUpdateCanvas);
this.get('graph').on('afterlayout', this.handleUpdateCanvas);
setTimeout(() => {
this.initContainer();
});
}
/**
* 初始化 Minimap 的容器
*/
public initContainer() {
const self = this;
const graph: IGraph = self.get('graph');
const size: number[] = self.get('size');
const className: string = self.get('className');
const viewportClassName: string = self.get('viewportClassName');
const getCss = self.get('getCss');
const containerHtml = `
<div class='f6-minimap ${className}'>
<div class="f6-minimap-container"></div>
<div class="viewport ${viewportClassName}"></div>
</div>`;
const containerCss = `
root {
width: ${graph.getWidth()};
height: ${graph.getHeight()};
opacity: 0;
pointer-events: none;
}
.f6-minimap{
position: absolute;
left: 0;
bottom: 0;
width: ${size[0]}; height: ${size[1]};
}
.f6-minimap-container{
position: relative;
background: rgba(0,0,0,0);
width: ${size[0]}; height: ${size[1]};
}
.viewport{
position: absolute;
border: 3 solid blue;
width: 100;
height: 100;
background: rgba(0,0,0,0);
z-index: 1000;
}
${getCss?.() ?? ''}
`;
const uiGroup = graph.get('uiGroup');
const miniMapContainerUI = createUI(containerHtml, containerCss, uiGroup);
const background = miniMapContainerUI.query('.f6-minimap-container');
const group = background.gNode;
const canvasGroup = group.addGroup();
this.set('groupCanvas', canvasGroup);
this.set('container', miniMapContainerUI);
self.updateCanvas();
this.initViewport();
}
public updateCanvas() {
if (this.destroyed) return;
// 如果是在动画,则不刷新视图
const isRefresh: boolean = this.get('refresh');
if (!isRefresh) {
return;
}
const graph: IGraph = this.get('graph');
if (graph.get('destroyed')) {
return;
}
// 如果是视口变换,也不刷新视图,但是需要重置视口大小和位置
if (this.get('viewportChange')) {
this.set('viewportChange', false);
this.updateViewport();
}
const size: number[] = this.get('size'); // 用户定义的 minimap size
const type: string = this.get('type'); // minimap 的类型
const padding: number = this.get('padding'); // 用户额定义的 minimap 的 padding
switch (type) {
case DEFAULT_MODE:
this.updateGraphShapes();
break;
case KEYSHAPE_MODE:
this.updateKeyShapes();
break;
case DELEGATE_MODE:
// 得到的节点直接带有 x 和 y,每个节点不存在父 group,即每个节点位置不由父 group 控制
this.updateDelegateShapes();
break;
default:
break;
}
const group = this.get('groupCanvas'); // canvas.get('children')[0];
if (!group) return;
group.resetMatrix();
// 重新计算所有子节点的matrix,从group开始重新计算totalmatrix,重置传递下来的matrix,保证计算canvasBBox的时候,相对左上角
group.applyMatrix([1, 0, 0, 0, 1, 0, 0, 0, 1]);
const bbox = group.getCanvasBBox();
const graphBBox = graph.get('group').getCanvasBBox(); // 主图的 bbox
const graphZoom = graph.getZoom() || 1;
let width = graphBBox.width / graphZoom;
let height = graphBBox.height / graphZoom;
if (Number.isFinite(bbox.width)) {
// 刷新后bbox可能会变,需要重置画布矩阵以缩放到合适的大小
width = max(bbox.width, width);
height = max(bbox.height, height);
}
width += 2 * padding;
height += 2 * padding;
const ratio = Math.min(size[0] / width, size[1] / height);
let matrix: Matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1];
let minX = 0;
let minY = 0;
// 平移到左上角
if (Number.isFinite(bbox.minX)) {
minX = -bbox.minX;
}
if (Number.isFinite(bbox.minY)) {
minY = -bbox.minY;
}
// 缩放到适合视口后, 平移到画布中心
const dx = (size[0] - (width - 2 * padding) * ratio) / 2;
const dy = (size[1] - (height - 2 * padding) * ratio) / 2;
matrix = transform(matrix, [
['t', minX, minY], // 平移到左上角
['s', ratio, ratio], // 缩放到正好撑着 minimap
['t', dx, dy], // 移动到画布中心
]);
group.setMatrix(matrix);
// 更新minimap视口
this.set('ratio', ratio);
this.set('totaldx', dx + minX * ratio);
this.set('totaldy', dy + minY * ratio);
this.set('dx', dx);
this.set('dy', dy);
this.updateViewport();
}
/**
* 获取minimap的画布
* @return {GCanvas} G的canvas实例
*/
public getCanvas(): GCanvas {
return this.get('canvas');
}
/**
* 获取minimap的窗口
* @return {HTMLElement} 窗口的dom实例
*/
public getViewport(): HTMLElement {
return this.get('viewport');
}
/**
* 获取minimap的容器dom
* @return {HTMLElement} dom
*/
public getContainer(): HTMLElement {
return this.get('container');
}
public destroy() {
this.get('container')?.remove();
}
} | the_stack |
import * as performance from "./performance";
import { SourceFile } from "./nodes";
import { Parser } from "./parser";
import { toCancelToken, isUri } from "./core";
import { CancelToken } from "@esfx/async-canceltoken";
import { Cancelable } from "@esfx/cancelable";
/**
* Asynchronously read a file from the host.
*
* @param file The resolved path to the file.
* @param cancelToken An optional `CancelToken` that indicates whether the operation was canceled.
* @returns A `string` containing the contents of the file, or `undefined` if the file could not be read.
*
* {@docCategory Hosts}
*/
export type ReadFileCallback = (this: void, file: string, cancelToken?: CancelToken) => PromiseLike<string | undefined> | string | undefined;
/**
* Asynchronously write a file to the host.
*
* @param file The resolved path to the file.
* @param content The contents of the file.
* @param cancelToken An optional `CancelToken` that indicates whether the operation was canceled.
*
* {@docCategory Hosts}
*/
export type WriteFileCallback = (this: void, file: string, content: string, cancelToken?: CancelToken) => PromiseLike<void> | void;
/**
* Options used to configure a {@link CoreAsyncHost}.
*
* {@docCategory Hosts}
*/
export interface CoreAsyncHostOptions {
/**
* Indicates whether the host is case-insensitive (`true`) or case-sensitive (`false`).
*/
ignoreCase?: boolean;
/**
* A set of known grammars in the form `{ "name": "path" }`
*/
knownGrammars?: Record<string, string>;
/**
* Indicates whether to include builtin grammars in the set of known grammars.
*/
useBuiltinGrammars?: boolean;
/**
* A callback used to control file normalization when generating keys for maps based on the case sensitivity of the host.
*/
normalizeFile?: (this: void, file: string, fallback: (file: string) => string) => string;
/**
* A callback used to control file resolution.
*/
resolveFile?: (this: void, file: string, referer: string | undefined, fallback: (file: string, referer?: string) => string) => string;
/**
* A callback used to control known grammar resolution.
*/
resolveKnownGrammar?: (this: void, name: string, fallback: (name: string) => string | undefined) => string | undefined;
/**
* A callback used to control asynchronous file reads.
*/
readFile?: (this: void, file: string, cancelToken: CancelToken | undefined, fallback: (file: string, cancelToken?: CancelToken) => Promise<string | undefined>) => PromiseLike<string | undefined> | string | undefined;
/**
* A callback used to control asynchronous file writes.
*/
writeFile?: (this: void, file: string, content: string, cancelToken: CancelToken | undefined, fallback: (file: string, content: string, cancelToken?: CancelToken) => Promise<void>) => PromiseLike<void> | void;
}
/**
* A Host is a user-provided service that indicates how various Grammarkdown services
* can interact with a file system. The `CoreAsyncHost` class provides the API surface that Grammarkdown
* uses to interact with a host that is able to access the file system asynchronously.
*
* {@docCategory Hosts}
*/
export class CoreAsyncHost {
private _ignoreCase: boolean;
private _innerParser: Parser | undefined;
private _knownGrammars: Map<string, string> | undefined;
private _useBuiltinGrammars: boolean;
private _normalizeFile: CoreAsyncHostOptions["normalizeFile"];
private _resolveFile: CoreAsyncHostOptions["resolveFile"];
private _resolveKnownGrammar: CoreAsyncHostOptions["resolveKnownGrammar"];
private _readFile: CoreAsyncHostOptions["readFile"];
private _writeFile: CoreAsyncHostOptions["writeFile"];
private _hostFallback?: CoreAsyncHost;
private _normalizeFileCallback?: (file: string) => string;
private _resolveFileCallback?: (file: string, referer?: string) => string;
private _resolveKnownGrammarCallback?: (name: string) => string | undefined;
private _readFileCallback?: (file: string, cancelToken?: CancelToken) => Promise<string | undefined>;
private _writeFileCallback?: (file: string, content: string, cancelToken?: CancelToken) => Promise<void>;
/**
* @param options The options used to configure the host.
* @param hostFallback An optional host to use as a fallback for operations not supported by this host.
*/
constructor(options: CoreAsyncHostOptions, hostFallback?: CoreAsyncHost) {
const {
ignoreCase = hostFallback?.ignoreCase ?? false,
knownGrammars,
useBuiltinGrammars = true,
normalizeFile,
resolveFile,
resolveKnownGrammar,
readFile,
writeFile,
} = options;
this._ignoreCase = ignoreCase;
this._useBuiltinGrammars = useBuiltinGrammars;
if (knownGrammars) {
for (const key in knownGrammars) if (Object.prototype.hasOwnProperty.call(knownGrammars, key)) {
this.registerKnownGrammar(key, knownGrammars[key]);
}
}
this._normalizeFile = normalizeFile;
this._resolveFile = resolveFile;
this._resolveKnownGrammar = resolveKnownGrammar;
this._readFile = readFile;
this._writeFile = writeFile;
this._hostFallback = hostFallback;
}
/**
* Indicates whether comparisons for this host should be case insensitive.
*/
public get ignoreCase() {
return this._ignoreCase;
}
/**
* Gets the parser instance associated with this host.
*/
protected get parser(): Parser {
return this._innerParser
|| (this._innerParser = this.createParser());
}
/**
* Creates a {@link StringAsyncHost} for the provided content.
* @param content The content of the file.
* @param file The file name for the content.
* @param hostFallback An optional host to use as a fallback for operations not supported by this host.
*/
public static forFile(content: PromiseLike<string> | string, file = "file.grammar", hostFallback?: CoreAsyncHost) {
return new StringAsyncHost(file, content, hostFallback);
}
/**
* Creates a `CoreAsyncHost`.
* @param options The options used to configure the host.
* @param hostFallback An optional host to use as a fallback for operations not supported by this host.
*/
public static from(custom: CoreAsyncHostOptions, hostFallback?: CoreAsyncHost) {
return new CoreAsyncHost(custom, hostFallback);
}
/**
* Normalize a file path's string representation for use as a key based on the case sensitivity of the host.
* @param file The file path.
*/
public normalizeFile(file: string) {
return this.normalizeFileCore(file);
}
/**
* Returns the path for a known or built-in grammar based on its name (i.e., `"es2015"`, etc.)
* @param name The name of the grammar.
*/
public resolveKnownGrammar(name: string) {
return this.resolveKnownGrammarCore(name)
?? (this._useBuiltinGrammars ? resolveBuiltInGrammar(name) : undefined);
}
/**
* Registers a known grammar for use with `@import` directives.
* @param name The name for the grammar.
* @param file The file path of the grammar.
*/
public registerKnownGrammar(name: string, file: string) {
this.registerKnownGrammarCore(name, file);
}
/**
* Resolve the full path of a file relative to the provided referer.
* @param file The path to the requested file.
* @param referer An optional path indicating the file from which the path should be resolved.
*/
public resolveFile(file: string, referer?: string): string {
file = this.resolveKnownGrammar(file) || file;
let result = this.resolveFileCore(file, referer);
result = result.replace(/\\/g, "/");
return result;
}
/**
* Parse a source file.
* @param file The path to the source file.
* @param text The text of the source file.
* @param cancelable An optional cancelable object that can be used to abort a long-running parse.
*/
public parseSourceFile(file: string, text: string, cancelable?: Cancelable): SourceFile {
performance.mark("beforeParse");
try {
return this.parser.parseSourceFile(file, text, cancelable);
}
finally {
performance.mark("afterParse");
performance.measure("parse", "beforeParse", "afterParse");
}
}
/**
* Reads a file from the host.
* @param file The path to the file.
* @param cancelable A cancelable object that can be used to abort the operation.
* @returns A `Promise` for either a `string` containing the content if the file could be read, or `undefined` if the file could not be read.
*/
public async readFile(file: string, cancelable?: Cancelable): Promise<string | undefined> {
performance.mark("ioRead");
try {
return await this.readFileCore(file, toCancelToken(cancelable));
}
finally {
performance.measure("ioRead", "ioRead");
}
}
/**
* Writes a file to the host.
* @param file The path to the file.
* @param text The contents of the file.
* @param cancelable A cancelable object that can be used to abort the operation.
* @returns A `Promise` that is settled when the operation completes.
*/
public async writeFile(file: string, text: string, cancelable?: Cancelable): Promise<void> {
performance.mark("ioWrite");
try {
await this.writeFileCore(file, text, toCancelToken(cancelable));
}
finally {
performance.measure("ioWrite", "ioWrite");
}
}
/**
* Reads and parses a source file from the host.
* @param file The path to the file.
* @param cancelable A cancelable object that can be used to abort the operation.
* @returns A `Promise` for either the parsed {@link SourceFile} of the file if the file could be read, or `undefined` if it could not be read.
*/
public async getSourceFile(file: string, cancelable?: Cancelable): Promise<SourceFile | undefined> {
cancelable = toCancelToken(cancelable);
const result = await this.readFile(file, cancelable);
return result !== undefined ? this.parseSourceFile(file, result, cancelable) : undefined;
}
/**
* Creates a {@link Parser} for this host.
* @virtual
*/
protected createParser(): Parser {
return new Parser();
}
/**
* When overridden in a derived class, normalizes a file path's string representation for use as a key based on the case sensitivity of the host.
* @param file The file path.
* @virtual
*/
protected normalizeFileCore(file: string): string {
const normalizeFile = this._normalizeFile;
if (normalizeFile) {
return normalizeFile(file, this._normalizeFileCallback ??= this._normalizeFileFallback.bind(this));
}
return this._normalizeFileFallback(file);
}
private _normalizeFileFallback(file: string): string {
return this._hostFallback?.normalizeFile(file)
?? (this.ignoreCase && !isUri(file) ? file.toUpperCase().toLowerCase() : file);
}
/**
* When overridden in a derived class, resolves the full path of a file relative to the provided referer.
* @param file The path to the requested file.
* @param referrer An optional path indicating the file from which the path should be resolved.
* @virtual
*/
protected resolveFileCore(file: string, referrer?: string) {
const resolveFile = this._resolveFile;
if (resolveFile) {
return resolveFile(file, referrer, this._resolveFileCallback ??= this._resolveFileFallback.bind(this));
}
return this._resolveFileFallback(file, referrer);
}
private _resolveFileFallback(file: string, referer?: string) {
if (this._hostFallback) return this._hostFallback.resolveFile(file, referer);
throw new Error("Cannot resolve a file without a fallback host.");
}
/**
* When overridden in a derived class, returns the path for a known or built-in grammar based on its name (i.e., `"es2015"`, etc.)
* @param name The name of the grammar.
* @virtual
*/
protected resolveKnownGrammarCore(name: string): string | undefined {
const resolveKnownGrammar = this._resolveKnownGrammar;
if (resolveKnownGrammar) {
return resolveKnownGrammar(name, this._resolveKnownGrammarCallback ??= this._resolveKnownGrammarFallback.bind(this));
}
return this._resolveKnownGrammarFallback(name);
}
private _resolveKnownGrammarFallback(name: string) {
return this._hostFallback?.resolveKnownGrammar(name);
}
/**
* When overridden in a derived clas, registers a known grammar for use with `@import` directives.
* @param name The name for the grammar.
* @param file The file path of the grammar.
* @virtual
*/
protected registerKnownGrammarCore(name: string, file: string) {
if (this._hostFallback) throw new Error("Known grammars must be registered on the fallback host.");
(this._knownGrammars ??= new Map()).set(name.toUpperCase(), file);
}
/**
* When overridden in a derived class, reads a file from the host.
* @param file The path to the file.
* @param cancelToken A cancellation token that can be used by the caller to abort the operation.
* @returns A `Promise` for either a `string` containing the content if the file could be read, or `undefined` if the file could not be read.
* @virtual
*/
protected async readFileCore(file: string, cancelToken?: CancelToken): Promise<string | undefined> {
const readFile = this._readFile;
if (readFile) {
return readFile(file, cancelToken, this._readFileCallback ??= this._readFileFallback.bind(this));
}
return this._readFileFallback(file, cancelToken);
}
private async _readFileFallback(file: string, cancelToken?: CancelToken) {
if (this._hostFallback) {
return this._hostFallback.readFile(file, cancelToken);
}
throw new Error(`File '${file}' cannot be read without a fallback host.`);
}
/**
* When overridden in a derived class, writes a file to the host.
* @param file The path to the file.
* @param text The contents of the file.
* @param cancelToken A cancellation token that can be used by the caller to abort the operation.
* @returns A `Promise` that is settled when the operation completes.
* @virtual
*/
protected async writeFileCore(file: string, content: string, cancelToken?: CancelToken) {
const writeFile = this._writeFile;
if (writeFile) {
return writeFile(file, content, cancelToken, this._writeFileCallback ??= this._writeFileFallback.bind(this));
}
return this._writeFileFallback(file, content, cancelToken);
}
private async _writeFileFallback(file: string, content: string, cancelToken?: CancelToken) {
if (this._hostFallback) {
return this._hostFallback.writeFile(file, content, cancelToken);
}
throw new Error(`Cannot write file without a fallback host.`);
}
}
/**
* An implementation of a {@link CoreAsyncHost} to simplify creating a host for a single file.
*
* {@docCategory Hosts}
*/
export class StringAsyncHost extends CoreAsyncHost {
/**
* The file name for the content.
*/
public readonly file: string;
/**
* The content of the file.
*/
public readonly content: PromiseLike<string> | string;
/**
* @param file The file name for the content.
* @param content The content of the file.
* @param hostFallback An optional host to use as a fallback for operations not supported by this host.
*/
constructor(file: string, content: PromiseLike<string> | string, hostFallback?: CoreAsyncHost) {
super({
normalizeFile: (file, fallback) => file === this.file ? file : fallback(file),
resolveFile: (file, referer, fallback) => file === this.file ? file : fallback(file, referer),
readFile: (file, cancelToken, fallback) => file === this.file ? this.content : fallback(file, cancelToken)
}, hostFallback);
this.file = file;
this.content = content;
}
}
let builtinGrammars: Map<string, string> | undefined;
function resolveBuiltInGrammar(name: string) {
if (!builtinGrammars) {
builtinGrammars = new Map<string, string>([
["ES6", require.resolve("../grammars/es2015.grammar")],
["ES2015", require.resolve("../grammars/es2015.grammar")],
["ES2020", require.resolve("../grammars/es2020.grammar")],
["TS", require.resolve("../grammars/typescript.grammar")],
["TYPESCRIPT", require.resolve("../grammars/typescript.grammar")],
]);
}
return builtinGrammars.get(name.toUpperCase());
} | the_stack |
import * as GS from 'gensequence';
import { genSequence as gs, Sequence } from 'gensequence';
import * as util from 'util';
import type { AffInfo, AffTransformFlags, AffWord, AffWordFlags, Fx, Rule, Substitution } from './affDef';
import { Converter } from './converter';
import { Mapping } from './types';
import { filterOrderedList, isDefined } from './util';
const log = false;
// cspell:ignore COMPOUNDBEGIN COMPOUNDEND COMPOUNDFORBIDFLAG COMPOUNDMIDDLE COMPOUNDMIN
// cspell:ignore FORBIDDENWORD KEEPCASE NEEDAFFIX
/** The `word` field in a Converted AffWord has been converted using the OCONV mapping */
export type ConvertedAffWord = AffWord;
const DefaultMaxDepth = 5;
export class Aff {
protected rules: Map<string, Rule>;
protected _oConv: Converter;
protected _iConv: Converter;
private _maxSuffixDepth = DefaultMaxDepth;
constructor(public affInfo: AffInfo) {
this.rules = processRules(affInfo);
this._iConv = new Converter(affInfo.ICONV || []);
this._oConv = new Converter(affInfo.OCONV || []);
}
public get maxSuffixDepth() {
return this._maxSuffixDepth;
}
public set maxSuffixDepth(value: number) {
this._maxSuffixDepth = value;
}
/**
* Takes a line from a hunspell.dic file and applies the rules found in the aff file.
* For performance reasons, only the `word` field is mapped with OCONV.
* @param {string} line - the line from the .dic file.
*/
applyRulesToDicEntry(line: string, maxDepth?: number): ConvertedAffWord[] {
const maxSuffixDepth = maxDepth ?? this.maxSuffixDepth;
const [lineLeft] = line.split(/\s+/, 1);
const [word, rules = ''] = lineLeft.split('/', 2);
const results = this.applyRulesToWord(asAffWord(word, rules), maxSuffixDepth).map((affWord) => ({
...affWord,
word: this._oConv.convert(affWord.word),
}));
results.sort(compareAff);
const filtered = results.filter(filterAff());
return filtered;
}
/**
* @internal
*/
applyRulesToWord(affWord: AffWord, remainingDepth: number): AffWord[] {
const compoundMin = this.affInfo.COMPOUNDMIN ?? 3;
const { word, base, suffix, prefix, dic } = affWord;
const allRules = this.getMatchingRules(affWord.rules);
const { rulesApplied, flags } = allRules
.filter((rule) => !!rule.flags)
.reduce(
(acc, rule) => ({
rulesApplied: [acc.rulesApplied, rule.id].join(' '),
flags: { ...acc.flags, ...rule.flags },
}),
{ rulesApplied: affWord.rulesApplied, flags: affWord.flags }
);
const rules = this.joinRules(allRules.filter((rule) => !rule.flags).map((rule) => rule.id));
const affixRules = allRules.map((rule) => rule.sfx || rule.pfx).filter(isDefined);
const wordWithFlags = { word, flags, rulesApplied, rules: '', base, suffix, prefix, dic };
return [wordWithFlags, ...this.applyAffixesToWord(affixRules, { ...wordWithFlags, rules }, remainingDepth)]
.filter(({ flags }) => !flags.isNeedAffix)
.map((affWord) => adjustCompounding(affWord, compoundMin))
.map((affWord) => logAffWord(affWord, 'applyRulesToWord'));
}
applyAffixesToWord(affixRules: Fx[], affWord: AffWord, remainingDepth: number): AffWord[] {
if (remainingDepth <= 0) {
return [];
}
const combinableRules = affixRules
.filter((rule) => rule.type === 'SFX')
.filter((rule) => rule.combinable === true)
.map(({ id }) => id);
const combinableSfx = this.joinRules(combinableRules);
const r = affixRules
.map((affix) => this.applyAffixToWord(affix, affWord, combinableSfx))
.reduce((a, b) => a.concat(b), [])
.map((affWord) => this.applyRulesToWord(affWord, remainingDepth - 1))
.reduce((a, b) => a.concat(b), []);
return r;
}
applyAffixToWord(affix: Fx, affWord: AffWord, combinableSfx: string): AffWord[] {
const { word } = affWord;
const combineRules = affix.type === 'PFX' && affix.combinable && !!combinableSfx ? combinableSfx : '';
const flags = affWord.flags.isNeedAffix ? removeNeedAffix(affWord.flags) : affWord.flags;
const matchingSubstitutions = [...affix.substitutionSets.values()].filter((sub) => sub.match.test(word));
const partialAffWord = { ...affWord, flags, rules: combineRules };
return matchingSubstitutions
.map((sub) => sub.substitutions)
.reduce((a, b) => a.concat(b), [])
.filter((sub) => sub.remove === '0' || sub.replace.test(word))
.map((sub) => this.substitute(affix, partialAffWord, sub))
.map((affWord) => logAffWord(affWord, 'applyAffixToWord'));
}
substitute(affix: Fx, affWord: AffWord, sub: Substitution): AffWord {
const { word: origWord, rulesApplied, flags, dic } = affWord;
const rules = affWord.rules + (sub.attachRules || '');
const word = origWord.replace(sub.replace, sub.attach);
const stripped = origWord.replace(sub.replace, '');
let p = affWord.prefix.length;
let s = origWord.length - affWord.suffix.length;
if (affix.type === 'SFX') {
s = Math.min(stripped.length, s);
p = Math.min(p, s);
} else {
const d = word.length - origWord.length;
p = Math.max(p, word.length - stripped.length);
s = Math.max(s + d, p);
}
const base = word.slice(p, s);
const prefix = word.slice(0, p);
const suffix = word.slice(s);
return {
word,
rulesApplied: rulesApplied + ' ' + affix.id,
rules,
flags,
base,
suffix,
prefix,
dic,
};
}
getMatchingRules(rules: string): Rule[] {
const { AF = [] } = this.affInfo;
const idx = parseInt(rules, 10);
const rulesToSplit = AF[idx] || rules;
return this.separateRules(rulesToSplit)
.map((key) => this.rules.get(key))
.filter(isDefined);
}
joinRules(rules: string[]): string {
switch (this.affInfo.FLAG) {
case 'long':
return rules.join('');
case 'num':
return rules.join(',');
}
return rules.join('');
}
separateRules(rules: string): string[] {
switch (this.affInfo.FLAG) {
case 'long':
return [...new Set(rules.replace(/(..)/g, '$1//').split('//').slice(0, -1))];
case 'num':
return [...new Set(rules.split(','))];
}
return [...new Set(rules.split(''))];
}
get iConv() {
return this._iConv;
}
get oConv() {
return this._oConv;
}
}
function signature(aff: AffWord) {
const { word, flags } = aff;
const sig = Object.entries(flags)
.filter((e) => !!e[1])
.map((f) => flagToStringMap[f[0]])
.sort()
.join('');
return word + '|' + sig;
}
export function processRules(affInfo: AffInfo): Map<string, Rule> {
const sfxRules: Sequence<Rule> = gs(affInfo.SFX || [])
.map(([, sfx]) => sfx)
.map((sfx) => ({ id: sfx.id, type: 'sfx', sfx }));
const pfxRules: Sequence<Rule> = gs(affInfo.PFX || [])
.map(([, pfx]) => pfx)
.map((pfx) => ({ id: pfx.id, type: 'pfx', pfx }));
const flagRules: Sequence<Rule> = GS.sequenceFromObject(affInfo as AffTransformFlags)
.filter(([key, value]) => !!affFlag[key] && !!value)
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
.map(([key, value]) => ({ id: value!, type: 'flag', flags: affFlag[key] }));
const rules = sfxRules
.concat(pfxRules)
.concat(flagRules)
.reduce<Map<string, Rule>>((acc, rule) => {
acc.set(rule.id, rule);
return acc;
}, new Map<string, Rule>());
return rules;
}
const affFlag: Mapping<AffTransformFlags, AffWordFlags> = {
KEEPCASE: { isKeepCase: true },
WARN: { isWarning: true },
FORCEUCASE: { isForceUCase: true },
FORBIDDENWORD: { isForbiddenWord: true },
NOSUGGEST: { isNoSuggest: true },
NEEDAFFIX: { isNeedAffix: true },
COMPOUNDBEGIN: { canBeCompoundBegin: true },
COMPOUNDMIDDLE: { canBeCompoundMiddle: true },
COMPOUNDEND: { canBeCompoundEnd: true },
COMPOUNDFLAG: { isCompoundPermitted: true },
COMPOUNDPERMITFLAG: { isCompoundPermitted: true },
COMPOUNDFORBIDFLAG: { isCompoundForbidden: true },
ONLYINCOMPOUND: { isOnlyAllowedInCompound: true },
};
const _FlagToStringMap: Record<keyof AffWordFlags, string> = {
isCompoundPermitted: 'C',
canBeCompoundBegin: 'B',
canBeCompoundMiddle: 'M',
canBeCompoundEnd: 'E',
isOnlyAllowedInCompound: 'O',
isWarning: 'W',
isKeepCase: 'K',
isForceUCase: 'U',
isForbiddenWord: 'F',
isNoSuggest: 'N',
isNeedAffix: 'A',
isCompoundForbidden: '-',
};
const _FlagToLongStringMap: Record<keyof AffWordFlags, string> = {
isCompoundPermitted: 'CompoundPermitted',
canBeCompoundBegin: 'CompoundBegin',
canBeCompoundMiddle: 'CompoundMiddle',
canBeCompoundEnd: 'CompoundEnd',
isOnlyAllowedInCompound: 'OnlyInCompound',
isWarning: 'Warning',
isKeepCase: 'KeepCase',
isForceUCase: 'ForceUpperCase',
isForbiddenWord: 'Forbidden',
isNoSuggest: 'NoSuggest',
isNeedAffix: 'NeedAffix',
isCompoundForbidden: 'CompoundForbidden',
};
const flagToStringMap: Record<string, string | undefined> = _FlagToStringMap;
const flagToLongStringMap: Record<string, string | undefined> = _FlagToLongStringMap;
export function logAffWord(affWord: AffWord, message: string) {
/* istanbul ignore if */
if (log) {
const dump = util.inspect(affWord, { showHidden: false, depth: 5, colors: true });
console.log(`${message}: ${dump}`);
}
return affWord;
}
/* istanbul ignore next */
export function affWordToColoredString(affWord: AffWord) {
return util
.inspect({ ...affWord, flags: flagsToString(affWord.flags) }, { showHidden: false, depth: 5, colors: true })
.replace(/(\s|\n|\r)+/g, ' ');
}
/* istanbul ignore next */
export function flagsToString(flags: AffWordFlags) {
return [...Object.entries(flags)]
.filter(([, v]) => !!v)
.map(([k]) => flagToLongStringMap[k])
.sort()
.join(':');
}
export function asAffWord(word: string, rules = '', flags: AffWordFlags = {}): AffWord {
return {
word,
base: word,
prefix: '',
suffix: '',
rulesApplied: '',
rules,
flags,
dic: rules ? word + '/' + rules : word,
};
}
export function compareAff(a: AffWord, b: AffWord) {
if (a.word !== b.word) {
return a.word < b.word ? -1 : 1;
}
const sigA = signature(a);
const sigB = signature(b);
return sigA < sigB ? -1 : sigA > sigB ? 1 : 0;
}
/**
* Returns a filter function that will filter adjacent AffWords
* It compares the word and the flags.
*/
export function filterAff() {
return filterOrderedList<AffWord>((a, b) => a.word !== b.word || signature(a) !== signature(b));
}
export const debug = {
signature,
};
function removeNeedAffix(flags: AffWordFlags): AffWordFlags {
const newFlags: AffWordFlags = { ...flags };
delete newFlags.isNeedAffix;
return newFlags;
}
function adjustCompounding(affWord: AffWord, minLength: number): AffWord {
if (!affWord.flags.isCompoundPermitted || affWord.word.length >= minLength) {
return affWord;
}
const { isCompoundPermitted: _, ...flags } = affWord.flags;
affWord.flags = flags;
return affWord;
} | the_stack |
import { Canvas, PixelFormat, Texture, TextureAccess } from "../../mod.ts";
import { FPS } from "../utils.ts";
class Boids {
particleCount: number;
particlesPerGroup: number;
computePipeline!: GPUComputePipeline;
particleBindGroups: GPUBindGroup[] = [];
renderPipeline!: GPURenderPipeline;
particleBuffers: GPUBuffer[] = [];
verticesBuffer!: GPUBuffer;
frameNum = 0;
dimensions = {
width: 800,
height: 800,
};
screenDimensions = {
width: 800,
height: 800,
};
texture: GPUTexture;
outputBuffer: GPUBuffer;
canvas: Canvas;
sdl2texture: Texture;
constructor(options: {
particleCount: number;
particlesPerGroup: number;
}, public device: GPUDevice) {
this.particleCount = options.particleCount;
this.particlesPerGroup = options.particlesPerGroup;
this.canvas = new Canvas({
title: "Hello, Deno!",
...this.dimensions,
centered: false,
fullscreen: false,
hidden: false,
resizable: true,
minimized: false,
maximized: false,
flags: null,
});
this.sdl2texture = this.canvas.createTexture(
PixelFormat.ABGR8888,
TextureAccess.Streaming,
this.dimensions.width,
this.dimensions.height,
);
this.texture = this.device.createTexture({
label: "Capture",
size: this.dimensions,
format: "rgba8unorm-srgb",
usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
});
const { padded, unpadded } = getRowPadding(this.dimensions.width);
this.outputBuffer = this.device.createBuffer({
label: "Capture",
size: padded * this.dimensions.height,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
}
init() {
const computeShader = this.device.createShaderModule({
code: Deno.readTextFileSync(new URL("./compute.wgsl", import.meta.url)),
});
const drawShader = this.device.createShaderModule({
code: Deno.readTextFileSync(new URL("./shader.wgsl", import.meta.url)),
});
const simParamData = new Float32Array([
0.1, // deltaT
0.2, // rule1Distance
0.2, // rule2Distance
0.2, // rule3Distance
0.7, // rule1Scale
0.3, // rule2Scale
0.5, // rule3Scale
]);
const simParamBuffer = createBufferInit(this.device, {
label: "Simulation Parameter Buffer",
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
contents: simParamData.buffer,
});
const computeBindGroupLayout = this.device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: {
minBindingSize: simParamData.length * 4,
},
},
{
binding: 1,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: "read-only-storage",
minBindingSize: this.particleCount * 16,
},
},
{
binding: 2,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: "storage",
minBindingSize: this.particleCount * 16,
},
},
],
});
const computePipelineLayout = this.device.createPipelineLayout({
label: "compute",
bindGroupLayouts: [computeBindGroupLayout],
});
const renderPipelineLayout = this.device.createPipelineLayout({
label: "render",
bindGroupLayouts: [],
});
this.renderPipeline = this.device.createRenderPipeline({
layout: renderPipelineLayout,
vertex: {
module: drawShader,
entryPoint: "main",
buffers: [
{
arrayStride: 4 * 4,
stepMode: "instance",
attributes: [
{
format: "float32x2",
offset: 0,
shaderLocation: 0,
},
{
format: "float32x2",
offset: 8,
shaderLocation: 1,
},
],
},
{
arrayStride: 2 * 4,
attributes: [
{
format: "float32x2",
offset: 0,
shaderLocation: 2,
},
],
},
],
},
fragment: {
module: drawShader,
entryPoint: "main",
targets: [
{
format: "rgba8unorm-srgb",
},
],
},
});
this.computePipeline = this.device.createComputePipeline({
label: "Compute pipeline",
layout: computePipelineLayout,
compute: {
module: computeShader,
entryPoint: "main",
},
});
const vertexBufferData = new Float32Array([
-0.01,
-0.02,
0.01,
-0.02,
0.00,
0.02,
]);
this.verticesBuffer = createBufferInit(this.device, {
label: "Vertex Buffer",
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
contents: vertexBufferData.buffer,
});
const initialParticleData = new Float32Array(4 * this.particleCount);
for (let i = 0; i < initialParticleData.length; i += 4) {
initialParticleData[i] = 2.0 * (Math.random() - 0.5); // posx
initialParticleData[i + 1] = 2.0 * (Math.random() - 0.5); // posy
initialParticleData[i + 2] = 2.0 * (Math.random() - 0.5) * 0.1; // velx
initialParticleData[i + 3] = 2.0 * (Math.random() - 0.5) * 0.1;
}
for (let i = 0; i < 2; i++) {
this.particleBuffers.push(createBufferInit(this.device, {
label: "Particle Buffer " + i,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.STORAGE |
GPUBufferUsage.COPY_DST,
contents: initialParticleData.buffer,
}));
}
for (let i = 0; i < 2; i++) {
this.particleBindGroups.push(this.device.createBindGroup({
layout: computeBindGroupLayout,
entries: [
{
binding: 0,
resource: {
buffer: simParamBuffer,
},
},
{
binding: 1,
resource: {
buffer: this.particleBuffers[i],
},
},
{
binding: 2,
resource: {
buffer: this.particleBuffers[(i + 1) % 2],
},
},
],
}));
}
}
render(encoder: GPUCommandEncoder, view: GPUTextureView) {
encoder.pushDebugGroup("compute boid movement");
const computePass = encoder.beginComputePass();
computePass.setPipeline(this.computePipeline);
computePass.setBindGroup(0, this.particleBindGroups[this.frameNum % 2]);
computePass.dispatch(
Math.ceil(this.particleCount / this.particlesPerGroup),
);
computePass.endPass();
encoder.copyBufferToBuffer(
this.particleBuffers[0],
0,
this.particleBuffers[1],
0,
16,
);
encoder.popDebugGroup();
encoder.pushDebugGroup("render boids");
const renderPass = encoder.beginRenderPass({
colorAttachments: [
{
view: view,
storeOp: "store",
loadValue: [0, 0, 0, 1],
},
],
});
renderPass.setPipeline(this.renderPipeline);
renderPass.setVertexBuffer(
0,
this.particleBuffers[(this.frameNum + 1) % 2],
);
renderPass.setVertexBuffer(1, this.verticesBuffer);
renderPass.draw(3, this.particleCount);
renderPass.endPass();
encoder.popDebugGroup();
this.frameNum += 1;
}
async update() {
const encoder = this.device.createCommandEncoder();
const { padded, unpadded } = getRowPadding(this.dimensions.width);
this.render(encoder, this.texture.createView());
// const outputBuffer = this.device.createBuffer({
// label: "Capture",
// size: padded * this.dimensions.height,
// usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
// });
encoder.copyTextureToBuffer(
{ texture: this.texture },
{
buffer: this.outputBuffer,
bytesPerRow: padded,
rowsPerImage: 0,
},
this.dimensions,
);
this.device.queue.submit([encoder.finish()]);
await this.outputBuffer.mapAsync(1);
const buf = new Uint8Array(this.outputBuffer.getMappedRange());
const buffer = new Uint8Array(unpadded * this.dimensions.height);
for (let i = 0; i < this.dimensions.height; i++) {
const slice = buf
.slice(i * padded, (i + 1) * padded)
.slice(0, unpadded);
buffer.set(slice, i * unpadded);
}
this.sdl2texture.update(buffer, this.dimensions.width * 4);
const rect = { x: 0, y: 0, ...this.dimensions };
const screen = { x: 0, y: 0, ...this.screenDimensions };
this.canvas.copy(this.sdl2texture, rect, screen);
this.canvas.present();
this.outputBuffer.unmap();
}
}
async function getDevice(features: GPUFeatureName[] = []): Promise<GPUDevice> {
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter?.requestDevice({
requiredFeatures: features,
});
if (!device) {
throw new Error("no suitable adapter found");
}
return device;
}
export function createBufferInit(
device: GPUDevice,
descriptor: BufferInit,
): GPUBuffer {
const contents = new Uint8Array(descriptor.contents);
const unpaddedSize = contents.byteLength;
const padding = 4 - unpaddedSize % 4;
const paddedSize = padding + unpaddedSize;
const buffer = device.createBuffer({
label: descriptor.label,
usage: descriptor.usage,
mappedAtCreation: true,
size: paddedSize,
});
const data = new Uint8Array(buffer.getMappedRange());
data.set(contents);
buffer.unmap();
return buffer;
}
interface BufferInit {
label?: string;
usage: number;
contents: ArrayBuffer;
}
function getRowPadding(width: number) {
const bytesPerPixel = 4;
const unpaddedBytesPerRow = width * bytesPerPixel;
const align = 256;
const paddedBytesPerRowPadding = (align - unpaddedBytesPerRow % align) %
align;
const paddedBytesPerRow = unpaddedBytesPerRow + paddedBytesPerRowPadding;
return {
unpadded: unpaddedBytesPerRow,
padded: paddedBytesPerRow,
};
}
const boids = new Boids({
particleCount: 100,
particlesPerGroup: 64,
}, await getDevice());
boids.init();
const tick = FPS(100);
event_loop:
for await (const event of boids.canvas) {
switch (event.type) {
case "resized": {
const { width, height } = event;
boids.canvas.copy(boids.sdl2texture, { x: 0, y: 0, width, height }, {
x: 0,
y: 0,
width,
height,
});
boids.screenDimensions = { width, height };
boids.canvas.present();
break;
}
case "draw": {
await boids.update();
tick();
break;
}
case "quit":
break event_loop;
case "key_down":
break event_loop;
default:
break;
}
} | the_stack |
import browserSync from "browser-sync";
import chalk from "chalk";
import gfs from "graceful-fs";
import http from "http";
import path from "path";
import rpn from "request-promise-native";
import { ClientlibTree } from "./clientlib-tree";
import * as messages from "./messages";
import { StyleTrees } from "./style-trees";
export interface IWrapperConfig {
bsOptions: browserSync.Options;
jcrContentRoots: string[];
proxyPort: number;
servers: string[];
dumpLibsPath?: string;
}
interface Instance {
clientlibTree: ClientlibTree;
name: string;
online: boolean;
port: number;
server: string;
aemSettings: IAemSettings;
}
interface IAemSettings {
// mode: string;
bundles: IBundles;
configs: IConfigs;
}
// Bundles
interface IBundles {
tracer?: IBundleData;
}
interface IBundleData {
id: number;
name: string;
fragment: boolean;
stateRaw: number;
state: string;
version: string;
symbolicName: string;
category: string;
props: IBundleProp[];
}
interface IBundleProp {
key: string;
value: any;
}
// Configs
interface IConfigs {
tracer?: ITracerSettings;
}
interface ITracerSettings {
enabled: boolean;
servletEnabled: boolean;
recordingCacheSizeInMB: number;
recordingCacheDurationInSecs: number;
recordingCompressionEnabled: boolean;
gzipResponse: boolean;
}
const instances: { [key: string]: Instance } = {};
let styleTrees: StyleTrees;
let config: IWrapperConfig;
// Sling Tracer logic
// TODO move to own file?
interface ITracerProfile {
logger: string;
level?: string;
caller?: boolean | number;
callerExcludeFilter?: string[];
postProcess?(message: string): string;
getJcrRef?(
message: string,
instance: Instance
): messages.ISourceFileReference | undefined;
fixJcrRef?(
sourceRef: messages.ISourceFileReference,
instance: Instance
): Promise<messages.ISourceFileReference>;
}
interface ITracerConfig {
pattern: RegExp;
profiles: ITracerProfile[];
}
/**
* Try to update the ref with the individual file info based on uber line nr from combined client lib
* @param ref Source file reference from the error message with line nr based on combined javascript files
* @param instance Server instance with the javascript client lib tree we use to find individual file
* @returns Promise with the ref itself with updated info, but since it is an object, it is the same reference as the provided parameter
*/
function fixJsPath(
ref: messages.ISourceFileReference,
instance: Instance
): Promise<messages.ISourceFileReference> {
if (ref.jcrPath && typeof ref.line === "number") {
return instance.clientlibTree.jsTrees
.getMappedFile(ref.jcrPath, ref.line)
.then(jsFileMapped => {
// Something was mapped, so update ref with data
if (jsFileMapped) {
ref.jcrPath = jsFileMapped.path;
ref.line = jsFileMapped.line; // Compensate for extra lines from files before this
messages.setFilePath(ref, config.jcrContentRoots);
}
return ref;
});
} else {
return Promise.resolve(ref);
}
}
// Sling Tracer profiles
// TODO do something about a lot of duplicate errors for YUI processor
// tslint:disable:object-literal-sort-keys
const yuiProfile: ITracerProfile = {
level: "error",
logger: "com.adobe.granite.ui.clientlibs.impl.YUIScriptProcessor",
getJcrRef: message => {
// Only check for lines and columns, since no other info in message
const sourceRef = messages.getRef(
message,
/(\d+):(\d+):/,
config.jcrContentRoots,
{
line: 1,
column: 2,
jcrPath: -1,
filePath: -1
}
);
return sourceRef;
},
fixJcrRef: (sourceRef, instance) => {
// Try to get the individual js file name, based on uber line nr
// Make sure all data is loaded into JsTrees
return fixJsPath(sourceRef, instance);
},
postProcess: message => {
// YUI adds a new line and it's own ERROR prefix for each line: strip it
return message.replace(/^\n\[ERROR\] /, "");
}
};
const jscompProfile: ITracerProfile = {
level: "error",
logger: "com.google.javascript.jscomp",
getJcrRef: (message, instance) => {
const sourceRef = messages.getRef(
message,
/^([^:[\]*'"|\s]+):(\d+):/,
config.jcrContentRoots,
{
jcrPath: 1,
line: 2,
column: -1,
filePath: -1
}
);
if (sourceRef) {
// Try to get column from line with ^ indicator
// Only works when indented with spaces, since we don't know the tab width
const match = /^( *\^)$/gm.exec(message);
if (match) {
sourceRef.column = match[1].length;
}
}
return sourceRef;
},
fixJcrRef: (sourceRef, instance) => {
// Try to get the individual js file name, based on uber line nr
// Make sure all data is loaded into JsTrees
return fixJsPath(sourceRef, instance);
}
};
const gccProfile: ITracerProfile = {
level: "error",
logger:
"com.adobe.granite.ui.clientlibs.processor.gcc.impl.GCCScriptProcessor"
};
const lessProfile: ITracerProfile = {
level: "error",
logger: "com.adobe.granite.ui.clientlibs.compiler.less.impl.LessCompilerImpl",
getJcrRef: message => {
// illegal jcr chars (but added '/' since we want complete path):
// https://helpx.adobe.com/experience-manager/6-3/sites/developing/using/reference-materials/javadoc/com/day/cq/commons/jcr/JcrUtil.html
const sourceRef = messages.getRef(
message,
/([^:[\]*'"|\s]+) on line (\d+), column (\d+)/,
config.jcrContentRoots
);
return sourceRef;
}
};
const htmlLibProfile: ITracerProfile = {
level: "error",
logger: "com.adobe.granite.ui.clientlibs.impl.HtmlLibraryManagerImpl",
getJcrRef: message => {
// Only check for js for now
const sourceRef = messages.getRef(
message,
/Error during assembly of (\/[^:[\]*'"|\s]+\.js)/,
config.jcrContentRoots,
{
jcrPath: 1,
filePath: -1,
line: -1,
column: -1
}
);
return sourceRef;
}
};
const cacheLibProfile: ITracerProfile = {
level: "error",
logger: "com.adobe.granite.ui.clientlibs.impl.LibraryCacheImpl"
};
const acsProfile: ITracerProfile = {
level: "error",
logger:
"com.adobe.acs.commons.rewriter.impl.VersionedClientlibsTransformerFactory"
};
const slingProcessorProfile: ITracerProfile = {
level: "error",
logger: "org.apache.sling.engine.impl.SlingRequestProcessorImpl"
};
const slingSightlyProfile: ITracerProfile = {
level: "error",
logger: "org.apache.sling.scripting.sightly"
};
// tslint:enable:object-literal-sort-keys
// Used for querying
const profiles = [
yuiProfile,
jscompProfile,
gccProfile,
lessProfile,
htmlLibProfile,
cacheLibProfile,
acsProfile,
slingProcessorProfile,
slingSightlyProfile
];
// Tracer configs
// TODO maybe just add all tracer configs to all requests?
const tracerConfigs: ITracerConfig[] = [
// Page, most logging is present in call to page itself (especially for gcc)
{
pattern: /\.(html|jsp)(\?.*|$)/,
profiles: [
yuiProfile,
jscompProfile,
gccProfile,
lessProfile,
htmlLibProfile,
cacheLibProfile,
acsProfile,
slingProcessorProfile,
slingSightlyProfile
]
},
// Styling, for individual calls to css in case of injection
{
pattern: /\.css(\?.*|$)/,
profiles: [lessProfile, htmlLibProfile, cacheLibProfile]
},
// Javascript, in case of requesting individual js files
{
pattern: /\.js(\?.*|$)/,
profiles: [
yuiProfile,
jscompProfile,
gccProfile,
htmlLibProfile,
cacheLibProfile
]
},
// Json, in case of api requests
// What is a good generic pattern?
{
pattern: /\.json(\?.*|$)/,
profiles: [slingProcessorProfile]
}
];
function setTracerHeaders(
proxyReq: http.ClientRequest,
req: http.IncomingMessage,
configs: ITracerConfig[]
) {
const url = req.url;
configs.forEach(tracerConfig => {
if (url && tracerConfig.pattern.test(url)) {
const configStrings = tracerConfig.profiles.map(
({ logger, level, caller, callerExcludeFilter }) => {
const fragments = [logger];
if (level) {
fragments.push(`level=${level}`);
}
if (caller === true || typeof caller === "number") {
fragments.push(`caller=${caller}`);
}
if (callerExcludeFilter && callerExcludeFilter.length) {
fragments.push(
`caller-exclude-filter="${callerExcludeFilter.join("|")}"`
);
}
return fragments.join(";");
}
);
proxyReq.setHeader("Sling-Tracer-Record", "true");
proxyReq.setHeader("Sling-Tracer-Config", configStrings.join(","));
}
});
}
function processTracer(
proxyRes: http.IncomingMessage,
url: string | undefined,
instance: Instance
) {
const header = proxyRes.headers["Sling-Tracer-Request-Id".toLowerCase()];
const slingTracerRequestId = Array.isArray(header)
? header.length
? header[0]
: ""
: header;
if (slingTracerRequestId) {
// Use timeout, since json may not be ready yet
// TODO is this true?
setTimeout(() => {
const tracerUrl =
instance.server +
"/system/console/tracer/" +
slingTracerRequestId +
".json";
rpn({
json: true,
uri: tracerUrl
}).then((data: any) => {
if (data && !data.error) {
const trace: ITracer = data;
generateReport(instance, url, slingTracerRequestId, trace).then(
report => {
report.map(line => console.log(line));
}
);
}
});
}, 100);
}
}
// Used for filtering duplicates in .filter
function onlyUnique<T>(value: T, index: number, self: T[]): boolean {
return self.indexOf(value) === index;
}
interface IReportMessage {
traceLog?: ILog;
postMessage?: string;
profile?: ITracerProfile;
sourceRef?: messages.ISourceFileReference;
}
function generateReport(
instance: Instance,
url: string | undefined,
slingTracerRequestId: string,
trace: ITracer
): Promise<string[]> {
// tslint:disable:object-literal-sort-keys
const levelColorMap: {
[key: string]: (message: string) => string;
} = {
error: chalk.red,
warn: chalk.yellow,
info: chalk.white,
debug: chalk.reset,
trace: chalk.grey
};
// tslint:enable:object-literal-sort-keys
// Used for the formatted messages from trace.logs[]
const report: string[] = [];
const reportMessages: IReportMessage[] = [];
// Magic for JS
const onlyLines: IReportMessage[] = [];
const onlyPaths: IReportMessage[] = [];
trace.logs.map(traceLog => {
const className = traceLog.logger.substr(
traceLog.logger.lastIndexOf(".") + 1
);
const coloredLevel = levelColorMap[traceLog.level.toLowerCase()](
traceLog.level
);
const message: IReportMessage = { traceLog };
// Check profile specific processing of message
const profile = profiles.find(p => traceLog.logger === p.logger);
if (profile) {
message.profile = profile;
// Try to translate JCR references back to local files
if (typeof profile.getJcrRef === "function") {
message.sourceRef = profile.getJcrRef(traceLog.message, instance);
// reportMessage
if (message.sourceRef) {
const hasPath =
message.sourceRef.jcrPath ||
message.sourceRef.absoluteFilePath ||
message.sourceRef.relativeFilePath;
const hasLine = typeof message.sourceRef.line === "number";
// Add to list
if (hasPath && hasLine) {
// Complete, so add direct to sourceFileRefs
reportMessages.push(message);
} else {
// Something is missing, try to fix
// Mainly for YUI
if (!hasPath && hasLine) {
// Only lines, so check if there are still onlyPaths present and clean up
if (onlyPaths.length) {
// First cleanup since last run
processOnlies();
}
onlyLines.push(message);
} else if (hasPath && !hasLine) {
onlyPaths.push(message);
}
}
}
}
// If function available, clean up log message
if (typeof profile.postProcess === "function") {
message.postMessage = profile.postProcess(traceLog.message);
}
}
report.push(
chalk`[${coloredLevel}] {cyan ${className}}: ${message.postMessage ||
traceLog.message}`
);
});
if (onlyPaths.length) {
processOnlies();
}
function processOnlies() {
// onlyPaths deduplicate: pick first (since probably
// related to onlyLines that came before it)
const uniquePathMessages: IReportMessage[] = [];
onlyPaths.forEach(message => {
const onlyPath = message.sourceRef;
if (
onlyPath &&
onlyPath.jcrPath &&
!uniquePathMessages.some(
up =>
typeof up.sourceRef !== "undefined" &&
up.sourceRef.jcrPath === onlyPath.jcrPath
)
) {
uniquePathMessages.push(message);
}
});
if (uniquePathMessages.length) {
uniquePathMessages.forEach((uniquePath, upIndex) => {
const pathRef = uniquePath.sourceRef;
if (upIndex === 0 && onlyLines.length && pathRef) {
// For first uniquePath try to apply all onlyLines if any
onlyLines.forEach((message, index) => {
const lineRef = message.sourceRef;
if (lineRef) {
if (
onlyLines.length === index + 1 &&
lineRef &&
lineRef.line === 1 &&
lineRef.column === 0
) {
// Last message has 1:0: which means summary and not relevant so skip
} else {
lineRef.jcrPath = pathRef.jcrPath;
// Store in final list
reportMessages.push(message);
}
}
});
} else {
// Just push all remaining paths
reportMessages.push(uniquePath);
}
});
}
// Done, empty onlyLines and onlyPaths before filling them again
onlyLines.splice(0, onlyLines.length);
onlyPaths.splice(0, onlyPaths.length);
}
// Process errors in request progress log (descriptive sightly/jsp errors are only in here)
// TODO work with some sort of error message list anyway (so no printing in here)
// so we can also print the relative paths with their message instead of at the bottom
const requestProgressErrorLogsRaw: string[] = [];
const requestProgressErrorLogs = !trace.requestProgressLogs
? []
: (trace.requestProgressLogs
.map(message => {
const match = /\d+ LOG SCRIPT ERROR: (.*)/.exec(message);
if (!match) {
return;
}
const postMessage = match[1];
// Test if not a ScriptEvaluationException with empty message
// (thrown several times in the upstream stack trace)
if (/ScriptEvaluationException:$/.test(postMessage)) {
return;
}
// Check if not already at the end of another message
const matchingMessages = requestProgressErrorLogsRaw.filter(
logMessage => postMessage.endsWith(logMessage)
);
// TODO add some check for empty or short postMessages (since they 'always' match endsWith)?
// Test if message was not yet in requestProgressErrorLogsRaw
if (matchingMessages.length === 0) {
requestProgressErrorLogsRaw.push(postMessage);
// Try to find jcr paths in message
let ref: messages.ISourceFileReference | undefined;
// NOTE, when using global patterns, make sure to reset the regex after test call
const progressLogPatterns = [
/([^:[\]*'"|\s]+) at line number (\d+) at column number (\d+)/, // htl
/([^:[\]*'"|\s]+)\((\d+),(\d+)\)/ // jsp
];
progressLogPatterns.some(pattern => {
const patternMatches = pattern.test(message);
if (patternMatches) {
ref = messages.getRef(message, pattern, config.jcrContentRoots);
}
// Stop looping when pattern is found
return patternMatches;
});
// If local ref was generated, add to list
if (ref) {
reportMessages.push({
postMessage,
sourceRef: ref
});
}
// Return message to map
return chalk`[{red ERROR}] {cyan Sling Request Progress Tracker}: ${postMessage}`;
}
})
.filter(message => typeof message === "string") as string[]);
// All sourceRefs are present, last fix round
const promises: Promise<messages.ISourceFileReference>[] = [];
for (const { sourceRef, profile } of reportMessages) {
if (profile && sourceRef) {
if (typeof profile.fixJcrRef === "function") {
promises.push(profile.fixJcrRef(sourceRef, instance));
}
}
}
return Promise.all(promises).then(fixedRefs => {
// We're not interested in fixedRefs, only that they have been fixed
const uniqueLocalPaths = reportMessages
.map(ref => ref.sourceRef && messages.formatMessage(ref.sourceRef))
.filter((filePath): filePath is string => typeof filePath === "string")
.filter(onlyUnique);
// Combine logs, requestProgressLogs and local paths into final report
const finalReport = report.concat(
requestProgressErrorLogs,
uniqueLocalPaths
);
// If there is something to report, add header with trace id
if (finalReport.length > 0) {
finalReport.unshift(
chalk`[{blue ${instance.name}}] Tracer output for [{yellow ${url ||
"[url missing]"}}] (${slingTracerRequestId})`
);
}
return finalReport;
});
}
interface IOsgiConfig<T> {
pid: string;
title: string;
description: string;
properties: T;
bundleLocation?: string;
bundle_location?: string;
service_location?: string;
}
interface IOsgiProperty<T> {
name: string;
optional: boolean;
is_set: boolean;
type: number;
value: T | string; // If is_set is false, value is always a string it seems
description: string;
}
interface IOsgiPropertiesTracer {
// tracerSets: IOsgiProperty; // Multi value
enabled: IOsgiProperty<boolean>;
servletEnabled: IOsgiProperty<boolean>;
recordingCacheSizeInMB: IOsgiProperty<number>;
recordingCacheDurationInSecs: IOsgiProperty<number>;
recordingCompressionEnabled: IOsgiProperty<boolean>;
gzipResponse: IOsgiProperty<boolean>;
}
function setSlingTracerBundleInfo(instance: Instance): Promise<Instance> {
const symbolicName = "org.apache.sling.tracer";
const url = instance.server + `/system/console/bundles/${symbolicName}.json`;
return rpn({
json: true,
uri: url
}).then((data: any) => {
if (data && data.data && data.data.length > 0) {
const bundleData = data.data[0];
if (
Object.keys(bundleData).length > 0 &&
bundleData.symbolicName === symbolicName
) {
instance.aemSettings.bundles.tracer = bundleData;
}
}
return instance;
});
}
function setSlingTracerSettings(instance: Instance): Promise<Instance> {
const buster = `${Date.now()}`.slice(-3);
// TODO use constant for this path, since also used in message
const url =
instance.server +
`/system/console/configMgr/org.apache.sling.tracer.internal.LogTracer?post=true&ts=${buster}`;
return rpn({
json: true,
uri: url
}).then((data: any) => {
if (data && data.properties && Object.keys(data.properties).length > 0) {
const { properties }: IOsgiConfig<IOsgiPropertiesTracer> = data;
// Convert types any way, since default values are always send as strings it seems :sob:
instance.aemSettings.configs.tracer = {
enabled: convert2Boolean(properties.enabled.value),
gzipResponse: convert2Boolean(properties.gzipResponse.value),
recordingCacheDurationInSecs: convert2Int(
properties.recordingCacheDurationInSecs.value
),
recordingCacheSizeInMB: convert2Int(
properties.recordingCacheSizeInMB.value
),
recordingCompressionEnabled: convert2Boolean(
properties.recordingCompressionEnabled.value
),
servletEnabled: convert2Boolean(properties.servletEnabled.value)
};
} else {
// Something went wrong, so don't store these settings, but continue for next settings
}
return instance;
});
}
function convert2Boolean(value: boolean | string): boolean {
return typeof value === "string" ? value === "true" : value;
}
function convert2Int(value: number | string): number {
return typeof value === "string" ? parseInt(value, 10) : value;
}
export function create(args: IWrapperConfig): Promise<void> {
// Documentation: https://www.browsersync.io/docs/options
const bsOptions: browserSync.Options = {
notify: false,
open: false
};
// Assign extra options to bs
Object.assign(bsOptions, args.bsOptions);
config = args;
config.jcrContentRoots = config.jcrContentRoots || [
"ui.apps/src/main/content/jcr_root/"
];
// Generate instances
args.servers.forEach((server, index) => {
// host as returned by aemsync onPushEnd
const host = server.substring(server.indexOf("@") + 1);
const name = host;
// TODO check if server is online? Or poll in between and
const instance: Instance = {
aemSettings: {
bundles: {},
configs: {}
},
clientlibTree: new ClientlibTree({ name, server }),
name,
online: true,
port: args.proxyPort + index * 2, // Claim numbers for proxy and ui
server
};
instances[host] = instance;
});
const hosts = Object.keys(instances);
// Create promises to add instance state
// TODO handle unresponsive server(s)
const swInstanceState = Date.now();
const promisesState: Promise<any>[] = [];
hosts.forEach(host => {
const instance = instances[host];
promisesState.push(
setSlingTracerBundleInfo(instance)
.then(() => {
const tracerBundle = instance.aemSettings.bundles.tracer;
// 0.0.2 is the only version that doesn't support the tracers with the servlet
// But it can be replaced with 1.0.2 on all AEM 6.0+ instances
if (tracerBundle && tracerBundle.version !== "0.0.2") {
// Tracer present and valid, check its configuration
return setSlingTracerSettings(instance).then(() => {
if (instance.aemSettings.configs.tracer) {
const tracerEnabled =
instance.aemSettings.configs.tracer.enabled &&
instance.aemSettings.configs.tracer.servletEnabled;
if (!tracerEnabled) {
// TODO move path to constant for reuse in call getting json
console.log(
chalk`[{blue ${instance.name}}] {cyan Apache Sling Log Tracer is not enabled, so errors from compiling and minifying Less and Javascript by AEM cannot be shown. To enable it, go to [{yellow ${instance.server}/system/console/configMgr/org.apache.sling.tracer.internal.LogTracer}] and turn on both 'Enabled' and 'Recording Servlet Enabled'. No restart of aemfed needed}.`
);
}
} else {
console.log(
chalk`[{blue ${instance.name}}] {cyan Apache Sling Log Tracer config was not found}.`
);
}
return instance;
});
} else {
// No valid tracer, show message about upgrade
const reason = tracerBundle
? `too old (version ${tracerBundle.version})`
: `not installed`;
console.error(
chalk`[{blue ${instance.name}}] {cyan Apache Sling Log Tracer bundle is ${reason}. At least version 1.0.0 is needed for aemfed to intercept AEM error messages. AEM 6.2 and before can install and run 1.0.2 or newer, see the 'Updating Sling Log Tracer' section in the README for instructions}.`
);
return instance;
}
})
.catch(err => {
console.error(
chalk`[{blue ${instance.name}}] [{red ERROR}] Something went wrong:`,
err
);
})
);
});
return Promise.all(promisesState).then(() => {
// Done with state
console.log(
"Get state for all instances: " + (Date.now() - swInstanceState) + " ms"
);
console.log("");
// Setup clientlib stuff
const swClientlibs = Date.now();
const promisesClientlibs: Promise<any>[] = [];
hosts.forEach(host => {
const instance = instances[host];
promisesClientlibs.push(instance.clientlibTree.init());
});
styleTrees = new StyleTrees(config.jcrContentRoots);
promisesClientlibs.push(styleTrees.init());
return Promise.all(promisesClientlibs)
.then(() => {
// console.log(`Init clientlibs finished`);
console.log(
"Build style and clientlib trees: " +
(Date.now() - swClientlibs) +
" ms"
);
console.log("---------------------------------------");
// Chain creation promises
let promise = Promise.resolve();
hosts.forEach(host => {
const instance = instances[host];
// Create bs instance and add to promise chain to make it serial
promise = promise.then(() => {
createBsInstancePromise(instance, bsOptions);
});
});
return promise;
})
.catch(reason => {
console.error(`Init rejected: ${reason}`);
});
});
}
interface ITracer {
method: string;
time: number;
timestamp: number;
requestProgressLogs?: string[]; // Optional, missing in some minimal requests
queries: IQuery[];
logs: ILog[];
loggerNames: string[];
}
interface ILog {
timestamp: number;
level: string;
logger: string;
message: string;
params: string[];
}
interface IQuery {
query: string;
plan: string;
caller: string;
}
function createBsInstancePromise(
instance: Instance,
bsOptions: browserSync.Options
): Promise<void> {
return new Promise((resolve, reject) => {
const bs = browserSync.create(instance.name);
// Set server specific settings
// TODO clone options first?
bsOptions.proxy = {
proxyReq: [
(proxyReq, req, res, proxyOptions) => {
setTracerHeaders(proxyReq, req, tracerConfigs);
}
],
proxyRes: [
(proxyRes, req, res) => {
processTracer(proxyRes, req.url, instance);
}
],
target: instance.server
};
bsOptions.port = instance.port;
bsOptions.ui = {
port: instance.port + 1
};
bs.init(bsOptions, (err, data) => {
if (err) {
reject(err);
} else {
resolve();
}
// Callback:
// console.log(data.options.get("urls").get("ui"));
// console.log(data.options.get("urls").get("ui-external"));
// console.log(bs.getOption("urls"));
});
});
}
export function reload(host: string, inputList: string[]): void {
// TODO since we can hit this at the same time when working with multiple servers
// make sure we don't get into any concurrency trouble
const instance = instances[host];
const bs = browserSync.get(instance.name);
// console.log("bs: ", bs);
let css = false;
let js = false;
let html = false;
let other = false;
const cssPaths: string[] = [];
const csstxtPaths: string[] = [];
const jsPaths: string[] = [];
const jstxtPaths: string[] = [];
const specialPaths: string[] = [];
inputList.forEach(absolutePath => {
// console.log('item', item);
if (absolutePath) {
if (/\.(css|less|scss)$/.test(absolutePath)) {
cssPaths.push(absolutePath);
} else if (/\.(js)$/.test(absolutePath)) {
jsPaths.push(absolutePath);
} else if (/\.(html|jsp)$/.test(absolutePath)) {
html = true;
} else if (/css\.txt$/.test(absolutePath)) {
csstxtPaths.push(absolutePath);
} else if (/js\.txt$/.test(absolutePath)) {
jstxtPaths.push(absolutePath);
} else {
// In packager special files are turned into dirs (.content.xml for example)
let stat;
try {
stat = gfs.statSync(absolutePath);
} catch (err) {
if (err.code === "ENOENT") {
// File not found anymore, thread as special so libs are rebuild
} else {
// Report on other errors
console.error("Error:", absolutePath, err);
}
}
if (!stat || stat.isDirectory()) {
specialPaths.push(absolutePath);
} else {
other = true;
}
}
}
});
// Fix state
// css.txt has only effect on one individual client lib, so handle as css/less
css = css || cssPaths.length > 0 || csstxtPaths.length > 0;
js = js || jsPaths.length > 0; // Don't include jsTxtFiles here yet, since not needed
other = other || specialPaths.length > 0;
// Always update styling info, since we only
let sw = Date.now();
// MULTI STYLE TREES
const cssRelatedFiles = cssPaths.concat(csstxtPaths);
const cssExt = ".css";
const cssToRefresh: string[] = [];
styleTrees.findClientlibs(cssRelatedFiles).forEach(cssFile => {
const cssBase = path.join(
path.dirname(cssFile),
path.basename(cssFile, cssExt)
);
// console.log(`Name without css: ${cssBase}`)
const clientLibs = instance.clientlibTree.findClientlibs(cssBase);
clientLibs.forEach(lib => {
// console.log(`Lib name: ${lib.name} (${lib.css})`);
if (lib.css && cssToRefresh.indexOf(lib.css) === -1) {
cssToRefresh.push(lib.css);
}
});
});
// console.log(cssToRefresh);
// console.log("Determine dependencies: " + (Date.now() - sw) + " ms");
if (css && !js && !html && !other) {
console.log(
chalk`[{blue ${instance.name}}] Only styling was changed, try to inject`
);
bs.reload(cssToRefresh);
} else {
if (js) {
// Fix js before reloading, so links can be generated immediately
// First make paths relative to correct jcr_root
const relativeJsPaths: string[] = [];
jsPaths.forEach(filePath => {
config.jcrContentRoots.forEach(rootDir => {
if (filePath.indexOf(rootDir) === 0) {
// Found correct root
const relativeJcrPath = filePath.replace(rootDir, "");
relativeJsPaths.push(relativeJcrPath);
}
});
});
// Remove relative paths from jstree cache (will be updated when needed)
instance.clientlibTree.jsTrees.resetFiles(relativeJsPaths);
}
if (specialPaths.length > 0 || jstxtPaths.length > 0) {
// If special paths were changed, reset the list of libs (but leave files alone)
instance.clientlibTree.jsTrees.resetLibs();
}
// When js files have been invalidated, trigger reload
bs.reload();
// Update clientlibTree if something changed in the clientlib structure (do after reload since is needed for next update)
// TODO make async
// TODO wait with next push/update until this is done
if (specialPaths.length > 0) {
console.log(
chalk`[{blue ${instance.name}}] Special paths were changed, so rebuild clientlib tree`
);
// Something changed in the structure, so rebuild all clientlib stuff
// TODO make function for this
// // Setup clientlib stuff
sw = Date.now();
// TODO reuse objects and only reinit?
const promises = [];
instance.clientlibTree = new ClientlibTree({
name: instance.name,
server: instance.server
});
promises.push(instance.clientlibTree.init());
// DOn't update style three, since it happened in the prvious step (if there were any less/css/csstxt changes)
// TODO maybe leave it in, as a catch-all in case we miss something when updating the file tree
Promise.all(promises)
.then(() => {
// console.log(`Init clientlibs finished`);
console.log(
chalk`[{blue ${instance.name}}] Rebuild clientlib tree: ${(
Date.now() - sw
).toString()} ms`
);
})
.catch(reason => {
console.log(
chalk`[{blue ${instance.name}}] [{red ERROR}] Rebuild rejected: ${reason}`
);
});
}
}
} | the_stack |
import * as path from 'path';
import { BotInfo, getBotDisplayName, isMac, SharedConstants } from '@bfemulator/app-shared';
import * as BotActions from '@bfemulator/app-shared/built/state/actions/botActions';
import {
BotConfigWithPath,
Command,
CommandServiceImpl,
CommandServiceInstance,
mergeEndpoints,
uniqueId,
} from '@bfemulator/sdk-shared';
import { BotConfigurationBase } from 'botframework-config/lib';
import { IConnectedService, IEndpointService, ServiceTypes } from 'botframework-config/lib/schema';
import { dialog } from 'electron';
import { store } from '../state/store';
import { BotHelpers } from '../botHelpers';
import { Emulator } from '../emulator';
import { TelemetryService } from '../telemetry';
import { botProjectFileWatcher, chatWatcher, transcriptsWatcher } from '../watchers';
import { CredentialManager } from '../credentialManager';
const { Bot } = SharedConstants.Commands;
/** Registers bot commands */
export class BotCommands {
@CommandServiceInstance()
private commandService: CommandServiceImpl;
// ---------------------------------------------------------------------------
// Create a bot
@Command(Bot.Create)
protected async createBot(bot: BotConfigWithPath, secret: string): Promise<BotConfigWithPath> {
// getStore and add bot entry to bots.json
const dirName = path.dirname(bot.path);
const botsJsonEntry: BotInfo = {
path: bot.path,
displayName: getBotDisplayName(bot),
transcriptsPath: path.join(dirName, './transcripts'),
chatsPath: path.join(dirName, './dialogs'),
};
BotHelpers.patchBotsJson(bot.path, botsJsonEntry);
// save the bot & secret
try {
await BotHelpers.saveBot(bot, secret);
if (secret) {
await CredentialManager.setPassword(bot.path, secret);
}
} catch (e) {
// TODO: make sure these are surfaced on the client side and caught so we can act on them
// eslint-disable-next-line no-console
console.error(`${Bot.Create}: Error trying to save bot: ${e}`);
throw e;
}
const telemetryInfo = { path: bot.path, hasSecret: !!secret };
TelemetryService.trackEvent('bot_create', telemetryInfo);
return bot;
}
// ---------------------------------------------------------------------------
// Save bot file and cause a bots list write
@Command(Bot.Save)
protected async saveBot(bot: BotConfigWithPath) {
await BotHelpers.saveBot(bot); // Let this propagate up the stack
}
// ---------------------------------------------------------------------------
// Opens a bot file at specified path and returns the bot
@Command(Bot.Open)
protected async openBot(botPath: string, secret?: string): Promise<BotConfigWithPath> {
const botInfo = BotHelpers.pathExistsInRecentBots(botPath) ? BotHelpers.getBotInfoByPath(botPath) : null;
if (botInfo) {
const dirName = path.dirname(botPath);
let syncWithClient: boolean;
if (!botInfo.transcriptsPath) {
botInfo.transcriptsPath = path.join(dirName, './transcripts');
syncWithClient = true;
}
if (!botInfo.chatsPath) {
botInfo.chatsPath = path.join(dirName, './dialogs');
syncWithClient = true;
}
if (syncWithClient) {
BotHelpers.patchBotsJson(botPath, botInfo);
}
}
// load the bot (decrypt with secret if we were able to get it)
let bot: BotConfigWithPath;
try {
bot = await BotHelpers.loadBotWithRetry(botPath, secret);
} catch (e) {
await dialog.showErrorBox('Failed to open the bot', e.message);
}
if (!bot) {
// user couldn't provide correct secret, abort
throw new Error('No secret provided to decrypt encrypted bot.');
}
return bot;
}
// ---------------------------------------------------------------------------
// Set active bot
@Command(Bot.SetActive)
protected async setActiveBot(bot: BotConfigWithPath): Promise<string> {
// set up the file watcher
await botProjectFileWatcher.watch(bot.path);
// set active bot and active directory
const botDirectory = path.dirname(bot.path);
store.dispatch(BotActions.setActive(bot));
store.dispatch(BotActions.setDirectory(botDirectory));
const botInfo = BotHelpers.getBotInfoByPath(bot.path) || {};
const dirName = path.dirname(bot.path);
const {
chatsPath = path.join(dirName, './dialogs'),
transcriptsPath = path.join(dirName, './transcripts'),
} = botInfo;
const botFilePath = path.parse(botInfo.path || '').dir;
const relativeChatsPath = path.relative(botFilePath, chatsPath);
const relativeTranscriptsPath = path.relative(botFilePath, transcriptsPath);
const displayedChatsPath = relativeChatsPath.includes('..') ? chatsPath : relativeChatsPath;
const displayedTranscriptsPath = relativeTranscriptsPath.includes('..') ? transcriptsPath : relativeTranscriptsPath;
const sep = isMac() ? path.posix.sep : (path.posix as any).win32.sep;
await Promise.all([
chatWatcher.watch(chatsPath),
transcriptsWatcher.watch(transcriptsPath),
this.commandService.remoteCall(Bot.ChatsPathUpdated, `${displayedChatsPath}${sep}**`),
this.commandService.remoteCall(Bot.TranscriptsPathUpdated, `${displayedTranscriptsPath}${sep}`),
this.commandService.call(Bot.RestartEndpointService),
]);
// Workaround for a JSON serialization issue in bot.services where they're an array
// on the Node side, but deserialize as a dictionary on the renderer side.
return botDirectory;
}
// ---------------------------------------------------------------------------
// Restart emulator endpoint service
@Command(Bot.RestartEndpointService)
protected async restartEndpointService() {
const bot = BotHelpers.getActiveBot();
const emulator = Emulator.getInstance();
emulator.server.state.endpoints.clear();
const overridesArePresent = bot.overrides && bot.overrides.endpoint;
let appliedOverrides = false;
bot.services
.filter(s => s.type === ServiceTypes.Endpoint)
.forEach(service => {
let endpoint = service as IEndpointService;
if (overridesArePresent && !appliedOverrides) {
// if an endpoint id was not specified, apply overrides to first endpoint;
// otherwise, apply overrides to the matching endpoint
if (!bot.overrides.endpoint.id) {
endpoint = mergeEndpoints(endpoint, bot.overrides.endpoint);
appliedOverrides = true;
} else if (bot.overrides.endpoint.id === service.id) {
endpoint = mergeEndpoints(endpoint, bot.overrides.endpoint);
appliedOverrides = true;
}
}
emulator.server.state.endpoints.set(endpoint.id, {
botId: endpoint.id,
botUrl: endpoint.endpoint,
msaAppId: endpoint.appId,
msaPassword: endpoint.appPassword,
channelService: (endpoint as any).channelService,
});
});
}
// ---------------------------------------------------------------------------
// Close active bot (called from client-side)
@Command(Bot.Close)
protected closeBot() {
botProjectFileWatcher.unwatch();
store.dispatch(BotActions.closeBot());
}
// ---------------------------------------------------------------------------
// Adds or updates an msbot service entry.
@Command(Bot.AddOrUpdateService)
protected async addOrUpdateService(serviceType: ServiceTypes, service: IConnectedService) {
if (!service.id || !service.id.length) {
service.id = uniqueId();
}
const activeBot = BotHelpers.getActiveBot();
const botInfo = activeBot && BotHelpers.getBotInfoByPath(activeBot.path);
if (botInfo) {
const secret = await CredentialManager.getPassword(activeBot.path);
const botConfig = BotHelpers.toSavableBot(activeBot, secret);
const index = botConfig.services.findIndex(s => s.id === service.id && s.type === service.type);
const existing = botConfig.services[index];
if (existing) {
// Patch existing service
botConfig.services[index] = BotConfigurationBase.serviceFromJSON({
...existing,
...service,
});
} else {
// Add new service
if (service.type !== serviceType) {
throw new Error('serviceType does not match');
}
botConfig.connectService(service);
TelemetryService.trackEvent('service_add', { type: service.type });
}
try {
await BotHelpers.saveBot(botConfig);
// The file watcher will not pick up this change immediately
// making the value in the store stale and potentially incorrect
// so we'll dispatch it right away
store.dispatch(BotActions.setActive(botConfig));
await this.commandService.remoteCall(SharedConstants.Commands.Bot.SetActive, botConfig, botConfig.getPath());
} catch (e) {
// eslint-disable-next-line no-console
console.error(`bot:add-or-update-service: Error trying to save bot: ${e}`);
throw e;
}
}
}
// ---------------------------------------------------------------------------
// Removes an msbot service entry.
@Command(Bot.RemoveService)
protected async removeService(serviceType: ServiceTypes, serviceOrId: any) {
const activeBot = BotHelpers.getActiveBot();
const botInfo = activeBot && BotHelpers.getBotInfoByPath(activeBot.path);
if (botInfo) {
const secret = await CredentialManager.getPassword(activeBot.path);
const botConfig = BotHelpers.toSavableBot(activeBot, secret);
const id = typeof serviceOrId === 'string' ? serviceOrId : serviceOrId.id;
botConfig.disconnectService(id);
try {
await BotHelpers.saveBot(botConfig);
store.dispatch(BotActions.setActive(botConfig));
await this.commandService.remoteCall(SharedConstants.Commands.Bot.SetActive, botConfig, botConfig.getPath());
} catch (e) {
// eslint-disable-next-line no-console
console.error(`bot:remove-service: Error trying to save bot: ${e}`);
throw e;
}
}
}
// ---------------------------------------------------------------------------
// Patches a bot record in bots.json
@Command(Bot.PatchBotList)
protected async patchBotList(botPath: string, botInfo: BotInfo): Promise<boolean> {
// patch bots.json and update the store
BotHelpers.patchBotsJson(botPath, botInfo);
const dirName = path.dirname(botInfo.path);
const {
chatsPath = path.join(dirName, './dialogs'),
transcriptsPath = path.join(dirName, './transcripts'),
} = botInfo;
await Promise.all([chatWatcher.watch(chatsPath), transcriptsWatcher.watch(transcriptsPath)]);
return true;
}
// ---------------------------------------------------------------------------
// Removes a bot record from bots.json (doesn't delete .bot file)
@Command(Bot.RemoveFromBotList)
protected async removeFromBotList(botPath: string): Promise<void> {
const { ShowMessageBox } = SharedConstants.Commands.Electron;
const result = await this.commandService.call(ShowMessageBox, true, {
type: 'question',
buttons: ['Cancel', 'OK'],
defaultId: 1,
message: `Remove Bot ${botPath} from bots list. Are you sure?`,
cancelId: 0,
});
if (result) {
await BotHelpers.removeBotFromList(botPath).catch();
}
}
} | the_stack |
import * as React from 'react';
import { Axis as D3Axis } from 'd3-axis';
import { select as d3Select } from 'd3-selection';
import { ILegend, Legends } from '../Legends/index';
import { classNamesFunction, getId, find } from '@fluentui/react/lib/Utilities';
import {
IAccessibilityProps,
CartesianChart,
IBasestate,
IChildProps,
ILineChartProps,
ILineChartPoints,
ICustomizedCalloutData,
IMargins,
IRefArrayData,
IColorFillBarsProps,
ILineChartStyleProps,
ILineChartStyles,
ILineChartGap,
} from '../../index';
import { DirectionalHint } from '@fluentui/react/lib/Callout';
import { EventsAnnotation } from './eventAnnotation/EventAnnotation';
import {
calloutData,
ChartTypes,
getXAxisType,
XAxisTypes,
tooltipOfXAxislabels,
Points,
pointTypes,
getMinMaxOfYAxis,
} from '../../utilities/index';
type NumericAxis = D3Axis<number | { valueOf(): number }>;
const getClassNames = classNamesFunction<ILineChartStyleProps, ILineChartStyles>();
enum PointSize {
hoverSize = 11,
invisibleSize = 1,
}
const DEFAULT_LINE_STROKE_SIZE = 4;
// The given shape of a icon must be 2.5 times bigger than line width (known as stroke width)
const PATH_MULTIPLY_SIZE = 2.5;
/**
*
* @param x units from origin
* @param y units from origin
* @param w is the legnth of the each side of a shape
* @param index index to get the shape path
*/
const _getPointPath = (x: number, y: number, w: number, index: number): string => {
const allPointPaths = [
// circle path
`M${x - w / 2} ${y}
A${w / 2} ${w / 2} 0 1 0 ${x + w / 2} ${y}
M${x - w / 2} ${y}
A ${w / 2} ${w / 2} 0 1 1 ${x + w / 2} ${y}
`,
//square
`M${x - w / 2} ${y - w / 2}
L${x + w / 2} ${y - w / 2}
L${x + w / 2} ${y + w / 2}
L${x - w / 2} ${y + w / 2}
Z`,
//triangle
`M${x - w / 2} ${y - 0.2886 * w}
H ${x + w / 2}
L${x} ${y + 0.5774 * w} Z`,
//diamond
`M${x} ${y - w / 2}
L${x + w / 2} ${y}
L${x} ${y + w / 2}
L${x - w / 2} ${y}
Z`,
//pyramid
`M${x} ${y - 0.5774 * w}
L${x + w / 2} ${y + 0.2886 * w}
L${x - w / 2} ${y + 0.2886 * w} Z`,
//hexagon
`M${x - 0.5 * w} ${y - 0.866 * w}
L${x + 0.5 * w} ${y - 0.866 * w}
L${x + w} ${y}
L${x + 0.5 * w} ${y + 0.866 * w}
L${x - 0.5 * w} ${y + 0.866 * w}
L${x - w} ${y}
Z`,
//pentagon
`M${x} ${y - 0.851 * w}
L${x + 0.6884 * w} ${y - 0.2633 * w}
L${x + 0.5001 * w} ${y + 0.6884 * w}
L${x - 0.5001 * w} ${y + 0.6884 * w}
L${x - 0.6884 * w} ${y - 0.2633 * w}
Z`,
//octagon
`M${x - 0.5001 * w} ${y - 1.207 * w}
L${x + 0.5001 * w} ${y - 1.207 * w}
L${x + 1.207 * w} ${y - 0.5001 * w}
L${x + 1.207 * w} ${y + 0.5001 * w}
L${x + 0.5001 * w} ${y + 1.207 * w}
L${x - 0.5001 * w} ${y + 1.207 * w}
L${x - 1.207 * w} ${y + 0.5001 * w}
L${x - 1.207 * w} ${y - 0.5001 * w}
Z`,
];
return allPointPaths[index];
};
type LineChartDataWithIndex = ILineChartPoints & { index: number };
export interface ILineChartState extends IBasestate {
// This array contains data of selected legends for points
selectedLegendPoints: LineChartDataWithIndex[];
// This array contains data of selected legends for color bars
selectedColorBarLegend: IColorFillBarsProps[];
// This is a boolean value which is set to true
// when at least one legend is selected
isSelectedLegend: boolean;
// This value will be used as customized callout props - point callout.
dataPointCalloutProps?: ICustomizedCalloutData;
// This value will be used as Customized callout props - For stack callout.
stackCalloutProps?: ICustomizedCalloutData;
// active or hovered point
activePoint?: string;
// x-axis callout accessibility data
xAxisCalloutAccessibilityData?: IAccessibilityProps;
}
export class LineChartBase extends React.Component<ILineChartProps, ILineChartState> {
private _points: LineChartDataWithIndex[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _calloutPoints: any[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _xAxisScale: any = '';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private _yAxisScale: any = '';
private _circleId: string;
private _lineId: string;
private _borderId: string;
private _verticalLine: string;
private _colorFillBarPatternId: string;
private _uniqueCallOutID: string | null;
private _refArray: IRefArrayData[];
private margins: IMargins;
private eventLabelHeight: number = 36;
private lines: JSX.Element[];
private _renderedColorFillBars: JSX.Element[];
private _colorFillBars: IColorFillBarsProps[];
private _colorFillBarsOpacity: number;
private _tooltipId: string;
constructor(props: ILineChartProps) {
super(props);
this.state = {
hoverXValue: '',
activeLegend: '',
YValueHover: [],
refSelected: '',
selectedLegend: '',
isCalloutVisible: false,
selectedLegendPoints: [],
selectedColorBarLegend: [],
isSelectedLegend: false,
activePoint: '',
};
this._refArray = [];
this._points = this._injectIndexPropertyInLineChartData(this.props.data.lineChartData);
this._colorFillBars = [];
this._colorFillBarsOpacity = 0.5;
this._calloutPoints = calloutData(this._points) || [];
this._circleId = getId('circle');
this._lineId = getId('lineID');
this._borderId = getId('borderID');
this._verticalLine = getId('verticalLine');
this._colorFillBarPatternId = getId('colorFillBarPattern');
this._tooltipId = getId('LineChartTooltipId_');
props.eventAnnotationProps &&
props.eventAnnotationProps.labelHeight &&
(this.eventLabelHeight = props.eventAnnotationProps.labelHeight);
}
public componentDidUpdate(prevProps: ILineChartProps): void {
/** note that height and width are not used to resize or set as dimesions of the chart,
* fitParentContainer is responisble for setting the height and width or resizing of the svg/chart
*/
if (
prevProps.height !== this.props.height ||
prevProps.width !== this.props.width ||
prevProps.data !== this.props.data
) {
this._points = this._injectIndexPropertyInLineChartData(this.props.data.lineChartData);
this._calloutPoints = calloutData(this._points) || [];
}
}
public render(): JSX.Element {
const { tickValues, tickFormat, eventAnnotationProps, legendProps, data } = this.props;
this._points = this._injectIndexPropertyInLineChartData(data.lineChartData);
const isXAxisDateType = getXAxisType(this._points);
let points = this._points;
if (legendProps && !!legendProps.canSelectMultipleLegends) {
points = this.state.selectedLegendPoints.length >= 1 ? this.state.selectedLegendPoints : this._points;
this._calloutPoints = calloutData(points);
}
const legendBars = this._createLegends(this._points!);
const calloutProps = {
isCalloutVisible: this.state.isCalloutVisible,
directionalHint: DirectionalHint.topAutoEdge,
YValueHover: this.state.YValueHover,
hoverXValue: this.state.hoverXValue,
id: `toolTip${this._uniqueCallOutID}`,
target: this.state.refSelected,
isBeakVisible: false,
gapSpace: 15,
onDismiss: this._closeCallout,
preventDismissOnEvent: () => true,
hidden: !(!this.props.hideTooltip && this.state.isCalloutVisible),
descriptionMessage:
this.props.getCalloutDescriptionMessage && this.state.stackCalloutProps
? this.props.getCalloutDescriptionMessage(this.state.stackCalloutProps)
: undefined,
'data-is-focusable': true,
xAxisCalloutAccessibilityData: this.state.xAxisCalloutAccessibilityData,
...this.props.calloutProps,
};
const tickParams = {
tickValues: tickValues,
tickFormat: tickFormat,
};
return (
<CartesianChart
{...this.props}
chartTitle={data.chartTitle}
points={points}
chartType={ChartTypes.LineChart}
isCalloutForStack
calloutProps={calloutProps}
tickParams={tickParams}
legendBars={legendBars}
getmargins={this._getMargins}
getGraphData={this._initializeLineChartData}
xAxisType={isXAxisDateType ? XAxisTypes.DateAxis : XAxisTypes.NumericAxis}
customizedCallout={this._getCustomizedCallout()}
onChartMouseLeave={this._handleChartMouseLeave}
/* eslint-disable react/jsx-no-bind */
// eslint-disable-next-line react/no-children-prop
children={(props: IChildProps) => {
this._xAxisScale = props.xScale!;
this._yAxisScale = props.yScale!;
return (
<>
<g>
<line
x1={0}
y1={0}
x2={0}
y2={props.containerHeight}
stroke={'#C8C8C8'}
id={this._verticalLine}
visibility={'hidden'}
strokeDasharray={'5,5'}
/>
<g>
{this._renderedColorFillBars}
{this.lines}
</g>
{eventAnnotationProps && (
<EventsAnnotation
{...eventAnnotationProps}
scale={props.xScale!}
chartYTop={this.margins.top! + this.eventLabelHeight}
chartYBottom={props.containerHeight! - 35}
/>
)}
</g>
</>
);
}}
/>
);
}
private _injectIndexPropertyInLineChartData = (lineChartData?: ILineChartPoints[]): LineChartDataWithIndex[] | [] => {
const { allowMultipleShapesForPoints = false } = this.props;
return lineChartData
? lineChartData.map((item: ILineChartPoints, index: number) => ({
...item,
index: allowMultipleShapesForPoints ? index : -1,
}))
: [];
};
private _getCustomizedCallout = () => {
return this.props.onRenderCalloutPerStack
? this.props.onRenderCalloutPerStack(this.state.stackCalloutProps)
: this.props.onRenderCalloutPerDataPoint
? this.props.onRenderCalloutPerDataPoint(this.state.dataPointCalloutProps)
: null;
};
private _getMargins = (margins: IMargins) => {
this.margins = margins;
};
private _initializeLineChartData = (
xScale: NumericAxis,
yScale: NumericAxis,
containerHeight: number,
containerWidth: number,
xElement: SVGElement | null,
) => {
this._xAxisScale = xScale;
this._yAxisScale = yScale;
this._renderedColorFillBars = this.props.colorFillBars ? this._createColorFillBars(containerHeight) : [];
this.lines = this._createLines(xElement!, containerHeight!);
};
private _handleSingleLegendSelectionAction = (lineChartItem: LineChartDataWithIndex | IColorFillBarsProps) => {
if (this.state.selectedLegend === lineChartItem.legend) {
this.setState({ selectedLegend: '', activeLegend: lineChartItem.legend });
this._handleLegendClick(lineChartItem, null);
} else {
this.setState({
selectedLegend: lineChartItem.legend,
activeLegend: lineChartItem.legend,
});
this._handleLegendClick(lineChartItem, lineChartItem.legend);
}
};
private _onHoverCardHide = () => {
this.setState({
selectedLegendPoints: [],
selectedColorBarLegend: [],
isSelectedLegend: false,
});
};
private _createLegends(data: LineChartDataWithIndex[]): JSX.Element {
const { legendProps, allowMultipleShapesForPoints = false } = this.props;
const isLegendMultiSelectEnabled = !!(legendProps && !!legendProps.canSelectMultipleLegends);
const legendDataItems = data.map((point: LineChartDataWithIndex) => {
const color: string = point.color;
// mapping data to the format Legends component needs
const legend: ILegend = {
title: point.legend!,
color: color,
action: () => {
if (isLegendMultiSelectEnabled) {
this._handleMultipleLineLegendSelectionAction(point);
} else {
this._handleSingleLegendSelectionAction(point);
}
},
onMouseOutAction: () => {
this.setState({ activeLegend: '' });
},
hoverAction: () => {
this.setState({ activeLegend: point.legend });
},
...(point.legendShape && {
shape: point.legendShape,
}),
...(allowMultipleShapesForPoints && {
shape: Points[point.index % Object.keys(pointTypes).length] as ILegend['shape'],
}),
};
return legend;
});
const colorFillBarsLegendDataItems = this.props.colorFillBars
? this.props.colorFillBars.map((colorFillBar: IColorFillBarsProps, index: number) => {
const title = colorFillBar.legend;
const legend: ILegend = {
title,
color: colorFillBar.color,
action: () => {
if (isLegendMultiSelectEnabled) {
this._handleMultipleColorFillBarLegendSelectionAction(colorFillBar);
} else {
this._handleSingleLegendSelectionAction(colorFillBar);
}
},
onMouseOutAction: () => {
this.setState({ activeLegend: '' });
},
hoverAction: () => {
this.setState({ activeLegend: title });
},
opacity: this._colorFillBarsOpacity,
stripePattern: colorFillBar.applyPattern,
};
return legend;
})
: [];
const legends = (
<Legends
legends={[...legendDataItems, ...colorFillBarsLegendDataItems]}
enabledWrapLines={this.props.enabledLegendsWrapLines}
overflowProps={this.props.legendsOverflowProps}
focusZonePropsInHoverCard={this.props.focusZonePropsForLegendsInHoverCard}
overflowText={this.props.legendsOverflowText}
{...(isLegendMultiSelectEnabled && { onLegendHoverCardLeave: this._onHoverCardHide })}
{...this.props.legendProps}
/>
);
return legends;
}
private _closeCallout = () => {
this.setState({
isCalloutVisible: false,
});
};
private _getBoxWidthOfShape = (pointId: string, pointIndex: number, isLastPoint: boolean) => {
const { allowMultipleShapesForPoints = false, strokeWidth = DEFAULT_LINE_STROKE_SIZE } = this.props;
const { activePoint } = this.state;
if (allowMultipleShapesForPoints) {
if (activePoint === pointId) {
return PointSize.hoverSize;
} else if (pointIndex === 1 || isLastPoint) {
return strokeWidth * PATH_MULTIPLY_SIZE;
} else {
return PointSize.invisibleSize;
}
} else {
if (activePoint === pointId) {
return PointSize.hoverSize;
} else {
return PointSize.invisibleSize;
}
}
};
private _getPath = (
xPos: number,
yPos: number,
pointId: string,
pointIndex: number,
isLastPoint: boolean,
pointOftheLine: number,
): string => {
const { allowMultipleShapesForPoints = false } = this.props;
let w = this._getBoxWidthOfShape(pointId, pointIndex, isLastPoint);
const index: number = allowMultipleShapesForPoints ? pointOftheLine % Object.keys(pointTypes).length : 0;
const widthRatio = pointTypes[index].widthRatio;
w = widthRatio > 1 ? w / widthRatio : w;
return _getPointPath(xPos, yPos, w, index);
};
private _getPointFill = (lineColor: string, pointId: string, pointIndex: number, isLastPoint: boolean) => {
const { activePoint } = this.state;
const { theme, allowMultipleShapesForPoints = false } = this.props;
if (allowMultipleShapesForPoints) {
if (pointIndex === 1 || isLastPoint) {
if (activePoint === pointId) {
return theme!.palette.white;
} else {
return lineColor;
}
} else {
if (activePoint === pointId) {
return theme!.palette.white;
} else {
return lineColor;
}
}
} else {
if (activePoint === pointId) {
return theme!.palette.white;
} else {
return lineColor;
}
}
};
private _createLines(xElement: SVGElement, containerHeight: number): JSX.Element[] {
const lines: JSX.Element[] = [];
if (this.state.isSelectedLegend) {
this._points = this.state.selectedLegendPoints;
} else {
this._points = this._injectIndexPropertyInLineChartData(this.props.data.lineChartData);
}
for (let i = 0; i < this._points.length; i++) {
const linesForLine: JSX.Element[] = [];
const bordersForLine: JSX.Element[] = [];
const pointsForLine: JSX.Element[] = [];
const legendVal: string = this._points[i].legend;
const lineColor: string = this._points[i].color;
const { activePoint } = this.state;
const { theme } = this.props;
const verticaLineHeight = containerHeight - this.margins.bottom! + 6;
if (this._points[i].data.length === 1) {
const { x: x1, y: y1, xAxisCalloutData, xAxisCalloutAccessibilityData } = this._points[i].data[0];
const circleId = `${this._circleId}${i}`;
pointsForLine.push(
<circle
id={`${this._circleId}${i}`}
key={`${this._circleId}${i}`}
r={activePoint === circleId ? 5.5 : 3.5}
cx={this._xAxisScale(x1)}
cy={this._yAxisScale(y1)}
fill={activePoint === circleId ? theme!.palette.white : lineColor}
onMouseOver={this._handleHover.bind(
this,
x1,
y1,
verticaLineHeight,
xAxisCalloutData,
circleId,
xAxisCalloutAccessibilityData,
)}
onMouseMove={this._handleHover.bind(
this,
x1,
y1,
verticaLineHeight,
xAxisCalloutData,
circleId,
xAxisCalloutAccessibilityData,
)}
onMouseOut={this._handleMouseOut}
strokeWidth={activePoint === circleId ? DEFAULT_LINE_STROKE_SIZE : 0}
stroke={activePoint === circleId ? lineColor : ''}
/>,
);
}
let gapIndex = 0;
const gaps = this._points[i].gaps?.sort((a, b) => a.startIndex - b.startIndex) ?? [];
for (let j = 1; j < this._points[i].data.length; j++) {
const gapResult = this._checkInGap(j, gaps, gapIndex);
const isInGap = gapResult.isInGap;
gapIndex = gapResult.gapIndex;
const lineId = `${this._lineId}${i}${j}`;
const borderId = `${this._borderId}${i}${j}`;
const circleId = `${this._circleId}${i}${j}`;
const { x: x1, y: y1, xAxisCalloutData, xAxisCalloutAccessibilityData } = this._points[i].data[j - 1];
const { x: x2, y: y2 } = this._points[i].data[j];
let path = this._getPath(this._xAxisScale(x1), this._yAxisScale(y1), circleId, j, false, this._points[i].index);
const strokeWidth =
this._points[i].lineOptions?.strokeWidth || this.props.strokeWidth || DEFAULT_LINE_STROKE_SIZE;
const isLegendSelected: boolean =
this.state.activeLegend === legendVal || this.state.activeLegend === '' || this.state.isSelectedLegend;
const currentPointHidden = this._points[i].hideNonActiveDots && activePoint !== circleId;
pointsForLine.push(
<path
id={circleId}
key={circleId}
d={path}
data-is-focusable={i === 0 ? true : false}
onMouseOver={this._handleHover.bind(
this,
x1,
y1,
verticaLineHeight,
xAxisCalloutData,
circleId,
xAxisCalloutAccessibilityData,
)}
onMouseMove={this._handleHover.bind(
this,
x1,
y1,
verticaLineHeight,
xAxisCalloutData,
circleId,
xAxisCalloutAccessibilityData,
)}
onMouseOut={this._handleMouseOut}
onFocus={() => this._handleFocus(lineId, x1, xAxisCalloutData, circleId, xAxisCalloutAccessibilityData)}
onBlur={this._handleMouseOut}
onClick={this._onDataPointClick.bind(this, this._points[i].data[j - 1].onDataPointClick)}
opacity={isLegendSelected && !currentPointHidden ? 1 : 0.01}
fill={this._getPointFill(lineColor, circleId, j, false)}
stroke={lineColor}
strokeWidth={strokeWidth}
/>,
);
if (j + 1 === this._points[i].data.length) {
const lastCircleId = `${circleId}${j}L`;
const lastPointHidden = this._points[i].hideNonActiveDots && activePoint !== lastCircleId;
path = this._getPath(
this._xAxisScale(x2),
this._yAxisScale(y2),
lastCircleId,
j,
true,
this._points[i].index,
);
const {
xAxisCalloutData: lastCirlceXCallout,
xAxisCalloutAccessibilityData: lastCirlceXCalloutAccessibilityData,
} = this._points[i].data[j];
pointsForLine.push(
<path
id={lastCircleId}
key={lastCircleId}
d={path}
data-is-focusable={i === 0 ? true : false}
onMouseOver={this._handleHover.bind(
this,
x2,
y2,
verticaLineHeight,
lastCirlceXCallout,
lastCircleId,
lastCirlceXCalloutAccessibilityData,
)}
onMouseMove={this._handleHover.bind(
this,
x2,
y2,
verticaLineHeight,
lastCirlceXCallout,
lastCircleId,
lastCirlceXCalloutAccessibilityData,
)}
onMouseOut={this._handleMouseOut}
onFocus={() =>
this._handleFocus(lineId, x2, lastCirlceXCallout, lastCircleId, lastCirlceXCalloutAccessibilityData)
}
onBlur={this._handleMouseOut}
onClick={this._onDataPointClick.bind(this, this._points[i].data[j].onDataPointClick)}
opacity={isLegendSelected && !lastPointHidden ? 1 : 0.01}
fill={this._getPointFill(lineColor, lastCircleId, j, true)}
stroke={lineColor}
strokeWidth={strokeWidth}
/>,
);
/* eslint-enable react/jsx-no-bind */
}
if (isLegendSelected) {
// don't draw line if it is in a gap
if (!isInGap) {
const lineBorderWidth = this._points[i].lineOptions?.lineBorderWidth
? Number.parseFloat(this._points[i].lineOptions!.lineBorderWidth!.toString())
: 0;
if (lineBorderWidth > 0) {
bordersForLine.push(
<line
id={borderId}
key={borderId}
x1={this._xAxisScale(x1)}
y1={this._yAxisScale(y1)}
x2={this._xAxisScale(x2)}
y2={this._yAxisScale(y2)}
strokeLinecap={this._points[i].lineOptions?.strokeLinecap ?? 'round'}
strokeWidth={Number.parseFloat(strokeWidth.toString()) + lineBorderWidth}
stroke={this._points[i].lineOptions?.lineBorderColor || theme!.palette.white}
opacity={1}
/>,
);
}
linesForLine.push(
<line
id={lineId}
key={lineId}
x1={this._xAxisScale(x1)}
y1={this._yAxisScale(y1)}
x2={this._xAxisScale(x2)}
y2={this._yAxisScale(y2)}
strokeWidth={strokeWidth}
ref={(e: SVGLineElement | null) => {
this._refCallback(e!, lineId);
}}
onMouseOver={this._handleHover.bind(
this,
x1,
y1,
verticaLineHeight,
xAxisCalloutData,
circleId,
xAxisCalloutAccessibilityData,
)}
onMouseMove={this._handleHover.bind(
this,
x1,
y1,
verticaLineHeight,
xAxisCalloutData,
circleId,
xAxisCalloutAccessibilityData,
)}
onMouseOut={this._handleMouseOut}
stroke={lineColor}
strokeLinecap={this._points[i].lineOptions?.strokeLinecap ?? 'round'}
strokeDasharray={this._points[i].lineOptions?.strokeDasharray}
strokeDashoffset={this._points[i].lineOptions?.strokeDashoffset}
opacity={1}
onClick={this._onLineClick.bind(this, this._points[i].onLineClick)}
/>,
);
}
} else {
if (!isInGap) {
linesForLine.push(
<line
id={lineId}
key={lineId}
x1={this._xAxisScale(x1)}
y1={this._yAxisScale(y1)}
x2={this._xAxisScale(x2)}
y2={this._yAxisScale(y2)}
strokeWidth={strokeWidth}
stroke={lineColor}
strokeLinecap={this._points[i].lineOptions?.strokeLinecap ?? 'round'}
strokeDasharray={this._points[i].lineOptions?.strokeDasharray}
strokeDashoffset={this._points[i].lineOptions?.strokeDashoffset}
opacity={0.1}
/>,
);
}
}
}
lines.push(...bordersForLine, ...linesForLine, ...pointsForLine);
}
const classNames = getClassNames(this.props.styles!, {
theme: this.props.theme!,
});
// Removing un wanted tooltip div from DOM, when prop not provided.
if (!this.props.showXAxisLablesTooltip) {
try {
document.getElementById(this._tooltipId) && document.getElementById(this._tooltipId)!.remove();
// eslint-disable-next-line no-empty
} catch (e) {}
}
// Used to display tooltip at x axis labels.
if (!this.props.wrapXAxisLables && this.props.showXAxisLablesTooltip) {
const xAxisElement = d3Select(xElement).call(this._xAxisScale);
try {
document.getElementById(this._tooltipId) && document.getElementById(this._tooltipId)!.remove();
// eslint-disable-next-line no-empty
} catch (e) {}
const tooltipProps = {
tooltipCls: classNames.tooltip!,
id: this._tooltipId,
xAxis: xAxisElement,
};
xAxisElement && tooltipOfXAxislabels(tooltipProps);
}
return lines;
}
private _createColorFillBars = (containerHeight: number) => {
const colorFillBars: JSX.Element[] = [];
if (this.state.isSelectedLegend) {
this._colorFillBars = this.state.selectedColorBarLegend;
} else {
this._colorFillBars = this.props.colorFillBars!;
}
const yMinMaxValues = getMinMaxOfYAxis(this._points, ChartTypes.LineChart);
const FILL_Y_PADDING = 3;
for (let i = 0; i < this._colorFillBars.length; i++) {
const colorFillBar = this._colorFillBars[i];
const colorFillBarId = getId(colorFillBar.legend.replace(/\W/g, ''));
if (colorFillBar.applyPattern) {
// Using a pattern element because CSS was unable to render diagonal stripes for rect elements
colorFillBars.push(this._getStripePattern(colorFillBar.color, i));
}
for (let j = 0; j < colorFillBar.data.length; j++) {
const startX = colorFillBar.data[j].startX;
const endX = colorFillBar.data[j].endX;
const opacity =
this.state.activeLegend === colorFillBar.legend ||
this.state.activeLegend === '' ||
this.state.isSelectedLegend
? this._colorFillBarsOpacity
: 0.1;
colorFillBars.push(
<rect
fill={colorFillBar.applyPattern ? `url(#${this._colorFillBarPatternId}${i})` : colorFillBar.color}
fillOpacity={opacity}
x={this._xAxisScale(startX)}
y={this._yAxisScale(yMinMaxValues.endValue) - FILL_Y_PADDING}
width={Math.abs(this._xAxisScale(endX) - this._xAxisScale(startX))}
height={
this._yAxisScale(this.props.yMinValue || 0) - this._yAxisScale(yMinMaxValues.endValue) + FILL_Y_PADDING
}
key={`${colorFillBarId}${j}`}
/>,
);
}
}
return colorFillBars;
};
private _getStripePattern = (color: string, id: number) => {
// This describes a tile pattern that resembles diagonal stripes
// For more information: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d
const stripePath = 'M-4,4 l8,-8 M0,16 l16,-16 M12,20 l8,-8';
return (
<pattern
id={`${this._colorFillBarPatternId}${id}`}
width={16}
height={16}
key={`${this._colorFillBarPatternId}${id}`}
patternUnits={'userSpaceOnUse'}
>
<path d={stripePath} stroke={color} strokeWidth={1.25} />
</pattern>
);
};
private _checkInGap = (pointIndex: number, gaps: ILineChartGap[], currentGapIndex: number) => {
let gapIndex = currentGapIndex;
let isInGap = false;
while (gapIndex < gaps.length && pointIndex > gaps[gapIndex].endIndex) {
gapIndex++;
}
if (gapIndex < gaps.length && pointIndex > gaps[gapIndex].startIndex && pointIndex <= gaps[gapIndex].endIndex) {
isInGap = true;
}
return { isInGap, gapIndex };
};
private _refCallback(element: SVGGElement, legendTitle: string): void {
this._refArray.push({ index: legendTitle, refElement: element });
}
private _handleFocus = (
lineId: string,
x: number | Date,
xAxisCalloutData: string | undefined,
circleId: string,
xAxisCalloutAccessibilityData?: IAccessibilityProps,
) => {
this._uniqueCallOutID = circleId;
const formattedData = x instanceof Date ? x.toLocaleDateString() : x;
const xVal = x instanceof Date ? x.getTime() : x;
const found = find(this._calloutPoints, (element: { x: string | number }) => element.x === xVal);
// if no points need to be called out then don't show vertical line and callout card
if (found) {
const _this = this;
d3Select('#' + circleId).attr('aria-labelledby', `toolTip${this._uniqueCallOutID}`);
d3Select(`#${this._verticalLine}`)
.attr('transform', () => `translate(${_this._xAxisScale(x)}, 0)`)
.attr('visibility', 'visibility');
this._refArray.forEach((obj: IRefArrayData) => {
if (obj.index === lineId) {
this.setState({
isCalloutVisible: true,
refSelected: obj.refElement,
hoverXValue: xAxisCalloutData ? xAxisCalloutData : '' + formattedData,
YValueHover: found.values,
stackCalloutProps: found!,
dataPointCalloutProps: found!,
activePoint: circleId,
xAxisCalloutAccessibilityData,
});
}
});
} else {
this.setState({
activePoint: circleId,
});
}
};
private _handleHover = (
x: number | Date,
y: number | Date,
lineHeight: number,
xAxisCalloutData: string,
circleId: string,
xAxisCalloutAccessibilityData: IAccessibilityProps,
mouseEvent: React.MouseEvent<SVGElement>,
) => {
mouseEvent.persist();
const formattedData = x instanceof Date ? x.toLocaleDateString() : x;
const xVal = x instanceof Date ? x.getTime() : x;
const _this = this;
const found = find(this._calloutPoints, (element: { x: string | number }) => element.x === xVal);
// if no points need to be called out then don't show vertical line and callout card
if (found) {
d3Select(`#${this._verticalLine}`)
.attr('transform', () => `translate(${_this._xAxisScale(x)}, ${_this._yAxisScale(y)})`)
.attr('visibility', 'visibility')
.attr('y2', `${lineHeight - _this._yAxisScale(y)}`);
if (this._uniqueCallOutID !== circleId) {
this._uniqueCallOutID = circleId;
this.setState({
isCalloutVisible: true,
refSelected: `#${circleId}`,
hoverXValue: xAxisCalloutData ? xAxisCalloutData : '' + formattedData,
YValueHover: found.values,
stackCalloutProps: found!,
dataPointCalloutProps: found!,
activePoint: circleId,
xAxisCalloutAccessibilityData,
});
}
} else {
this.setState({
activePoint: circleId,
});
}
};
private _onLineClick = (func: () => void) => {
if (func) {
func();
}
};
private _onDataPointClick = (func: () => void) => {
if (func) {
func();
}
};
private _handleMouseOut = () => {
d3Select(`#${this._verticalLine}`).attr('visibility', 'hidden');
};
private _handleChartMouseLeave = () => {
this._uniqueCallOutID = null;
this.setState({
isCalloutVisible: false,
activePoint: '',
});
};
private _handleLegendClick = (
lineChartItem: LineChartDataWithIndex | IColorFillBarsProps,
selectedLegend: string | null | string[],
): void => {
if (lineChartItem.onLegendClick) {
lineChartItem.onLegendClick(selectedLegend);
}
};
private _handleMultipleLineLegendSelectionAction = (selectedLine: LineChartDataWithIndex) => {
const selectedLineIndex = this.state.selectedLegendPoints.reduce((acc, line, index) => {
if (acc > -1 || line.legend !== selectedLine.legend) {
return acc;
} else {
return index;
}
}, -1);
let selectedLines: LineChartDataWithIndex[];
if (selectedLineIndex === -1) {
selectedLines = [...this.state.selectedLegendPoints, selectedLine];
} else {
selectedLines = this.state.selectedLegendPoints
.slice(0, selectedLineIndex)
.concat(this.state.selectedLegendPoints.slice(selectedLineIndex + 1));
}
const areAllLineLegendsSelected = this.props.data && selectedLines.length === this.props.data.lineChartData!.length;
if (
areAllLineLegendsSelected &&
((this.props.colorFillBars && this.props.colorFillBars.length === this.state.selectedColorBarLegend.length) ||
!this.props.colorFillBars)
) {
// Clear all legends if all legends including color fill bar legends are selected
// Or clear all legends if all legends are selected and there are no color fill bars
this._clearMultipleLegendSelections();
} else if (!selectedLines.length && !this.state.selectedColorBarLegend.length) {
// Clear all legends if no legends including color fill bar legends are selected
this._clearMultipleLegendSelections();
} else {
// Otherwise, set state when one or more legends are selected, including color fill bar legends
this.setState({
selectedLegendPoints: selectedLines,
isSelectedLegend: true,
});
}
const selectedLegendTitlesToPass = selectedLines.map((line: LineChartDataWithIndex) => line.legend);
this._handleLegendClick(selectedLine, selectedLegendTitlesToPass);
};
private _handleMultipleColorFillBarLegendSelectionAction = (selectedColorFillBar: IColorFillBarsProps) => {
const selectedColorFillBarIndex = this.state.selectedColorBarLegend.reduce((acc, colorFillBar, index) => {
if (acc > -1 || colorFillBar.legend !== selectedColorFillBar.legend) {
return acc;
} else {
return index;
}
}, -1);
let selectedColorFillBars: IColorFillBarsProps[];
if (selectedColorFillBarIndex === -1) {
selectedColorFillBars = [...this.state.selectedColorBarLegend, selectedColorFillBar];
} else {
selectedColorFillBars = this.state.selectedColorBarLegend
.slice(0, selectedColorFillBarIndex)
.concat(this.state.selectedColorBarLegend.slice(selectedColorFillBarIndex + 1));
}
const areAllColorFillBarLegendsSelected =
selectedColorFillBars.length === (this.props.colorFillBars && this.props.colorFillBars!.length);
if (
areAllColorFillBarLegendsSelected &&
((this.props.data && this.props.data.lineChartData!.length === this.state.selectedLegendPoints.length) ||
!this.props.data)
) {
// Clear all legends if all legends, including line legends, are selected
// Or clear all legends if all legends are selected and there is no line data
this._clearMultipleLegendSelections();
} else if (!selectedColorFillBars.length && !this.state.selectedLegendPoints.length) {
// Clear all legends if no legends are selected, including line legends
this._clearMultipleLegendSelections();
} else {
// set state when one or more legends are selected, including line legends
this.setState({
selectedColorBarLegend: selectedColorFillBars,
isSelectedLegend: true,
});
}
const selectedLegendTitlesToPass = selectedColorFillBars.map(
(colorFillBar: IColorFillBarsProps) => colorFillBar.legend,
);
this._handleLegendClick(selectedColorFillBar, selectedLegendTitlesToPass);
};
private _clearMultipleLegendSelections = () => {
this.setState({
selectedColorBarLegend: [],
selectedLegendPoints: [],
isSelectedLegend: false,
});
};
} | the_stack |
"use strict";
import * as tl from "azure-pipelines-task-lib/task";
import * as Q from "q";
import ContainerConnection from "./containerconnection";
import * as pipelineUtils from "./pipelineutils";
import * as path from "path";
import * as crypto from "crypto";
const matchPatternForSize = new RegExp(/[\d\.]+/);
const orgUrl = tl.getVariable('System.TeamFoundationCollectionUri');
const buildString = "build";
const hostType = tl.getVariable("System.HostType");
const isBuild = hostType && hostType.toLowerCase() === buildString;
const matchPatternForDigest = new RegExp(/sha256\:(.+)/);
export function build(connection: ContainerConnection, dockerFile: string, commandArguments: string, labelArguments: string[], tagArguments: string[], onCommandOut: (output) => any): any {
var command = connection.createCommand();
command.arg("build");
command.arg(["-f", dockerFile]);
if (labelArguments) {
labelArguments.forEach(label => {
command.arg(["--label", label]);
});
}
command.line(commandArguments);
if (tagArguments) {
tagArguments.forEach(tagArgument => {
command.arg(["-t", tagArgument]);
});
}
command.arg(getBuildContext(dockerFile));
// setup variable to store the command output
let output = "";
//In case of BuildKit build, docker tool is sending the logs to stderr.
command.on(isBuildKitBuild() ? "stderr" : "stdout", data => {
output += data;
});
return connection.execCommand(command).then(() => {
// Return the std output of the command by calling the delegate
onCommandOut(output);
});
}
export function command(connection: ContainerConnection, dockerCommand: string, commandArguments: string, onCommandOut: (output) => any): any {
let command = connection.createCommand();
command.arg(dockerCommand);
command.line(commandArguments);
// setup variable to store the command output
let output = "";
command.on("stdout", data => {
output += data;
});
return connection.execCommand(command).then(() => {
// Return the std output of the command by calling the delegate
onCommandOut(output);
});
}
export function push(connection: ContainerConnection, image: string, commandArguments: string, onCommandOut: (image, output) => any): any {
var command = connection.createCommand();
command.arg("push");
command.arg(image);
command.line(commandArguments);
// setup variable to store the command output
let output = "";
command.on("stdout", data => {
output += data;
});
return connection.execCommand(command).then(() => {
// Return the std output of the command by calling the delegate
onCommandOut(image, output + "\n");
});
}
export function start(connection: ContainerConnection, container: string, commandArguments: string, onCommandOut: (container, output) => any): any {
var command = connection.createCommand();
command.arg("start");
command.arg(container);
command.line(commandArguments);
// setup variable to store the command output
let output = "";
command.on("stdout", data => {
output += data;
});
return connection.execCommand(command).then(() => {
// Return the std output of the command by calling the delegate
onCommandOut(container, output + "\n");
});
}
export function stop(connection: ContainerConnection, container: string, commandArguments: string, onCommandOut: (container, output) => any): any {
var command = connection.createCommand();
command.arg("stop");
command.arg(container);
command.line(commandArguments);
// setup variable to store the command output
let output = "";
command.on("stdout", data => {
output += data;
});
return connection.execCommand(command).then(() => {
// Return the std output of the command by calling the delegate
onCommandOut(container, output + "\n");
});
}
export function getCommandArguments(args: string): string {
return args ? args.replace(/\n/g, " ") : "";
}
export function getCreatorEmail(): string {
const schedule = "schedule";
const buildReason = tl.getVariable("Build.Reason");
let userEmail: string = "";
if (isBuild && (!buildReason || buildReason.toLowerCase() !== schedule)) {
userEmail = tl.getVariable("Build.RequestedForEmail");
}
else {
userEmail = tl.getVariable("Release.RequestedForEmail");
}
return userEmail;
}
export function getPipelineLogsUrl(): string {
let pipelineUrl = "";
if (isBuild) {
pipelineUrl = orgUrl + tl.getVariable("System.TeamProject") + "/_build/results?buildId=" + tl.getVariable("Build.BuildId");
}
else {
pipelineUrl = orgUrl + tl.getVariable("System.TeamProject") + "/_releaseProgress?releaseId=" + tl.getVariable("Release.ReleaseId");
}
return pipelineUrl;
}
export function getBuildAndPushArguments(dockerFile: string, labelArguments: string[], tagArguments: string[]): { [key: string]: string } {
let labelArgumentsString = "";
let tagArgumentsString = "";
if (labelArguments && labelArguments.length > 0) {
labelArgumentsString = labelArguments.join(", ");
}
if (tagArguments && tagArguments.length > 0) {
tagArgumentsString = tagArguments.join(", ");
}
let buildArguments = {
"dockerFilePath": dockerFile,
"labels": labelArgumentsString,
"tags": tagArgumentsString,
"context": getBuildContext(dockerFile)
};
return buildArguments;
}
export function getBuildContext(dockerFile: string): string {
let buildContext = tl.getPathInput("buildContext");
if (useDefaultBuildContext(buildContext)) {
buildContext = path.dirname(dockerFile);
}
return buildContext;
}
export function useDefaultBuildContext(buildContext: string): boolean {
let defaultWorkingDir = tl.getVariable("SYSTEM_DEFAULTWORKINGDIRECTORY");
let defaultPath = path.join(defaultWorkingDir, "**");
return buildContext === defaultPath;
}
export function getPipelineUrl(): string {
let pipelineUrl = "";
const pipelineId = tl.getVariable("System.DefinitionId");
if (isBuild) {
pipelineUrl = orgUrl + tl.getVariable("System.TeamProject") + "/_build?definitionId=" + pipelineId;
}
else {
pipelineUrl = orgUrl + tl.getVariable("System.TeamProject") + "/_release?definitionId=" + pipelineId;
}
return pipelineUrl;
}
export function getLayers(history: string): { [key: string]: string }[] {
var layers = [];
if (!history) {
return null;
}
var lines = history.split(/[\r?\n]/);
lines.forEach(line => {
line = line.trim();
if (line.length != 0) {
layers.push(parseHistoryForLayers(line));
}
});
return layers.reverse();
}
export function getImageFingerPrintV1Name(history: string): string {
let v1Name = "";
if (!history) {
return null;
}
const lines = history.split(/[\r?\n]/);
if (lines && lines.length > 0) {
v1Name = parseHistoryForV1Name(lines[0]);
}
return v1Name;
}
export function getImageSize(layers: { [key: string]: string }[]): string {
let imageSize = 0;
for (const layer of layers) {
for (let key in layer) {
if (key.toLowerCase() === "size") {
const layerSize = extractSizeInBytes(layer[key]);
imageSize += layerSize;
}
}
}
return imageSize.toString() + "B";
}
export function extractSizeInBytes(size: string): number {
const sizeStringValue = size.match(matchPatternForSize);
if (sizeStringValue && sizeStringValue.length > 0) {
const sizeIntValue = parseFloat(sizeStringValue[0]);
const sizeUnit = size.substring(sizeIntValue.toString().length);
switch (sizeUnit.toLowerCase()) {
case "b": return sizeIntValue;
case "kb": return sizeIntValue * 1024;
case "mb": return sizeIntValue * 1024 * 1024;
case "gb": return sizeIntValue * 1024 * 1024 * 1024;
case "tb": return sizeIntValue * 1024 * 1024 * 1024 * 1024;
case "pb": return sizeIntValue * 1024 * 1024 * 1024 * 1024 * 1024;
}
}
return 0;
}
function parseHistoryForLayers(input: string) {
const NOP = '#(nop)';
let directive = "UNSPECIFIED";
let argument = "";
let index: number = input.indexOf(NOP);
const createdByMatch = "; createdBy:";
const indexCreatedBy = input.indexOf(createdByMatch);
if (index != -1) {
argument = input.substr(index + 6).trim();
directive = argument.substr(0, argument.indexOf(' '));
argument = argument.substr(argument.indexOf(' ') + 1).trim();
}
else {
directive = 'RUN';
argument = input.substring(indexCreatedBy + createdByMatch.length, input.length - 1);
}
const layerIdMatch = "; layerId:";
const indexLayerId = argument.indexOf(layerIdMatch);
if (indexLayerId >= 0) {
argument = argument.substring(0, indexLayerId);
}
let createdAt: string = "";
let layerSize: string = "";
const createdAtMatch = "createdAt:";
const layerSizeMatch = "; layerSize:";
const indexCreatedAt = input.indexOf(createdAtMatch);
const indexLayerSize = input.indexOf(layerSizeMatch);
if (indexCreatedAt >= 0 && indexLayerSize >= 0) {
createdAt = input.substring(indexCreatedAt + createdAtMatch.length, indexLayerSize);
layerSize = input.substring(indexLayerSize + layerSizeMatch.length, indexCreatedBy);
}
return { "directive": directive, "arguments": argument, "createdOn": createdAt, "size": layerSize };
}
function parseHistoryForV1Name(topHistoryLayer: string): string {
let v1Name = "";
const layerIdString = "layerId:sha256:";
const indexOfLayerId = topHistoryLayer.indexOf(layerIdString);
if (indexOfLayerId >= 0) {
v1Name = topHistoryLayer.substring(indexOfLayerId + layerIdString.length);
}
return v1Name;
}
export async function getHistory(connection: ContainerConnection, image: string): Promise<string> {
var command = connection.createCommand();
command.arg("history");
command.arg(["--format", "createdAt:{{.CreatedAt}}; layerSize:{{.Size}}; createdBy:{{.CreatedBy}}; layerId:{{.ID}}"]);
command.arg("--no-trunc");
command.arg(image);
const defer = Q.defer();
// setup variable to store the command output
let output = "";
command.on("stdout", data => {
output += data;
});
try {
connection.execCommand(command).then(() => {
defer.resolve();
});
}
catch (e) {
// Swallow any exceptions encountered in executing command
// such as --format flag not supported in old docker cli versions
output = null;
defer.resolve();
tl.warning("Not publishing to image meta data store as get history failed with error " + e);
}
await defer.promise;
return output;
}
export async function getImageRootfsLayers(connection: ContainerConnection, imageDigest: string): Promise<string[]> {
var command = connection.createCommand();
command.arg("inspect");
command.arg(imageDigest);
command.arg(["-f", "{{.RootFS.Layers}}"]);
const defer = Q.defer();
// setup variable to store the command output
let output = "";
command.on("stdout", data => {
output += data;
});
try {
connection.execCommand(command).then(() => {
defer.resolve();
});
}
catch (e) {
// Swallow any exceptions encountered in executing command
output = null;
defer.resolve();
tl.warning("get image inspect failed with error " + e);
}
await defer.promise;
// Remove '[' and ']' from output
output = output.replace(/\[/g, "");
output = output.replace(/]/g, "");
// Return array of rootLayers in the form -> [sha256:2c833f307fd8f18a378b71d3c43c575fabdb88955a2198662938ac2a08a99928,sha256:5f349fdc9028f7edde7f8d4c487d59b3e4b9d66a367dc85492fc7a81abf57b41, ...]
let rootLayers = output.split(" ");
return rootLayers;
}
export function getImageFingerPrint(rootLayers: string[], v1Name: string): { [key: string]: string | string[] } {
let v2_blobs: string[] = [];
let v2Name: string = "";
if (rootLayers && rootLayers.length > 0) {
rootLayers.forEach(layer => {
// remove sha256 from layerIds
const digest = getDigest(layer);
v2_blobs.push(digest);
// As per grafeas spec, the name of the image's v2 blobs computed via:
// [bottom] := v2_blob[bottom]
// [N] := sha256(v2_blob[N] + " " + v2_name[N+1])
// Only the name of the final blob is kept.
v2Name = v2Name + digest + " ";
});
v2Name = generateV2Name(v2Name.trim());
}
return {
"v1Name": v1Name,
"v2Blobs": v2_blobs,
"v2Name": v2Name
};
}
function getDigest(imageId: string): string {
const imageMatch = imageId.match(matchPatternForDigest);
if (imageMatch && imageMatch.length >= 1) {
return imageMatch[1];
}
return "";
}
function generateV2Name(input: string): string {
return crypto.createHash("sha256").update(input).digest("hex");
}
function isBuildKitBuild(): boolean {
const isBuildKitBuildValue = tl.getVariable("DOCKER_BUILDKIT");
return isBuildKitBuildValue && Number(isBuildKitBuildValue) == 1;
} | the_stack |
import * as os from 'os'
import * as prettier from 'prettier'
import { GenerateArgs, ModelMap, ContextDefinition } from '../../types'
import {
GraphQLTypeField,
GraphQLTypeObject,
GraphQLInterfaceObject,
GraphQLTypeDefinition,
GraphQLUnionObject,
} from '../../source-helper'
import {
renderDefaultResolvers,
getContextName,
getModelName,
TypeToInputTypeAssociation,
InputTypesMap,
printFieldLikeType,
getDistinctInputTypes,
renderEnums,
groupModelsNameByImportPath,
InterfacesMap,
UnionsMap,
createInterfacesMap,
createUnionsMap,
union,
resolverReturnType,
} from '../common'
import { TypeAliasDefinition } from '../../introspection/types'
import { upperFirst } from '../../utils'
export function format(code: string, options: prettier.Options = {}) {
try {
return prettier.format(code, {
...options,
parser: 'typescript',
})
} catch (e) {
console.log(
`There is a syntax error in generated code, unformatted code printed, error: ${JSON.stringify(
e,
)}`,
)
return code
}
}
export function generate(args: GenerateArgs): string {
// TODO: Maybe move this to source helper
const inputTypesMap: InputTypesMap = args.types
.filter(type => type.type.isInput)
.reduce((inputTypes, type) => {
return {
...inputTypes,
[`${type.name}`]: type,
}
}, {})
// TODO: Type this
const typeToInputTypeAssociation: TypeToInputTypeAssociation = args.types
.filter(
type =>
type.type.isObject &&
type.fields.filter(
field => field.arguments.filter(arg => arg.type.isInput).length > 0,
).length > 0,
)
.reduce((types, type) => {
return {
...types,
[`${type.name}`]: [].concat(
...(type.fields.map(field =>
field.arguments
.filter(arg => arg.type.isInput)
.map(arg => arg.type.name),
) as any),
),
}
}, {})
const interfacesMap = createInterfacesMap(args.interfaces)
const unionsMap = createUnionsMap(args.unions)
const hasPolymorphicObjects =
Object.keys(interfacesMap).length > 0 || Object.keys(unionsMap).length > 0
return `\
${renderHeader(args, { hasPolymorphicObjects })}
${renderEnums(args)}
${renderNamespaces(
args,
interfacesMap,
unionsMap,
typeToInputTypeAssociation,
inputTypesMap,
)}
${renderResolvers(args)}
${
args.iResolversAugmentationEnabled
? renderGraphqlToolsModuleAugmentationIResolvers()
: ''
}
`
}
/**
* This renders a TypeScript module augmentation against graphql-tools
* IResolvers type. Apollo Server uses that type to type its resolvers.
* The problem with that type is that it is very loose compared to
* graphqlgen including being an index type. The index type in particular
* breaks compatibility with the resolvers generated by graphqlgen. We
* fix this by augmenting the IResolvers type.
*
* References:
*
* - https://www.typescriptlang.org/docs/handbook/declaration-merging.html
* - https://github.com/prisma/graphqlgen/issues/15
*/
const renderGraphqlToolsModuleAugmentationIResolvers = (): string => {
// Use ts-ignore otherwise tests will throw an error about no such
// module being found. Further, if a user for some reason is not using
// Apollo Server, then this augmentation doesn't matter anyways, and
// should not throw an exception for them either.
return `
// @ts-ignore
declare module "graphql-tools" {
interface IResolvers extends Resolvers {}
}
`
}
type HeaderOptions = {
hasPolymorphicObjects?: boolean
}
function renderHeader(
args: GenerateArgs,
{ hasPolymorphicObjects = false }: HeaderOptions = {},
): string {
const imports = hasPolymorphicObjects
? ['GraphQLResolveInfo', 'GraphQLIsTypeOfFn']
: ['GraphQLResolveInfo']
return `
// Code generated by github.com/prisma/graphqlgen, DO NOT EDIT.
import { ${imports.join(', ')} } from 'graphql'
${renderImports(args)}
`
}
function renderImports(args: GenerateArgs) {
const modelsToImport = Object.keys(args.modelMap)
.filter(modelName => {
const modelDef = args.modelMap[modelName].definition
return !(
modelDef.kind === 'TypeAliasDefinition' &&
(modelDef as TypeAliasDefinition).isEnum
)
})
.map(modelName => args.modelMap[modelName])
const modelsByImportPaths = groupModelsNameByImportPath(modelsToImport)
if (args.context) {
const importsFromContextPath =
modelsByImportPaths[args.context.contextPath] || []
return importsToString(
Object.assign({}, modelsByImportPaths, {
[args.context.contextPath]: importsFromContextPath.concat(
getContextName(args.context),
),
}),
)
}
return `${importsToString(modelsByImportPaths)}${os.EOL}type ${getContextName(
args.context,
)} = any`
}
function importsToString(
modelsByImportPaths: ReturnType<typeof groupModelsNameByImportPath>,
) {
return Object.keys(modelsByImportPaths)
.map(
importPath =>
`import { ${modelsByImportPaths[importPath].join(
', ',
)} } from '${importPath}'`,
)
.join(os.EOL)
}
function renderNamespaces(
args: GenerateArgs,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
typeToInputTypeAssociation: TypeToInputTypeAssociation,
inputTypesMap: InputTypesMap,
): string {
return `\
${renderObjectNamespaces(
args,
interfacesMap,
unionsMap,
typeToInputTypeAssociation,
inputTypesMap,
)}
${renderInterfaceNamespaces(args, interfacesMap, unionsMap)}
${renderUnionNamespaces(args)}
`
}
function renderObjectNamespaces(
args: GenerateArgs,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
typeToInputTypeAssociation: TypeToInputTypeAssociation,
inputTypesMap: InputTypesMap,
): string {
return args.types
.filter(type => type.type.isObject)
.map(type =>
renderNamespace(
type,
interfacesMap,
unionsMap,
typeToInputTypeAssociation,
inputTypesMap,
args,
),
)
.join(os.EOL)
}
function renderInterfaceNamespaces(
args: GenerateArgs,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
): string {
return args.interfaces
.map(type => renderInterfaceNamespace(type, interfacesMap, unionsMap, args))
.join(os.EOL)
}
function renderUnionNamespaces(args: GenerateArgs): string {
return args.unions.map(type => renderUnionNamespace(type, args)).join(os.EOL)
}
function renderInterfaceNamespace(
graphQLTypeObject: GraphQLInterfaceObject,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
args: GenerateArgs,
): string {
return `\
export namespace ${graphQLTypeObject.name}Resolvers {
${renderInputArgInterfaces(
graphQLTypeObject,
args.modelMap,
interfacesMap,
unionsMap,
)}
export interface Type {
__resolveType: ${renderTypeResolveTypeResolver(graphQLTypeObject, args)}
}
}
`
}
export const renderTypeResolveTypeResolver = (
abstractType: GraphQLInterfaceObject | GraphQLUnionObject,
args: GenerateArgs,
): string => {
const modelNames: string[] = []
const gqlObjectNameTypes: string[] = []
const gqlObjects =
abstractType.kind === 'interface'
? abstractType.implementors
: abstractType.types
for (const gqlObj of gqlObjects) {
modelNames.push(getModelName(gqlObj, args.modelMap))
gqlObjectNameTypes.push(renderStringConstant(gqlObj.name))
}
return `
(
value: ${union(modelNames)},
context: ${getContextName(args.context)},
info: GraphQLResolveInfo
) => ${resolverReturnType(union(gqlObjectNameTypes))}
`
}
const renderStringConstant = (x: unknown) => `"${x}"`
function renderUnionNamespace(
graphQLTypeObject: GraphQLUnionObject,
args: GenerateArgs,
): string {
return `\
export namespace ${graphQLTypeObject.name}Resolvers {
export interface Type {
__resolveType?: ${renderTypeResolveTypeResolver(
graphQLTypeObject,
args,
)}
}
}
`
}
function renderNamespace(
graphQLTypeObject: GraphQLTypeObject,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
typeToInputTypeAssociation: TypeToInputTypeAssociation,
inputTypesMap: InputTypesMap,
args: GenerateArgs,
): string {
return `\
export namespace ${graphQLTypeObject.name}Resolvers {
${
args.defaultResolversEnabled
? renderDefaultResolvers(graphQLTypeObject, args, 'defaultResolvers')
: ''
}
${renderInputTypeInterfaces(
graphQLTypeObject,
args.modelMap,
interfacesMap,
unionsMap,
typeToInputTypeAssociation,
inputTypesMap,
)}
${renderInputArgInterfaces(
graphQLTypeObject,
args.modelMap,
interfacesMap,
unionsMap,
)}
${renderResolverFunctionInterfaces(
graphQLTypeObject,
args.modelMap,
interfacesMap,
unionsMap,
args.delegatedParentResolversEnabled,
args.context,
)}
${renderResolverTypeInterface(
graphQLTypeObject,
args.modelMap,
interfacesMap,
unionsMap,
args.delegatedParentResolversEnabled,
args.context,
)}
${/* TODO renderResolverClass(type, modelMap) */ ''}
}
`
}
function renderIsTypeOfFunctionInterface(
type: GraphQLTypeObject | GraphQLInterfaceObject,
modelMap: ModelMap,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
context?: ContextDefinition,
) {
let possibleTypes: GraphQLTypeDefinition[] = []
// TODO Refactor once type is a proper discriminated union
if (!type.type.isInterface) {
type = type as GraphQLTypeObject
if (type.implements) {
possibleTypes = type.implements.reduce(
(obj: GraphQLTypeDefinition[], interfaceName) => {
return [...obj, ...interfacesMap[interfaceName]]
},
[],
)
}
}
for (let unionName in unionsMap) {
if (unionsMap[unionName].find(unionType => unionType.name === type.name)) {
possibleTypes = unionsMap[unionName]
}
}
if (possibleTypes.length === 0) {
return ''
}
return `\
__isTypeOf?: GraphQLIsTypeOfFn<${possibleTypes
.map(possibleType => getModelName(possibleType, modelMap))
.join(' | ')}, ${getContextName(context)}>;`
}
function renderInputTypeInterfaces(
type: GraphQLTypeObject,
modelMap: ModelMap,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
typeToInputTypeAssociation: TypeToInputTypeAssociation,
inputTypesMap: InputTypesMap,
) {
if (!typeToInputTypeAssociation[type.name]) {
return ``
}
return getDistinctInputTypes(type, typeToInputTypeAssociation, inputTypesMap)
.map(typeAssociation => {
return `export interface ${inputTypesMap[typeAssociation].name} {
${inputTypesMap[typeAssociation].fields.map(field =>
printFieldLikeType(field, modelMap, interfacesMap, unionsMap),
)}
}`
})
.join(os.EOL)
}
function renderInputArgInterfaces(
type: GraphQLTypeObject | GraphQLInterfaceObject,
modelMap: ModelMap,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
): string {
return type.fields
.map(field =>
renderInputArgInterface(field, modelMap, interfacesMap, unionsMap),
)
.join(os.EOL)
}
function renderInputArgInterface(
field: GraphQLTypeField,
modelMap: ModelMap,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
): string {
if (field.arguments.length === 0) {
return ''
}
return `
export interface Args${upperFirst(field.name)} {
${field.arguments
.map(arg =>
printFieldLikeType(
arg as GraphQLTypeField,
modelMap,
interfacesMap,
unionsMap,
),
)
.join(os.EOL)}
}
`
}
function renderResolverFunctionInterfaces(
type: GraphQLTypeObject,
modelMap: ModelMap,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
delegatedParentResolversEnabled: boolean,
context?: ContextDefinition,
): string {
return type.fields
.map(
field =>
`export type ${upperFirst(field.name)}Resolver = ${renderTypeResolver(
field,
type,
modelMap,
interfacesMap,
unionsMap,
delegatedParentResolversEnabled,
context,
)}`,
)
.join(os.EOL)
}
function renderResolverTypeInterface(
type: GraphQLTypeObject | GraphQLInterfaceObject,
modelMap: ModelMap,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
delegatedParentResolversEnabled: boolean,
context?: ContextDefinition,
interfaceName: string = 'Type',
): string {
return `
export interface ${interfaceName} {
${type.fields
.map(
field =>
`${field.name}: ${renderTypeResolver(
field,
type,
modelMap,
interfacesMap,
unionsMap,
delegatedParentResolversEnabled,
context,
)}`,
)
.join(os.EOL)}
${renderIsTypeOfFunctionInterface(
type,
modelMap,
interfacesMap,
unionsMap,
context,
)}
}
`
}
const renderTypeResolver = (
field: GraphQLTypeField,
type: GraphQLTypeObject | GraphQLInterfaceObject,
modelMap: ModelMap,
interfacesMap: InterfacesMap,
unionsMap: UnionsMap,
delegatedParentResolversEnabled: boolean,
context?: ContextDefinition,
): string => {
let parent: string
if (type.type.isInterface) {
const implementingTypes = interfacesMap[type.name]
parent = implementingTypes
.map(implType => getModelName(implType, modelMap, 'undefined'))
.join(' | ')
} else {
parent = getModelName(type.type as any, modelMap, 'undefined')
}
const params = `
(
parent: ${parent},
args: ${
field.arguments.length > 0 ? `Args${upperFirst(field.name)}` : '{}'
},
ctx: ${getContextName(context)},
info: GraphQLResolveInfo,
)
`
const returnType = printFieldLikeType(
field,
modelMap,
interfacesMap,
unionsMap,
{ isReturn: true },
)
if (type.name === 'Subscription') {
return `
{
subscribe: ${params} => ${resolverReturnType(
`AsyncIterator<${returnType}>`,
)}
resolve?: ${params} => ${resolverReturnType(returnType)}
}
`
}
const resolveFunc = `${params} => ${resolverReturnType(returnType)}`
if (!delegatedParentResolversEnabled) return resolveFunc
const DelegatedParentResolver = `
{
fragment: string
resolve: ${resolveFunc}
}
`
const resolver = union([`(${resolveFunc})`, DelegatedParentResolver])
return resolver
}
function renderResolvers(args: GenerateArgs): string {
return `\
export interface Resolvers {
${[
...args.types
.filter(obj => obj.type.isObject)
.map(type => `${type.name}: ${type.name}Resolvers.Type`),
...args.interfaces.map(type => `${type.name}?: ${type.name}Resolvers.Type`),
...args.unions.map(type => `${type.name}?: ${type.name}Resolvers.Type`),
].join(os.EOL)}
}
`
} | the_stack |
import { addTypenameToDocument } from '@apollo/client/utilities';
import isEqual from '@wry/equality';
import { ApolloTransaction } from '../apollo/Transaction';
import { CacheSnapshot } from '../CacheSnapshot';
import { areChildrenDynamic, expandVariables } from '../ParsedQueryNode';
import { JsonObject } from '../primitive';
import { EntityId, OperationInstance, RawOperation } from '../schema';
import { DocumentNode, isObject } from '../util';
import { ConsoleTracer } from './ConsoleTracer';
import { QueryInfo } from './QueryInfo';
import { Tracer } from './Tracer';
// Augment DocumentNode type with Hermes's properties
// Because react-apollo can call us without doing transformDocument
// to be safe, we will always call transformDocument then flag that
// we have already done so to not repeating the process.
declare module 'graphql/language/ast' {
export interface DocumentNode {
/** Indicating that query has already ran transformDocument */
hasBeenTransformed?: boolean;
}
}
export namespace CacheContext {
export type EntityIdForNode = (node: JsonObject) => EntityId | undefined;
export type EntityIdForValue = (value: any) => EntityId | undefined;
export type EntityIdMapper = (node: JsonObject) => string | number | undefined;
export type EntityTransformer = (node: JsonObject) => void;
export type OnChangeCallback = (newCacheShapshot: CacheSnapshot, editedNodeIds: Set<String>) => void;
/**
* Expected to return an EntityId or undefined, but we loosen the restrictions
* for ease of declaration.
*/
export type ResolverRedirect = (args: JsonObject) => any;
export type ResolverRedirects = {
[typeName: string]: {
[fieldName: string]: ResolverRedirect,
},
};
/**
* Callback that is triggered when an entity is edited within the cache.
*/
export interface EntityUpdater {
// TODO: It's a bit odd that this is the _only_ Apollo-specific interface
// that we're exposing. Do we want to keep that? It does mirror a
// mutation's update callback nicely.
(dataProxy: ApolloTransaction, entity: any, previous: any): void;
}
export interface EntityUpdaters {
[typeName: string]: EntityUpdater;
}
/**
* Configuration for a Hermes cache.
*/
export interface Configuration {
/** Whether __typename should be injected into nodes in queries. */
addTypename?: boolean;
/**
* Given a node, determines a _globally unique_ identifier for it to be used
* by the cache.
*
* Generally, any node that is considered to be an entity (domain object) by
* the application should be given an id. All entities are normalized
* within the cache; everything else is not.
*/
entityIdForNode?: EntityIdMapper;
/**
* Transformation function to be run on entity nodes that change during
* write operation; an entity node is defined by `entityIdForNode`.
*/
entityTransformer?: EntityTransformer;
/**
* Whether values in the graph should be frozen.
*
* Defaults to true unless process.env.NODE_ENV === 'production'
*/
freeze?: boolean;
/**
* Parameterized fields that should redirect to entities in the cache when
* there is no value currently cached for their location.
*
* Note that you may only redirect to _entities_ within the graph.
* Redirection to arbitrary nodes is not supported.
*/
resolverRedirects?: ResolverRedirects;
/**
* Callbacks that are triggered when entities of a given type are changed.
*
* These provide the opportunity to make edits to the cache based on the
* values that were edited within entities. For example: keeping a filtered
* list in sync w/ the values within it.
*
* Note that these callbacks are called immediately before a transaction is
* committed. You will not see their effect _during_ a transaction.
*/
entityUpdaters?: EntityUpdaters;
/**
* Callback that is triggered when there is a change in the cache.
*
* This allow the cache to be integrated with external tools such as Redux.
* It allows other tools to be notified when there are changes.
*/
onChange?: OnChangeCallback;
/**
* The tracer to instrument the cache with.
*
* If not supplied, a ConsoleTracer will be constructed, with `verbose` and
* `logger` passed as its arguments.
*/
tracer?: Tracer;
/**
* Whether strict mode is enabled (defaults to true).
*/
strict?: boolean;
/**
* Whether debugging information should be logged out.
*
* Enabling this will cause the cache to emit log events for most operations
* performed against it.
*
* Ignored if `tracer` is supplied.
*/
verbose?: boolean;
/**
* The logger to use when emitting messages. By default, `console`.
*
* Ignored if `tracer` is supplied.
*/
logger?: ConsoleTracer.Logger;
}
}
/**
* Configuration and shared state used throughout the cache's operation.
*/
export class CacheContext {
/** Retrieve the EntityId for a given node, if any. */
readonly entityIdForValue: CacheContext.EntityIdForValue;
/** Run transformation on changed entity node, if any. */
readonly entityTransformer: CacheContext.EntityTransformer | undefined;
/** Whether we should freeze snapshots after writes. */
readonly freezeSnapshots: boolean;
/** Whether the cache should emit debug level log events. */
readonly verbose: boolean;
/** Configured resolver redirects. */
readonly resolverRedirects: CacheContext.ResolverRedirects;
/** Configured entity updaters. */
readonly entityUpdaters: CacheContext.EntityUpdaters;
/** Configured on-change callback */
readonly onChange: CacheContext.OnChangeCallback | undefined;
/** Whether the cache should operate in strict mode. */
readonly strict: boolean;
/** The tracer we should use. */
readonly tracer: Tracer;
/** Whether __typename should be injected into nodes in queries. */
readonly addTypename: boolean;
/** All currently known & processed GraphQL documents. */
private readonly _queryInfoMap = new Map<string, QueryInfo>();
/** All currently known & parsed queries, for identity mapping. */
private readonly _operationMap = new Map<string, OperationInstance[]>();
constructor(config: CacheContext.Configuration = {}) {
// Infer dev mode from NODE_ENV, by convention.
const nodeEnv = typeof process !== 'undefined' ? process.env.NODE_ENV : 'development';
this.entityIdForValue = _makeEntityIdMapper(config.entityIdForNode);
this.entityTransformer = config.entityTransformer;
this.freezeSnapshots = 'freeze' in config ? !!config.freeze : nodeEnv !== 'production';
this.strict = typeof config.strict === 'boolean' ? config.strict : true;
this.verbose = !!config.verbose;
this.resolverRedirects = config.resolverRedirects || {};
this.onChange = config.onChange;
this.entityUpdaters = config.entityUpdaters || {};
this.tracer = config.tracer || new ConsoleTracer(!!config.verbose, config.logger);
this.addTypename = config.addTypename || false;
}
/**
* Performs any transformations of operation documents.
*
* Cache consumers should call this on any operation document prior to calling
* any other method in the cache.
*/
transformDocument(document: DocumentNode): DocumentNode {
if (this.addTypename && !document.hasBeenTransformed) {
const transformedDocument = addTypenameToDocument(document);
transformedDocument.hasBeenTransformed = true;
return transformedDocument;
}
return document;
}
/**
* Returns a memoized & parsed operation.
*
* To aid in various cache lookups, the result is memoized by all of its
* values, and can be used as an identity for a specific operation.
*/
parseOperation(raw: RawOperation): OperationInstance {
// It appears like Apollo or someone upstream is cloning or otherwise
// modifying the queries that are passed down. Thus, the operation source
// is a more reliable cache key…
const cacheKey = operationCacheKey(raw.document, raw.fragmentName);
let operationInstances = this._operationMap.get(cacheKey);
if (!operationInstances) {
operationInstances = [];
this._operationMap.set(cacheKey, operationInstances);
}
// Do we already have a copy of this guy?
for (const instance of operationInstances) {
if (instance.rootId !== raw.rootId) continue;
if (!isEqual(instance.variables, raw.variables)) continue;
return instance;
}
const updateRaw: RawOperation = {
...raw,
document: this.transformDocument(raw.document),
};
const info = this._queryInfo(cacheKey, updateRaw);
const fullVariables = { ...info.variableDefaults, ...updateRaw.variables } as JsonObject;
const operation = {
info,
rootId: updateRaw.rootId,
parsedQuery: expandVariables(info.parsed, fullVariables),
isStatic: !areChildrenDynamic(info.parsed),
variables: updateRaw.variables,
};
operationInstances.push(operation);
return operation;
}
/**
* Retrieves a memoized QueryInfo for a given GraphQL document.
*/
private _queryInfo(cacheKey: string, raw: RawOperation): QueryInfo {
if (!this._queryInfoMap.has(cacheKey)) {
this._queryInfoMap.set(cacheKey, new QueryInfo(this, raw));
}
return this._queryInfoMap.get(cacheKey)!;
}
}
/**
* Wrap entityIdForNode so that it coerces all values to strings.
*/
export function _makeEntityIdMapper(
mapper: CacheContext.EntityIdMapper = defaultEntityIdMapper,
): CacheContext.EntityIdForValue {
return function entityIdForNode(node: JsonObject) {
if (!isObject(node)) return undefined;
// We don't trust upstream implementations.
const entityId = mapper(node);
if (typeof entityId === 'string') return entityId;
if (typeof entityId === 'number') return String(entityId);
return undefined;
};
}
export function defaultEntityIdMapper(node: { id?: any }) {
return node.id;
}
export function operationCacheKey(document: DocumentNode, fragmentName?: string) {
if (fragmentName) {
return `${fragmentName}❖${document.loc!.source.body}`;
}
return document.loc!.source.body;
} | the_stack |
import { Match, Template } from '@aws-cdk/assertions';
import { Topic } from '@aws-cdk/aws-sns';
import { Stack } from '@aws-cdk/core';
import * as cdkp from '../../lib';
import { LegacyTestGitHubNpmPipeline, ModernTestGitHubNpmPipeline, OneStackApp, PIPELINE_ENV, TestApp, stringLike } from '../testhelpers';
import { behavior } from '../testhelpers/compliance';
let app: TestApp;
let pipelineStack: Stack;
beforeEach(() => {
app = new TestApp();
pipelineStack = new Stack(app, 'PipelineSecurityStack', { env: PIPELINE_ENV });
});
afterEach(() => {
app.cleanup();
});
behavior('security check option generates lambda/codebuild at pipeline scope', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk');
pipeline.addApplicationStage(new OneStackApp(app, 'App'), { confirmBroadeningPermissions: true });
THEN_codePipelineExpectation();
});
suite.modern(() => {
const pipeline = new ModernTestGitHubNpmPipeline(pipelineStack, 'Cdk');
const stage = new OneStackApp(app, 'App');
pipeline.addStage(stage, {
pre: [
new cdkp.ConfirmPermissionsBroadening('Check', {
stage,
}),
],
});
THEN_codePipelineExpectation();
});
function THEN_codePipelineExpectation() {
Template.fromStack(pipelineStack).resourceCountIs('AWS::Lambda::Function', 1);
Template.fromStack(pipelineStack).hasResourceProperties('AWS::Lambda::Function', {
Role: {
'Fn::GetAtt': [
stringLike('CdkPipeline*SecurityCheckCDKPipelinesAutoApproveServiceRole*'),
'Arn',
],
},
});
// 1 for github build, 1 for synth stage, and 1 for the application security check
Template.fromStack(pipelineStack).resourceCountIs('AWS::CodeBuild::Project', 3);
}
});
behavior('security check option passes correct environment variables to check project', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk');
pipeline.addApplicationStage(new OneStackApp(pipelineStack, 'App'), { confirmBroadeningPermissions: true });
THEN_codePipelineExpectation();
});
suite.modern(() => {
const pipeline = new ModernTestGitHubNpmPipeline(pipelineStack, 'Cdk');
const stage = new OneStackApp(pipelineStack, 'App');
pipeline.addStage(stage, {
pre: [
new cdkp.ConfirmPermissionsBroadening('Check', {
stage,
}),
],
});
THEN_codePipelineExpectation();
});
function THEN_codePipelineExpectation() {
Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodePipeline::Pipeline', {
Stages: Match.arrayWith([
{
Name: 'App',
Actions: Match.arrayWith([
Match.objectLike({
Name: stringLike('*Check'),
Configuration: Match.objectLike({
EnvironmentVariables: Match.serializedJson([
{ name: 'STAGE_PATH', type: 'PLAINTEXT', value: 'PipelineSecurityStack/App' },
{ name: 'STAGE_NAME', type: 'PLAINTEXT', value: 'App' },
{ name: 'ACTION_NAME', type: 'PLAINTEXT', value: Match.anyValue() },
]),
}),
}),
]),
},
]),
});
}
});
behavior('pipeline created with auto approve tags and lambda/codebuild w/ valid permissions', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk');
pipeline.addApplicationStage(new OneStackApp(app, 'App'), { confirmBroadeningPermissions: true });
THEN_codePipelineExpectation();
});
suite.modern(() => {
const pipeline = new ModernTestGitHubNpmPipeline(pipelineStack, 'Cdk');
const stage = new OneStackApp(app, 'App');
pipeline.addStage(stage, {
pre: [
new cdkp.ConfirmPermissionsBroadening('Check', {
stage,
}),
],
});
THEN_codePipelineExpectation();
});
function THEN_codePipelineExpectation() {
// CodePipeline must be tagged as SECURITY_CHECK=ALLOW_APPROVE
Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodePipeline::Pipeline', {
Tags: [
{
Key: 'SECURITY_CHECK',
Value: 'ALLOW_APPROVE',
},
],
});
// Lambda Function only has access to pipelines tagged SECURITY_CHECK=ALLOW_APPROVE
Template.fromStack(pipelineStack).hasResourceProperties('AWS::IAM::Policy', {
PolicyDocument: {
Statement: [
{
Action: ['codepipeline:GetPipelineState', 'codepipeline:PutApprovalResult'],
Condition: {
StringEquals: { 'aws:ResourceTag/SECURITY_CHECK': 'ALLOW_APPROVE' },
},
Effect: 'Allow',
Resource: '*',
},
],
},
});
// CodeBuild must have access to the stacks and invoking the lambda function
Template.fromStack(pipelineStack).hasResourceProperties('AWS::IAM::Policy', {
PolicyDocument: {
Statement: Match.arrayWith([
{
Action: 'sts:AssumeRole',
Condition: {
'ForAnyValue:StringEquals': {
'iam:ResourceTag/aws-cdk:bootstrap-role': [
'deploy',
],
},
},
Effect: 'Allow',
Resource: '*',
},
{
Action: 'lambda:InvokeFunction',
Effect: 'Allow',
Resource: [
{
'Fn::GetAtt': [
stringLike('*AutoApprove*'),
'Arn',
],
},
{
'Fn::Join': [
'',
[
{
'Fn::GetAtt': [
stringLike('*AutoApprove*'),
'Arn',
],
},
':*',
],
],
},
],
},
]),
},
});
}
});
behavior('confirmBroadeningPermissions option at addApplicationStage runs security check on all apps unless overriden', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk');
const securityStage = pipeline.addApplicationStage(new OneStackApp(app, 'StageSecurityCheckStack'), { confirmBroadeningPermissions: true });
securityStage.addApplication(new OneStackApp(app, 'AnotherStack'));
securityStage.addApplication(new OneStackApp(app, 'SkipCheckStack'), { confirmBroadeningPermissions: false });
THEN_codePipelineExpectation();
});
// For the modern API, there is no inheritance
suite.doesNotApply.modern();
function THEN_codePipelineExpectation() {
Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodePipeline::Pipeline', {
Stages: [
{
Actions: [Match.objectLike({ Name: 'GitHub', RunOrder: 1 })],
Name: 'Source',
},
{
Actions: [Match.objectLike({ Name: 'Synth', RunOrder: 1 })],
Name: 'Build',
},
{
Actions: [Match.objectLike({ Name: 'SelfMutate', RunOrder: 1 })],
Name: 'UpdatePipeline',
},
{
Actions: [
Match.objectLike({ Name: 'StageSecurityCheckStackSecurityCheck', RunOrder: 1 }),
Match.objectLike({ Name: 'StageSecurityCheckStackManualApproval', RunOrder: 2 }),
Match.objectLike({ Name: 'AnotherStackSecurityCheck', RunOrder: 5 }),
Match.objectLike({ Name: 'AnotherStackManualApproval', RunOrder: 6 }),
Match.objectLike({ Name: 'Stack.Prepare', RunOrder: 3 }),
Match.objectLike({ Name: 'Stack.Deploy', RunOrder: 4 }),
Match.objectLike({ Name: 'AnotherStack-Stack.Prepare', RunOrder: 7 }),
Match.objectLike({ Name: 'AnotherStack-Stack.Deploy', RunOrder: 8 }),
Match.objectLike({ Name: 'SkipCheckStack-Stack.Prepare', RunOrder: 9 }),
Match.objectLike({ Name: 'SkipCheckStack-Stack.Deploy', RunOrder: 10 }),
],
Name: 'StageSecurityCheckStack',
},
],
});
}
});
behavior('confirmBroadeningPermissions option at addApplication runs security check only on selected application', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk');
const noSecurityStage = pipeline.addApplicationStage(new OneStackApp(app, 'NoSecurityCheckStack'));
noSecurityStage.addApplication(new OneStackApp(app, 'EnableCheckStack'), { confirmBroadeningPermissions: true });
THEN_codePipelineExpectation();
});
// For the modern API, there is no inheritance
suite.doesNotApply.modern();
function THEN_codePipelineExpectation() {
Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodePipeline::Pipeline', {
Stages: [
{
Actions: [Match.objectLike({ Name: 'GitHub', RunOrder: 1 })],
Name: 'Source',
},
{
Actions: [Match.objectLike({ Name: 'Synth', RunOrder: 1 })],
Name: 'Build',
},
{
Actions: [Match.objectLike({ Name: 'SelfMutate', RunOrder: 1 })],
Name: 'UpdatePipeline',
},
{
Actions: [
Match.objectLike({ Name: 'EnableCheckStackSecurityCheck', RunOrder: 3 }),
Match.objectLike({ Name: 'EnableCheckStackManualApproval', RunOrder: 4 }),
Match.objectLike({ Name: 'Stack.Prepare', RunOrder: 1 }),
Match.objectLike({ Name: 'Stack.Deploy', RunOrder: 2 }),
Match.objectLike({ Name: 'EnableCheckStack-Stack.Prepare', RunOrder: 5 }),
Match.objectLike({ Name: 'EnableCheckStack-Stack.Deploy', RunOrder: 6 }),
],
Name: 'NoSecurityCheckStack',
},
],
});
}
});
behavior('confirmBroadeningPermissions and notification topic options generates the right resources', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk');
const topic = new Topic(pipelineStack, 'NotificationTopic');
pipeline.addApplicationStage(new OneStackApp(app, 'MyStack'), {
confirmBroadeningPermissions: true,
securityNotificationTopic: topic,
});
THEN_codePipelineExpectation();
});
suite.modern(() => {
const pipeline = new ModernTestGitHubNpmPipeline(pipelineStack, 'Cdk');
const topic = new Topic(pipelineStack, 'NotificationTopic');
const stage = new OneStackApp(app, 'MyStack');
pipeline.addStage(stage, {
pre: [
new cdkp.ConfirmPermissionsBroadening('Approve', {
stage,
notificationTopic: topic,
}),
],
});
THEN_codePipelineExpectation();
});
function THEN_codePipelineExpectation() {
Template.fromStack(pipelineStack).resourceCountIs('AWS::SNS::Topic', 1);
Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodePipeline::Pipeline', {
Stages: Match.arrayWith([
{
Name: 'MyStack',
Actions: [
Match.objectLike({
Configuration: {
ProjectName: { Ref: stringLike('*SecurityCheck*') },
EnvironmentVariables: {
'Fn::Join': ['', [
stringLike('*'),
{ Ref: 'NotificationTopicEB7A0DF1' },
stringLike('*'),
]],
},
},
Name: stringLike('*Check'),
Namespace: stringLike('*'),
RunOrder: 1,
}),
Match.objectLike({
Configuration: {
CustomData: stringLike('#{*.MESSAGE}'),
ExternalEntityLink: stringLike('#{*.LINK}'),
},
Name: stringLike('*Approv*'),
RunOrder: 2,
}),
Match.objectLike({ Name: 'Stack.Prepare', RunOrder: 3 }),
Match.objectLike({ Name: 'Stack.Deploy', RunOrder: 4 }),
],
},
]),
});
}
});
behavior('Stages declared outside the pipeline create their own ApplicationSecurityCheck', (suite) => {
suite.legacy(() => {
const pipeline = new LegacyTestGitHubNpmPipeline(pipelineStack, 'Cdk');
const pipelineStage = pipeline.codePipeline.addStage({
stageName: 'UnattachedStage',
});
const unattachedStage = new cdkp.CdkStage(pipelineStack, 'UnattachedStage', {
stageName: 'UnattachedStage',
pipelineStage,
cloudAssemblyArtifact: pipeline.cloudAssemblyArtifact,
host: {
publishAsset: () => undefined,
stackOutputArtifact: () => undefined,
},
});
unattachedStage.addApplication(new OneStackApp(app, 'UnattachedStage'), {
confirmBroadeningPermissions: true,
});
THEN_codePipelineExpectation();
});
// Not a valid use of the modern API
suite.doesNotApply.modern();
function THEN_codePipelineExpectation() {
Template.fromStack(pipelineStack).resourceCountIs('AWS::Lambda::Function', 1);
// 1 for github build, 1 for synth stage, and 1 for the application security check
Template.fromStack(pipelineStack).resourceCountIs('AWS::CodeBuild::Project', 3);
Template.fromStack(pipelineStack).hasResourceProperties('AWS::CodePipeline::Pipeline', {
Tags: [
{
Key: 'SECURITY_CHECK',
Value: 'ALLOW_APPROVE',
},
],
Stages: [
Match.objectLike({ Name: 'Source' }),
Match.objectLike({ Name: 'Build' }),
Match.objectLike({ Name: 'UpdatePipeline' }),
{
Actions: [
Match.objectLike({
Configuration: {
ProjectName: { Ref: 'UnattachedStageStageApplicationSecurityCheckCDKSecurityCheckADCE795B' },
},
Name: 'UnattachedStageSecurityCheck',
RunOrder: 1,
}),
Match.objectLike({
Configuration: {
CustomData: '#{UnattachedStageSecurityCheck.MESSAGE}',
ExternalEntityLink: '#{UnattachedStageSecurityCheck.LINK}',
},
Name: 'UnattachedStageManualApproval',
RunOrder: 2,
}),
Match.objectLike({ Name: 'Stack.Prepare', RunOrder: 3 }),
Match.objectLike({ Name: 'Stack.Deploy', RunOrder: 4 }),
],
Name: 'UnattachedStage',
},
],
});
}
}); | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import { CodeGuruReviewerClient } from "./CodeGuruReviewerClient";
import {
AssociateRepositoryCommand,
AssociateRepositoryCommandInput,
AssociateRepositoryCommandOutput,
} from "./commands/AssociateRepositoryCommand";
import {
CreateCodeReviewCommand,
CreateCodeReviewCommandInput,
CreateCodeReviewCommandOutput,
} from "./commands/CreateCodeReviewCommand";
import {
DescribeCodeReviewCommand,
DescribeCodeReviewCommandInput,
DescribeCodeReviewCommandOutput,
} from "./commands/DescribeCodeReviewCommand";
import {
DescribeRecommendationFeedbackCommand,
DescribeRecommendationFeedbackCommandInput,
DescribeRecommendationFeedbackCommandOutput,
} from "./commands/DescribeRecommendationFeedbackCommand";
import {
DescribeRepositoryAssociationCommand,
DescribeRepositoryAssociationCommandInput,
DescribeRepositoryAssociationCommandOutput,
} from "./commands/DescribeRepositoryAssociationCommand";
import {
DisassociateRepositoryCommand,
DisassociateRepositoryCommandInput,
DisassociateRepositoryCommandOutput,
} from "./commands/DisassociateRepositoryCommand";
import {
ListCodeReviewsCommand,
ListCodeReviewsCommandInput,
ListCodeReviewsCommandOutput,
} from "./commands/ListCodeReviewsCommand";
import {
ListRecommendationFeedbackCommand,
ListRecommendationFeedbackCommandInput,
ListRecommendationFeedbackCommandOutput,
} from "./commands/ListRecommendationFeedbackCommand";
import {
ListRecommendationsCommand,
ListRecommendationsCommandInput,
ListRecommendationsCommandOutput,
} from "./commands/ListRecommendationsCommand";
import {
ListRepositoryAssociationsCommand,
ListRepositoryAssociationsCommandInput,
ListRepositoryAssociationsCommandOutput,
} from "./commands/ListRepositoryAssociationsCommand";
import {
ListTagsForResourceCommand,
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import {
PutRecommendationFeedbackCommand,
PutRecommendationFeedbackCommandInput,
PutRecommendationFeedbackCommandOutput,
} from "./commands/PutRecommendationFeedbackCommand";
import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
UntagResourceCommand,
UntagResourceCommandInput,
UntagResourceCommandOutput,
} from "./commands/UntagResourceCommand";
/**
* <p>This section provides documentation for the Amazon CodeGuru Reviewer API operations. CodeGuru Reviewer is a service
* that uses program analysis and machine learning to detect potential defects that are difficult for developers to find and recommends
* fixes in your Java and Python code.</p>
*
* <p>By proactively detecting and providing recommendations for addressing code defects and implementing best practices, CodeGuru Reviewer
* improves the overall quality and maintainability of your code base during the code review stage. For more information about CodeGuru Reviewer, see the
* <i>
* <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/welcome.html">Amazon CodeGuru Reviewer User Guide</a>.</i>
* </p>
*
* <p>
* To improve the security of your CodeGuru Reviewer API calls, you can establish a private connection between your VPC and CodeGuru Reviewer by
* creating an <i>interface VPC endpoint</i>. For more information, see
* <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/vpc-interface-endpoints.html">CodeGuru Reviewer and interface
* VPC endpoints (Amazon Web Services PrivateLink)</a> in the <i>Amazon CodeGuru Reviewer User Guide</i>.
* </p>
*/
export class CodeGuruReviewer extends CodeGuruReviewerClient {
/**
* <p>
* Use to associate an Amazon Web Services CodeCommit repository or a repostory managed by
* Amazon Web Services CodeStar Connections with Amazon CodeGuru Reviewer. When you associate a
* repository, CodeGuru Reviewer reviews source code changes in the repository's pull requests and provides
* automatic recommendations. You can view recommendations using the CodeGuru Reviewer console. For more information, see
* <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/recommendations.html">Recommendations in
* Amazon CodeGuru Reviewer</a> in the <i>Amazon CodeGuru Reviewer User Guide.</i>
* </p>
*
* <p>If you associate a CodeCommit or S3 repository, it must be in the same
* Amazon Web Services Region and Amazon Web Services account where its CodeGuru Reviewer code reviews are configured.</p>
*
* <p>Bitbucket and GitHub Enterprise Server repositories are managed by Amazon Web Services CodeStar
* Connections to connect to CodeGuru Reviewer. For more information, see <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/getting-started-associate-repository.html">Associate a repository</a> in
* the <i>Amazon CodeGuru Reviewer User Guide.</i>
* </p>
*
* <note>
* <p>
* You cannot use the CodeGuru Reviewer SDK or the Amazon Web Services CLI to associate a GitHub repository with Amazon CodeGuru Reviewer. To associate
* a GitHub repository, use the console. For more information, see
* <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/getting-started-with-guru.html">Getting
* started with CodeGuru Reviewer</a> in the <i>CodeGuru Reviewer User Guide.</i>
* </p>
* </note>
*/
public associateRepository(
args: AssociateRepositoryCommandInput,
options?: __HttpHandlerOptions
): Promise<AssociateRepositoryCommandOutput>;
public associateRepository(
args: AssociateRepositoryCommandInput,
cb: (err: any, data?: AssociateRepositoryCommandOutput) => void
): void;
public associateRepository(
args: AssociateRepositoryCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AssociateRepositoryCommandOutput) => void
): void;
public associateRepository(
args: AssociateRepositoryCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AssociateRepositoryCommandOutput) => void),
cb?: (err: any, data?: AssociateRepositoryCommandOutput) => void
): Promise<AssociateRepositoryCommandOutput> | void {
const command = new AssociateRepositoryCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Use to create a code review with a <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_CodeReviewType.html">
* <code>CodeReviewType</code>
* </a>
* of <code>RepositoryAnalysis</code>. This type of code review analyzes all code under a specified branch in an associated repository.
* <code>PullRequest</code> code reviews are automatically triggered by a pull request.
* </p>
*/
public createCodeReview(
args: CreateCodeReviewCommandInput,
options?: __HttpHandlerOptions
): Promise<CreateCodeReviewCommandOutput>;
public createCodeReview(
args: CreateCodeReviewCommandInput,
cb: (err: any, data?: CreateCodeReviewCommandOutput) => void
): void;
public createCodeReview(
args: CreateCodeReviewCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CreateCodeReviewCommandOutput) => void
): void;
public createCodeReview(
args: CreateCodeReviewCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateCodeReviewCommandOutput) => void),
cb?: (err: any, data?: CreateCodeReviewCommandOutput) => void
): Promise<CreateCodeReviewCommandOutput> | void {
const command = new CreateCodeReviewCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p> Returns the metadata associated with the code review along with its status.</p>
*/
public describeCodeReview(
args: DescribeCodeReviewCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeCodeReviewCommandOutput>;
public describeCodeReview(
args: DescribeCodeReviewCommandInput,
cb: (err: any, data?: DescribeCodeReviewCommandOutput) => void
): void;
public describeCodeReview(
args: DescribeCodeReviewCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeCodeReviewCommandOutput) => void
): void;
public describeCodeReview(
args: DescribeCodeReviewCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeCodeReviewCommandOutput) => void),
cb?: (err: any, data?: DescribeCodeReviewCommandOutput) => void
): Promise<DescribeCodeReviewCommandOutput> | void {
const command = new DescribeCodeReviewCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Describes the customer feedback for a CodeGuru Reviewer recommendation.
* </p>
*/
public describeRecommendationFeedback(
args: DescribeRecommendationFeedbackCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeRecommendationFeedbackCommandOutput>;
public describeRecommendationFeedback(
args: DescribeRecommendationFeedbackCommandInput,
cb: (err: any, data?: DescribeRecommendationFeedbackCommandOutput) => void
): void;
public describeRecommendationFeedback(
args: DescribeRecommendationFeedbackCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeRecommendationFeedbackCommandOutput) => void
): void;
public describeRecommendationFeedback(
args: DescribeRecommendationFeedbackCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeRecommendationFeedbackCommandOutput) => void),
cb?: (err: any, data?: DescribeRecommendationFeedbackCommandOutput) => void
): Promise<DescribeRecommendationFeedbackCommandOutput> | void {
const command = new DescribeRecommendationFeedbackCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Returns a <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_RepositoryAssociation.html">
* <code>RepositoryAssociation</code>
* </a> object
* that contains information about the requested repository association.
* </p>
*/
public describeRepositoryAssociation(
args: DescribeRepositoryAssociationCommandInput,
options?: __HttpHandlerOptions
): Promise<DescribeRepositoryAssociationCommandOutput>;
public describeRepositoryAssociation(
args: DescribeRepositoryAssociationCommandInput,
cb: (err: any, data?: DescribeRepositoryAssociationCommandOutput) => void
): void;
public describeRepositoryAssociation(
args: DescribeRepositoryAssociationCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DescribeRepositoryAssociationCommandOutput) => void
): void;
public describeRepositoryAssociation(
args: DescribeRepositoryAssociationCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeRepositoryAssociationCommandOutput) => void),
cb?: (err: any, data?: DescribeRepositoryAssociationCommandOutput) => void
): Promise<DescribeRepositoryAssociationCommandOutput> | void {
const command = new DescribeRepositoryAssociationCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes the association between Amazon CodeGuru Reviewer and a repository.</p>
*/
public disassociateRepository(
args: DisassociateRepositoryCommandInput,
options?: __HttpHandlerOptions
): Promise<DisassociateRepositoryCommandOutput>;
public disassociateRepository(
args: DisassociateRepositoryCommandInput,
cb: (err: any, data?: DisassociateRepositoryCommandOutput) => void
): void;
public disassociateRepository(
args: DisassociateRepositoryCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DisassociateRepositoryCommandOutput) => void
): void;
public disassociateRepository(
args: DisassociateRepositoryCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisassociateRepositoryCommandOutput) => void),
cb?: (err: any, data?: DisassociateRepositoryCommandOutput) => void
): Promise<DisassociateRepositoryCommandOutput> | void {
const command = new DisassociateRepositoryCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Lists all the code reviews that the customer has created in the past 90 days.
* </p>
*/
public listCodeReviews(
args: ListCodeReviewsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListCodeReviewsCommandOutput>;
public listCodeReviews(
args: ListCodeReviewsCommandInput,
cb: (err: any, data?: ListCodeReviewsCommandOutput) => void
): void;
public listCodeReviews(
args: ListCodeReviewsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListCodeReviewsCommandOutput) => void
): void;
public listCodeReviews(
args: ListCodeReviewsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListCodeReviewsCommandOutput) => void),
cb?: (err: any, data?: ListCodeReviewsCommandOutput) => void
): Promise<ListCodeReviewsCommandOutput> | void {
const command = new ListCodeReviewsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Returns a list of
* <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_RecommendationFeedbackSummary.html">
* <code>RecommendationFeedbackSummary</code>
* </a>
* objects that contain customer recommendation feedback for all CodeGuru Reviewer users.
* </p>
*/
public listRecommendationFeedback(
args: ListRecommendationFeedbackCommandInput,
options?: __HttpHandlerOptions
): Promise<ListRecommendationFeedbackCommandOutput>;
public listRecommendationFeedback(
args: ListRecommendationFeedbackCommandInput,
cb: (err: any, data?: ListRecommendationFeedbackCommandOutput) => void
): void;
public listRecommendationFeedback(
args: ListRecommendationFeedbackCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListRecommendationFeedbackCommandOutput) => void
): void;
public listRecommendationFeedback(
args: ListRecommendationFeedbackCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListRecommendationFeedbackCommandOutput) => void),
cb?: (err: any, data?: ListRecommendationFeedbackCommandOutput) => void
): Promise<ListRecommendationFeedbackCommandOutput> | void {
const command = new ListRecommendationFeedbackCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Returns the list of all recommendations for a completed code review.
* </p>
*/
public listRecommendations(
args: ListRecommendationsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListRecommendationsCommandOutput>;
public listRecommendations(
args: ListRecommendationsCommandInput,
cb: (err: any, data?: ListRecommendationsCommandOutput) => void
): void;
public listRecommendations(
args: ListRecommendationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListRecommendationsCommandOutput) => void
): void;
public listRecommendations(
args: ListRecommendationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListRecommendationsCommandOutput) => void),
cb?: (err: any, data?: ListRecommendationsCommandOutput) => void
): Promise<ListRecommendationsCommandOutput> | void {
const command = new ListRecommendationsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Returns a list of <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_RepositoryAssociationSummary.html">
* <code>RepositoryAssociationSummary</code>
* </a> objects that
* contain summary information about a repository association. You can filter the returned list by
* <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_RepositoryAssociationSummary.html#reviewer-Type-RepositoryAssociationSummary-ProviderType">
* <code>ProviderType</code>
* </a>,
* <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_RepositoryAssociationSummary.html#reviewer-Type-RepositoryAssociationSummary-Name">
* <code>Name</code>
* </a>,
* <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_RepositoryAssociationSummary.html#reviewer-Type-RepositoryAssociationSummary-State">
* <code>State</code>
* </a>, and
* <a href="https://docs.aws.amazon.com/codeguru/latest/reviewer-api/API_RepositoryAssociationSummary.html#reviewer-Type-RepositoryAssociationSummary-Owner">
* <code>Owner</code>
* </a>.
* </p>
*/
public listRepositoryAssociations(
args: ListRepositoryAssociationsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListRepositoryAssociationsCommandOutput>;
public listRepositoryAssociations(
args: ListRepositoryAssociationsCommandInput,
cb: (err: any, data?: ListRepositoryAssociationsCommandOutput) => void
): void;
public listRepositoryAssociations(
args: ListRepositoryAssociationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListRepositoryAssociationsCommandOutput) => void
): void;
public listRepositoryAssociations(
args: ListRepositoryAssociationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListRepositoryAssociationsCommandOutput) => void),
cb?: (err: any, data?: ListRepositoryAssociationsCommandOutput) => void
): Promise<ListRepositoryAssociationsCommandOutput> | void {
const command = new ListRepositoryAssociationsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns the list of tags associated with an associated repository resource.</p>
*/
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTagsForResourceCommandOutput>;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTagsForResourceCommandOutput) => void
): void;
public listTagsForResource(
args: ListTagsForResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void),
cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void
): Promise<ListTagsForResourceCommandOutput> | void {
const command = new ListTagsForResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>
* Stores customer feedback for a CodeGuru Reviewer recommendation. When this API is called again with different reactions the previous feedback is overwritten.
* </p>
*/
public putRecommendationFeedback(
args: PutRecommendationFeedbackCommandInput,
options?: __HttpHandlerOptions
): Promise<PutRecommendationFeedbackCommandOutput>;
public putRecommendationFeedback(
args: PutRecommendationFeedbackCommandInput,
cb: (err: any, data?: PutRecommendationFeedbackCommandOutput) => void
): void;
public putRecommendationFeedback(
args: PutRecommendationFeedbackCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: PutRecommendationFeedbackCommandOutput) => void
): void;
public putRecommendationFeedback(
args: PutRecommendationFeedbackCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutRecommendationFeedbackCommandOutput) => void),
cb?: (err: any, data?: PutRecommendationFeedbackCommandOutput) => void
): Promise<PutRecommendationFeedbackCommandOutput> | void {
const command = new PutRecommendationFeedbackCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Adds one or more tags to an associated repository.</p>
*/
public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>;
public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void;
public tagResource(
args: TagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TagResourceCommandOutput) => void
): void;
public tagResource(
args: TagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void),
cb?: (err: any, data?: TagResourceCommandOutput) => void
): Promise<TagResourceCommandOutput> | void {
const command = new TagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Removes a tag from an associated repository.</p>
*/
public untagResource(
args: UntagResourceCommandInput,
options?: __HttpHandlerOptions
): Promise<UntagResourceCommandOutput>;
public untagResource(
args: UntagResourceCommandInput,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UntagResourceCommandOutput) => void
): void;
public untagResource(
args: UntagResourceCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void),
cb?: (err: any, data?: UntagResourceCommandOutput) => void
): Promise<UntagResourceCommandOutput> | void {
const command = new UntagResourceCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
import { EventEmitter } from "events";
interface KeyState {
isDown: boolean;
wasJustPressed: boolean;
wasJustAutoRepeated: boolean;
wasJustReleased: boolean;
}
interface MouseButtonState {
isDown: boolean;
doubleClicked: boolean;
wasJustPressed: boolean;
wasJustReleased: boolean;
}
interface TouchState {
isDown: boolean;
wasStarted: boolean;
wasEnded: boolean;
position: { x: number; y: number; };
}
interface GamepadButtonState {
isDown: boolean;
wasJustPressed: boolean;
wasJustReleased: boolean;
value: number;
}
interface GamepadAxisState {
wasPositiveJustPressed: boolean;
wasPositiveJustAutoRepeated: boolean;
wasPositiveJustReleased: boolean;
wasNegativeJustPressed: boolean;
wasNegativeJustAutoRepeated: boolean;
wasNegativeJustReleased: boolean;
value: number;
}
interface GamepadAutoRepeat {
axis: number;
positive: boolean;
time: number;
}
export default class Input extends EventEmitter {
static maxTouches = 10;
canvas: HTMLCanvasElement;
mouseButtons: MouseButtonState[] = [];
mouseButtonsDown: boolean[] = [];
mousePosition = { x: 0, y: 0 };
newMousePosition: { x: number; y: number; };
mouseDelta = { x: 0, y: 0 };
newMouseDelta = { x: 0, y: 0 };
newScrollDelta: number;
touches: TouchState[] = [];
touchesDown: boolean[] = [];
keyboardButtons: KeyState[] = [];
keyboardButtonsDown: boolean[] = [];
autoRepeatedKey: number = null;
textEntered = "";
newTextEntered = "";
gamepadsButtons: GamepadButtonState[][] = [];
gamepadsAxes: GamepadAxisState[][] = [];
gamepadsAutoRepeats: GamepadAutoRepeat[] = [];
gamepadAxisDeadZone = 0.25;
gamepadAxisAutoRepeatDelayMs = 500;
gamepadAxisAutoRepeatRateMs = 33;
exited = false;
private wantsPointerLock = false;
private wantsFullscreen = false;
private wasPointerLocked = false;
private wasFullscreen = false;
constructor(canvas: HTMLCanvasElement, options: { enableOnExit?: boolean } = {}) {
super();
if (options == null) options = {};
this.canvas = canvas;
// Mouse
this.canvas.addEventListener("mousemove", this.onMouseMove);
this.canvas.addEventListener("mousedown", this.onMouseDown);
this.canvas.addEventListener("dblclick", this.onMouseDblClick);
document.addEventListener("mouseup", this.onMouseUp);
this.canvas.addEventListener("contextmenu", this.onContextMenu);
this.canvas.addEventListener("DOMMouseScroll", this.onMouseWheel);
this.canvas.addEventListener("mousewheel", this.onMouseWheel);
const compatDoc = document as any;
if ("onpointerlockchange" in compatDoc) compatDoc.addEventListener("pointerlockchange", this.onPointerLockChange, false);
else if ("onmozpointerlockchange" in compatDoc) compatDoc.addEventListener("mozpointerlockchange", this.onPointerLockChange, false);
else if ("onwebkitpointerlockchange" in compatDoc) compatDoc.addEventListener("webkitpointerlockchange", this.onPointerLockChange, false);
if ("onpointerlockerror" in compatDoc) compatDoc.addEventListener("pointerlockerror", this.onPointerLockError, false);
else if ("onmozpointerlockerror" in compatDoc) compatDoc.addEventListener("mozpointerlockerror", this.onPointerLockError, false);
else if ("onwebkitpointerlockerror" in compatDoc) compatDoc.addEventListener("webkitpointerlockerror", this.onPointerLockError, false);
if ("onfullscreenchange" in compatDoc) compatDoc.addEventListener("fullscreenchange", this.onFullscreenChange, false);
else if ("onmozfullscreenchange" in compatDoc) compatDoc.addEventListener("mozfullscreenchange", this.onFullscreenChange, false);
else if ("onwebkitfullscreenchange" in compatDoc) compatDoc.addEventListener("webkitfullscreenchange", this.onFullscreenChange, false);
if ("onfullscreenerror" in compatDoc) compatDoc.addEventListener("fullscreenerror", this.onFullscreenError, false);
else if ("onmozfullscreenerror" in compatDoc) compatDoc.addEventListener("mozfullscreenerror", this.onFullscreenError, false);
else if ("onwebkitfullscreenerror" in compatDoc) compatDoc.addEventListener("webkitfullscreenerror", this.onFullscreenError, false);
// Touch
this.canvas.addEventListener("touchstart", this.onTouchStart);
this.canvas.addEventListener("touchend", this.onTouchEnd);
this.canvas.addEventListener("touchmove", this.onTouchMove);
// Keyboard
this.canvas.addEventListener("keydown", this.onKeyDown);
this.canvas.addEventListener("keypress", this.onKeyPress);
document.addEventListener("keyup", this.onKeyUp);
// Gamepad
for (let i = 0; i < 4; i++) {
this.gamepadsButtons[i] = [];
this.gamepadsAxes[i] = [];
this.gamepadsAutoRepeats[i] = null;
}
// On exit
if (options.enableOnExit) {
window.onbeforeunload = this.doExitCallback;
}
window.addEventListener("blur", this.onBlur);
this.reset();
}
destroy() {
this.removeAllListeners();
this.canvas.removeEventListener("mousemove", this.onMouseMove);
this.canvas.removeEventListener("mousedown", this.onMouseDown);
document.removeEventListener("mouseup", this.onMouseUp);
this.canvas.removeEventListener("contextmenu", this.onContextMenu);
this.canvas.removeEventListener("DOMMouseScroll", this.onMouseWheel);
this.canvas.removeEventListener("mousewheel", this.onMouseWheel);
const compatDoc = document as any;
if ("onpointerlockchange" in compatDoc) compatDoc.removeEventListener("pointerlockchange", this.onPointerLockChange, false);
else if ("onmozpointerlockchange" in compatDoc) compatDoc.removeEventListener("mozpointerlockchange", this.onPointerLockChange, false);
else if ("onwebkitpointerlockchange" in compatDoc) compatDoc.removeEventListener("webkitpointerlockchange", this.onPointerLockChange, false);
if ("onpointerlockerror" in compatDoc) compatDoc.removeEventListener("pointerlockerror", this.onPointerLockError, false);
else if ("onmozpointerlockerror" in compatDoc) compatDoc.removeEventListener("mozpointerlockerror", this.onPointerLockError, false);
else if ("onwebkitpointerlockerror" in compatDoc) compatDoc.removeEventListener("webkitpointerlockerror", this.onPointerLockError, false);
if ("onfullscreenchange" in compatDoc) compatDoc.removeEventListener("fullscreenchange", this.onFullscreenChange, false);
else if ("onmozfullscreenchange" in compatDoc) compatDoc.removeEventListener("mozfullscreenchange", this.onFullscreenChange, false);
else if ("onwebkitfullscreenchange" in compatDoc) compatDoc.removeEventListener("webkitfullscreenchange", this.onFullscreenChange, false);
if ("onfullscreenerror" in compatDoc) compatDoc.removeEventListener("fullscreenerror", this.onFullscreenError, false);
else if ("onmozfullscreenerror" in compatDoc) compatDoc.removeEventListener("mozfullscreenerror", this.onFullscreenError, false);
else if ("onwebkitfullscreenerror" in compatDoc) compatDoc.removeEventListener("webkitfullscreenerror", this.onFullscreenError, false);
this.canvas.removeEventListener("touchstart", this.onTouchStart);
this.canvas.removeEventListener("touchend", this.onTouchEnd);
this.canvas.removeEventListener("touchmove", this.onTouchMove);
this.canvas.removeEventListener("keydown", this.onKeyDown);
this.canvas.removeEventListener("keypress", this.onKeyPress);
document.removeEventListener("keyup", this.onKeyUp);
window.removeEventListener("blur", this.onBlur);
}
reset() {
// Mouse
this.newScrollDelta = 0;
for (let i = 0; i <= 6; i++) {
this.mouseButtons[i] = { isDown: false, doubleClicked: false, wasJustPressed: false, wasJustReleased: false };
this.mouseButtonsDown[i] = false;
}
this.mousePosition.x = 0;
this.mousePosition.y = 0;
this.newMousePosition = null;
this.mouseDelta.x = 0;
this.mouseDelta.y = 0;
this.newMouseDelta.x = 0;
this.newMouseDelta.y = 0;
// Touch
for (let i = 0; i < Input.maxTouches; i++) {
this.touches[i] = { isDown: false, wasStarted: false, wasEnded: false, position: { x: 0, y: 0} };
this.touchesDown[i] = false;
}
// Keyboard
for (let i = 0; i <= 255; i++) {
this.keyboardButtons[i] = { isDown: false, wasJustPressed: false, wasJustAutoRepeated: false, wasJustReleased: false };
this.keyboardButtonsDown[i] = false;
}
this.textEntered = "";
this.newTextEntered = "";
// Gamepads
for (let i = 0; i < 4; i++) {
for (let button = 0; button < 16; button++) {
this.gamepadsButtons[i][button] = {
isDown: false,
wasJustPressed: false,
wasJustReleased: false,
value: 0
};
}
for (let axes = 0; axes < 4; axes++) {
this.gamepadsAxes[i][axes] = {
wasPositiveJustPressed: false,
wasPositiveJustAutoRepeated: false,
wasPositiveJustReleased: false,
wasNegativeJustPressed: false,
wasNegativeJustAutoRepeated: false,
wasNegativeJustReleased: false,
value: 0
};
}
}
}
lockMouse() {
this.wantsPointerLock = true;
this.newMouseDelta.x = 0;
this.newMouseDelta.y = 0;
}
unlockMouse() {
this.wantsPointerLock = false;
this.wasPointerLocked = false;
if (!this._isPointerLocked()) return;
if ((<any>document).exitPointerLock) (<any>document).exitPointerLock();
else if ((<any>document).webkitExitPointerLock) (<any>document).webkitExitPointerLock();
else if ((<any>document).mozExitPointerLock) (<any>document).mozExitPointerLock();
}
_isPointerLocked() {
return (<any>document).pointerLockElement === this.canvas ||
(<any>document).webkitPointerLockElement === this.canvas ||
(<any>document).mozPointerLockElement === this.canvas;
}
_doPointerLock() {
if ((<any>this.canvas).requestPointerLock) (<any>this.canvas).requestPointerLock();
else if ((<any>this.canvas).webkitRequestPointerLock) (<any>this.canvas).webkitRequestPointerLock();
else if ((<any>this.canvas).mozRequestPointerLock) (<any>this.canvas).mozRequestPointerLock();
}
private onPointerLockChange = () => {
const isPointerLocked = this._isPointerLocked();
if (this.wasPointerLocked !== isPointerLocked) {
this.emit("mouseLockStateChange", isPointerLocked ? "active" : "suspended");
this.wasPointerLocked = isPointerLocked;
}
}
private onPointerLockError = () => {
if (this.wasPointerLocked) {
this.emit("mouseLockStateChange", "suspended");
this.wasPointerLocked = false;
}
}
goFullscreen() { this.wantsFullscreen = true; }
exitFullscreen() {
this.wantsFullscreen = false;
this.wasFullscreen = false;
if (!this._isFullscreen()) return;
if ((document as any).exitFullscreen) (document as any).exitFullscreen();
else if ((document as any).webkitExitFullscreen) (document as any).webkitExitFullscreen();
else if ((document as any).mozCancelFullScreen) (document as any).mozCancelFullScreen();
}
_isFullscreen() {
return (document as any).fullscreenElement === this.canvas ||
(document as any).webkitFullscreenElement === this.canvas ||
(document as any).mozFullScreenElement === this.canvas;
}
_doGoFullscreen() {
if ((this.canvas as any).requestFullscreen) (this.canvas as any).requestFullscreen();
else if ((this.canvas as any).webkitRequestFullscreen) (this.canvas as any).webkitRequestFullscreen();
else if ((this.canvas as any).mozRequestFullScreen) (this.canvas as any).mozRequestFullScreen();
}
private onFullscreenChange = () => {
const isFullscreen = this._isFullscreen();
if (this.wasFullscreen !== isFullscreen) {
this.emit("fullscreenStateChange", isFullscreen ? "active" : "suspended");
this.wasFullscreen = isFullscreen;
}
}
private onFullscreenError = () => {
if (this.wasFullscreen) {
this.emit("fullscreenStateChange", "suspended");
this.wasFullscreen = false;
}
}
private onBlur = () => { this.reset(); };
private onMouseMove = (event: any) => {
event.preventDefault();
if (this.wantsPointerLock) {
if (this.wasPointerLocked) {
const delta = { x: 0, y: 0 };
if (event.movementX != null) { delta.x = event.movementX; delta.y = event.movementY; }
else if (event.webkitMovementX != null) { delta.x = event.webkitMovementX; delta.y = event.webkitMovementY; }
else if (event.mozMovementX == null) { delta.x = event.mozMovementX; delta.y = event.mozMovementY; }
this.newMouseDelta.x += delta.x;
this.newMouseDelta.y += delta.y;
}
} else {
const rect = event.target.getBoundingClientRect();
this.newMousePosition = { x: event.clientX - rect.left, y: event.clientY - rect.top };
}
}
private onMouseDown = (event: MouseEvent) => {
event.preventDefault();
this.canvas.focus();
this.mouseButtonsDown[event.button] = true;
if (this.wantsFullscreen && !this.wasFullscreen) this._doGoFullscreen();
if (this.wantsPointerLock && !this.wasPointerLocked) this._doPointerLock();
}
private onMouseUp = (event: MouseEvent) => {
if (this.mouseButtonsDown[event.button]) event.preventDefault();
this.mouseButtonsDown[event.button] = false;
if (this.wantsFullscreen && !this.wasFullscreen) this._doGoFullscreen();
if (this.wantsPointerLock && !this.wasPointerLocked) this._doPointerLock();
}
private onMouseDblClick = (event: MouseEvent) => {
event.preventDefault();
this.mouseButtons[event.button].doubleClicked = true;
}
private onContextMenu = (event: Event) => {
event.preventDefault();
}
private onMouseWheel = (event: MouseWheelEvent) => {
event.preventDefault();
this.newScrollDelta = ((event as any).wheelDelta > 0 || event.detail < 0) ? 1 : -1;
return false;
}
private onTouchStart = (event: any) => {
event.preventDefault();
const rect = event.target.getBoundingClientRect();
for (let i = 0; i < event.changedTouches.length; i++) {
const touch = event.changedTouches[i];
this.touches[touch.identifier].position.x = touch.clientX - rect.left;
this.touches[touch.identifier].position.y = touch.clientY - rect.top;
this.touchesDown[touch.identifier] = true;
if (touch.identifier === 0) {
this.newMousePosition = { x: touch.clientX - rect.left, y: touch.clientY - rect.top };
this.mouseButtonsDown[0] = true;
}
}
}
private onTouchEnd = (event: any) => {
event.preventDefault();
for (let i = 0; i < event.changedTouches.length; i++) {
const touch = event.changedTouches[i];
this.touchesDown[touch.identifier] = false;
if (touch.identifier === 0) this.mouseButtonsDown[0] = false;
}
}
private onTouchMove = (event: any) => {
event.preventDefault();
const rect = event.target.getBoundingClientRect();
for (let i = 0; i < event.changedTouches.length; i++) {
const touch = event.changedTouches[i];
this.touches[touch.identifier].position.x = touch.clientX - rect.left;
this.touches[touch.identifier].position.y = touch.clientY - rect.top;
if (touch.identifier === 0) this.newMousePosition = { x: touch.clientX - rect.left, y: touch.clientY - rect.top };
}
}
// TODO: stop using keyCode when KeyboardEvent.code is supported more widely
// See https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.code
private onKeyDown = (event: KeyboardEvent) => {
// NOTE: Key codes in range 33-47 are Page Up/Down, Home/End, arrow keys, Insert/Delete, etc.
let isControlKey = event.keyCode < 48 && event.keyCode !== 32;
if (isControlKey) event.preventDefault();
if (!this.keyboardButtonsDown[event.keyCode]) this.keyboardButtonsDown[event.keyCode] = true;
else this.autoRepeatedKey = event.keyCode;
return !isControlKey;
}
private onKeyPress = (event: KeyboardEvent) => {
if (event.keyCode > 0 && event.keyCode < 32) return;
if (event.char != null) this.newTextEntered += event.char;
else if (event.charCode !== 0) this.newTextEntered += String.fromCharCode(event.charCode);
else this.newTextEntered += String.fromCharCode(event.keyCode);
}
private onKeyUp = (event: KeyboardEvent) => {
this.keyboardButtonsDown[event.keyCode] = false;
}
private doExitCallback = () => {
// NOTE: It seems window.onbeforeunload might be called twice
// in some circumstances so we check if the callback was cleared already
// http://stackoverflow.com/questions/8711393/onbeforeunload-fires-twice
if (!this.exited) this.emit("exit");
this.exited = true;
}
update() {
this.mouseButtonsDown[5] = this.newScrollDelta > 0;
this.mouseButtonsDown[6] = this.newScrollDelta < 0;
if (this.newScrollDelta !== 0) this.newScrollDelta = 0;
if (this.wantsPointerLock) {
this.mouseDelta.x = this.newMouseDelta.x;
this.mouseDelta.y = this.newMouseDelta.y;
this.newMouseDelta.x = 0;
this.newMouseDelta.y = 0;
} else if (this.newMousePosition != null) {
this.mouseDelta.x = this.newMousePosition.x - this.mousePosition.x;
this.mouseDelta.y = this.newMousePosition.y - this.mousePosition.y;
this.mousePosition.x = this.newMousePosition.x;
this.mousePosition.y = this.newMousePosition.y;
this.newMousePosition = null;
} else {
this.mouseDelta.x = 0;
this.mouseDelta.y = 0;
}
for (let i = 0; i < this.mouseButtons.length; i++) {
const mouseButton = this.mouseButtons[i];
const wasDown = mouseButton.isDown;
mouseButton.isDown = this.mouseButtonsDown[i];
mouseButton.wasJustPressed = !wasDown && mouseButton.isDown;
mouseButton.wasJustReleased = wasDown && !mouseButton.isDown;
}
for (let i = 0; i < this.touches.length; i++) {
const touch = this.touches[i];
const wasDown = touch.isDown;
touch.isDown = this.touchesDown[i];
touch.wasStarted = !wasDown && touch.isDown;
touch.wasEnded = wasDown && !touch.isDown;
}
for (let i = 0; i < this.keyboardButtons.length; i++) {
const keyboardButton = this.keyboardButtons[i];
const wasDown = keyboardButton.isDown;
keyboardButton.isDown = this.keyboardButtonsDown[i];
keyboardButton.wasJustPressed = !wasDown && keyboardButton.isDown;
keyboardButton.wasJustAutoRepeated = false;
keyboardButton.wasJustReleased = wasDown && !keyboardButton.isDown;
}
if (this.autoRepeatedKey != null) {
this.keyboardButtons[this.autoRepeatedKey].wasJustAutoRepeated = true;
this.autoRepeatedKey = null;
}
this.textEntered = this.newTextEntered;
this.newTextEntered = "";
const gamepads = (navigator.getGamepads != null) ? navigator.getGamepads() : null;
if (gamepads == null) return;
for (let index = 0; index < 4; index++) {
const gamepad = gamepads[index];
if (gamepad == null) continue;
for (let i = 0; i < this.gamepadsButtons[index].length; i++) {
if (gamepad.buttons[i] == null) continue;
const button = this.gamepadsButtons[index][i];
const wasDown = button.isDown;
button.isDown = gamepad.buttons[i].pressed;
button.value = gamepad.buttons[i].value;
button.wasJustPressed = !wasDown && button.isDown;
button.wasJustReleased = wasDown && !button.isDown;
}
const pressedValue = 0.5;
const now = Date.now();
for (let stick = 0; stick < 2; stick++) {
if (gamepad.axes[2 * stick] == null || gamepad.axes[2 * stick + 1] == null) continue;
const axisLength = Math.sqrt( Math.pow(Math.abs(gamepad.axes[2 * stick]), 2) + Math.pow(Math.abs(gamepad.axes[2 * stick + 1]), 2) );
const axes = [ this.gamepadsAxes[index][2 * stick], this.gamepadsAxes[index][2 * stick + 1] ];
const wasAxisDown = [
{ positive: axes[0].value > pressedValue, negative: axes[0].value < -pressedValue },
{ positive: axes[1].value > pressedValue, negative: axes[1].value < -pressedValue }
];
if (axisLength < this.gamepadAxisDeadZone) {
axes[0].value = 0;
axes[1].value = 0;
} else {
axes[0].value = gamepad.axes[2 * stick];
axes[1].value = gamepad.axes[2 * stick + 1];
}
const isAxisDown = [
{ positive: axes[0].value > pressedValue, negative: axes[0].value < -pressedValue },
{ positive: axes[1].value > pressedValue, negative: axes[1].value < -pressedValue }
];
axes[0].wasPositiveJustPressed = !wasAxisDown[0].positive && isAxisDown[0].positive;
axes[0].wasPositiveJustReleased = wasAxisDown[0].positive && !isAxisDown[0].positive;
axes[0].wasPositiveJustAutoRepeated = false;
axes[0].wasNegativeJustPressed = !wasAxisDown[0].negative && isAxisDown[0].negative;
axes[0].wasNegativeJustReleased = wasAxisDown[0].negative && !isAxisDown[0].negative;
axes[0].wasNegativeJustAutoRepeated = false;
axes[1].wasPositiveJustPressed = !wasAxisDown[1].positive && isAxisDown[1].positive;
axes[1].wasPositiveJustReleased = wasAxisDown[1].positive && !isAxisDown[1].positive;
axes[1].wasPositiveJustAutoRepeated = false;
axes[1].wasNegativeJustPressed = !wasAxisDown[1].negative && isAxisDown[1].negative;
axes[1].wasNegativeJustReleased = wasAxisDown[1].negative && !isAxisDown[1].negative;
axes[1].wasNegativeJustAutoRepeated = false;
let currentAutoRepeat = this.gamepadsAutoRepeats[index];
if (currentAutoRepeat != null) {
const axisIndex = currentAutoRepeat.axis - stick * 2;
if (axisIndex === 0 || axisIndex === 1) {
const autoRepeatedAxis = axes[axisIndex];
if ((currentAutoRepeat.positive && !isAxisDown[axisIndex].positive) ||
(!currentAutoRepeat.positive && !isAxisDown[axisIndex].negative)) {
// Auto-repeated axis has been released
currentAutoRepeat = this.gamepadsAutoRepeats[index] = null;
} else {
// Check for auto-repeat deadline
if (currentAutoRepeat.time <= now) {
if (currentAutoRepeat.positive) autoRepeatedAxis.wasPositiveJustAutoRepeated = true;
else autoRepeatedAxis.wasNegativeJustAutoRepeated = true;
currentAutoRepeat.time = now + this.gamepadAxisAutoRepeatRateMs;
}
}
}
}
let newAutoRepeat: GamepadAutoRepeat;
if (axes[0].wasPositiveJustPressed || axes[0].wasNegativeJustPressed) {
newAutoRepeat = { axis: stick * 2, positive: axes[0].wasPositiveJustPressed, time: now + this.gamepadAxisAutoRepeatDelayMs };
} else if (axes[1].wasPositiveJustPressed || axes[1].wasNegativeJustPressed) {
newAutoRepeat = { axis: stick * 2 + 1, positive: axes[1].wasPositiveJustPressed, time: now + this.gamepadAxisAutoRepeatDelayMs };
}
if (newAutoRepeat != null) {
if (currentAutoRepeat == null || currentAutoRepeat.axis !== newAutoRepeat.axis || currentAutoRepeat.positive !== newAutoRepeat.positive) {
this.gamepadsAutoRepeats[index] = newAutoRepeat;
}
}
}
}
}
}
// FIXME: KeyEvent isn't in lib.d.ts yet
if ((<any>global).window != null && (<any>window).KeyEvent == null) {
(<any>window).KeyEvent = {
DOM_VK_CANCEL: 3,
DOM_VK_HELP: 6,
DOM_VK_BACK_SPACE: 8,
DOM_VK_TAB: 9,
DOM_VK_CLEAR: 12,
DOM_VK_RETURN: 13,
DOM_VK_ENTER: 14,
DOM_VK_SHIFT: 16,
DOM_VK_CONTROL: 17,
DOM_VK_ALT: 18,
DOM_VK_PAUSE: 19,
DOM_VK_CAPS_LOCK: 20,
DOM_VK_ESCAPE: 27,
DOM_VK_SPACE: 32,
DOM_VK_PAGE_UP: 33,
DOM_VK_PAGE_DOWN: 34,
DOM_VK_END: 35,
DOM_VK_HOME: 36,
DOM_VK_LEFT: 37,
DOM_VK_UP: 38,
DOM_VK_RIGHT: 39,
DOM_VK_DOWN: 40,
DOM_VK_PRINTSCREEN: 44,
DOM_VK_INSERT: 45,
DOM_VK_DELETE: 46,
DOM_VK_0: 48,
DOM_VK_1: 49,
DOM_VK_2: 50,
DOM_VK_3: 51,
DOM_VK_4: 52,
DOM_VK_5: 53,
DOM_VK_6: 54,
DOM_VK_7: 55,
DOM_VK_8: 56,
DOM_VK_9: 57,
DOM_VK_SEMICOLON: 59,
DOM_VK_EQUALS: 61,
DOM_VK_A: 65,
DOM_VK_B: 66,
DOM_VK_C: 67,
DOM_VK_D: 68,
DOM_VK_E: 69,
DOM_VK_F: 70,
DOM_VK_G: 71,
DOM_VK_H: 72,
DOM_VK_I: 73,
DOM_VK_J: 74,
DOM_VK_K: 75,
DOM_VK_L: 76,
DOM_VK_M: 77,
DOM_VK_N: 78,
DOM_VK_O: 79,
DOM_VK_P: 80,
DOM_VK_Q: 81,
DOM_VK_R: 82,
DOM_VK_S: 83,
DOM_VK_T: 84,
DOM_VK_U: 85,
DOM_VK_V: 86,
DOM_VK_W: 87,
DOM_VK_X: 88,
DOM_VK_Y: 89,
DOM_VK_Z: 90,
DOM_VK_CONTEXT_MENU: 93,
DOM_VK_NUMPAD0: 96,
DOM_VK_NUMPAD1: 97,
DOM_VK_NUMPAD2: 98,
DOM_VK_NUMPAD3: 99,
DOM_VK_NUMPAD4: 100,
DOM_VK_NUMPAD5: 101,
DOM_VK_NUMPAD6: 102,
DOM_VK_NUMPAD7: 103,
DOM_VK_NUMPAD8: 104,
DOM_VK_NUMPAD9: 105,
DOM_VK_MULTIPLY: 106,
DOM_VK_ADD: 107,
DOM_VK_SEPARATOR: 108,
DOM_VK_SUBTRACT: 109,
DOM_VK_DECIMAL: 110,
DOM_VK_DIVIDE: 111,
DOM_VK_F1: 112,
DOM_VK_F2: 113,
DOM_VK_F3: 114,
DOM_VK_F4: 115,
DOM_VK_F5: 116,
DOM_VK_F6: 117,
DOM_VK_F7: 118,
DOM_VK_F8: 119,
DOM_VK_F9: 120,
DOM_VK_F10: 121,
DOM_VK_F11: 122,
DOM_VK_F12: 123,
DOM_VK_F13: 124,
DOM_VK_F14: 125,
DOM_VK_F15: 126,
DOM_VK_F16: 127,
DOM_VK_F17: 128,
DOM_VK_F18: 129,
DOM_VK_F19: 130,
DOM_VK_F20: 131,
DOM_VK_F21: 132,
DOM_VK_F22: 133,
DOM_VK_F23: 134,
DOM_VK_F24: 135,
DOM_VK_NUM_LOCK: 144,
DOM_VK_SCROLL_LOCK: 145,
DOM_VK_COMMA: 188,
DOM_VK_PERIOD: 190,
DOM_VK_SLASH: 191,
DOM_VK_BACK_QUOTE: 192,
DOM_VK_OPEN_BRACKET: 219,
DOM_VK_BACK_SLASH: 220,
DOM_VK_CLOSE_BRACKET: 221,
DOM_VK_QUOTE: 222,
DOM_VK_META: 224
};
} | the_stack |
import { assert, expect } from 'chai'
import 'mocha'
import * as semver from 'semver'
import { resolve } from 'path'
import { exec, fork } from 'child_process'
import * as pmx from '../src'
const launch = (fixture) => {
return fork(resolve(__dirname, fixture), [], {
execArgv: process.env.NYC_ROOT_ID ? process.execArgv : [ '-r', 'ts-node/register' ]
})
}
describe('API', function () {
this.timeout(10000)
describe('Notify', () => {
it('should receive data from notify', (done) => {
const child = launch('fixtures/apiNotifyChild.ts')
child.on('message', msg => {
if (msg.data.message === 'myNotify') {
expect(msg.data.message).to.equal('myNotify')
child.kill('SIGINT')
done()
}
})
})
})
describe('Metrics', () => {
it('should receive data from metric', (done) => {
const child = launch('fixtures/apiMetricsChild.ts')
child.on('message', res => {
if (res.type === 'axm:monitor') {
// both metrics aren't used
expect(res.data.hasOwnProperty('metric with spaces')).to.equal(false)
expect(res.data.hasOwnProperty('metric wi!th special chars % ///')).to.equal(false)
expect(res.data.hasOwnProperty('metricHistogram')).to.equal(true)
expect(res.data.hasOwnProperty('metricInline')).to.equal(true)
expect(res.data.hasOwnProperty('toto')).to.equal(true)
expect(res.data.metricHistogram.value).to.equal(10)
expect(res.data.metricHistogram.type).to.equal('metric/custom')
expect(res.data.metricInline.value).to.equal(11)
expect(res.data.toto.value).to.equal(42)
child.kill('SIGINT')
return done()
}
})
child.on('error', done)
})
})
describe('Actions', () => {
it('should receive data from action', (done) => {
const child = launch('fixtures/apiActionsChild')
child.on('message', res => {
if (res.type === 'axm:action' && res.data.action_name === 'testAction') {
child.send(res.data.action_name)
} else if (res.type === 'axm:reply') {
expect(res.data.action_name).to.equal('testAction')
expect(res.data.return.data).to.equal('testActionReply')
child.kill('SIGINT')
done()
}
})
})
it('should receive data from action with conf', (done) => {
const child = launch('fixtures/apiActionsJsonChild')
child.on('message', res => {
if (res.type === 'axm:action' && res.data.action_name === 'testActionWithConf') {
child.send(res.data.action_name)
} else if (res.type === 'axm:reply') {
expect(res.data.action_name).to.equal('testActionWithConf')
expect(res.data.return.data).to.equal('testActionWithConfReply')
child.kill('SIGINT')
done()
}
})
})
})
describe('Histogram', () => {
it('should return an histogram', () => {
// @ts-ignore
const firstWay = pmx.histogram('firstWay')
// @ts-ignore
const secondWay = pmx.histogram({
name: 'secondWay'
})
expect(firstWay.constructor.name).to.equal('Histogram')
expect(secondWay.constructor.name).to.equal('Histogram')
})
})
describe('Counter', () => {
it('should return a counter', () => {
// @ts-ignore old api
const firstWay = pmx.counter('firstWay')
const secondWay = pmx.counter({
name: 'secondWay'
})
expect(firstWay.constructor.name).to.equal('Counter')
expect(secondWay.constructor.name).to.equal('Counter')
})
})
describe('Meter', () => {
it('should return a counter', () => {
// @ts-ignore old api
const firstWay = pmx.meter('firstWay')
const secondWay = pmx.meter({
name: 'secondWay'
})
expect(firstWay.constructor.name).to.equal('Meter')
expect(secondWay.constructor.name).to.equal('Meter')
})
})
describe('Metric', () => {
it('should return an metric', () => {
// @ts-ignore old api
const firstWay = pmx.metric('firstWay')
const secondWay = pmx.metric({
name: 'secondWay'
})
expect(typeof firstWay.val === 'function').to.equal(true)
expect(typeof secondWay.val === 'function').to.equal(true)
})
})
describe('onExit', () => {
it.skip('should catch signals and launch callback', (done) => {
const child = launch('fixtures/apiOnExitChild')
child.on('message', res => {
if (res === 'callback') {
done()
}
})
setTimeout(function () {
child.kill('SIGINT')
}, 1000)
})
it('should return null cause no callback provided', () => {
// @ts-ignore what the fuck is that test
const fn = pmx.onExit()
expect(fn).to.equal(undefined)
})
it('should catch uncaught exception and launch callback', (done) => {
const child = launch('fixtures/apiOnExitExceptionChild')
child.on('message', res => {
if (res.type === 'process:exception') {
assert(!!res.data.message.match(/Cannot read property/))
}
if (res === 'callback') {
done()
}
})
})
})
describe('Compatibility', () => {
it('should return metrics object with clean keys', () => {
// @ts-ignore
const metrics = pmx.metrics([
{
name: 'metricHistogram',
type: 'histogram',
id: 'metric/custom'
},
{
name: 'metric with spaces',
type: 'histogram',
id: 'metric/custom'
},
{
name: 'metric wi!th special chars % ///',
type: 'histogram',
id: 'metric/custom'
},
{
name: 'metricFailure',
type: 'notExist'
}
])
expect(metrics[0].constructor.name === 'Histogram').to.equal(true)
expect(metrics[1].constructor.name === 'Histogram').to.equal(true)
expect(metrics[2].constructor.name === 'Histogram').to.equal(true)
expect(metrics[3].constructor.name === 'Object').to.equal(true)
expect(Object.keys(metrics).length).to.equal(4)
})
it('should receive data from event', (done) => {
const child = launch('fixtures/apiBackwardEventChild')
child.on('message', res => {
if (res.type === 'human:event') {
expect(res.data.__name).to.equal('myEvent')
expect(res.data.prop1).to.equal('value1')
child.kill('SIGINT')
done()
}
})
})
it('should receive data from expressErrorHandler', (done) => {
const child = launch('fixtures/apiBackwardExpressChild')
child.on('message', msg => {
if (msg === 'expressReady') {
const httpModule = require('http')
httpModule.get('http://localhost:3003/error')
} else if (msg.type === 'process:exception') {
expect(msg.data.message).to.equal('toto')
expect(msg.data.metadata.http.path).to.equal('/error')
expect(msg.data.metadata.http.method).to.equal('GET')
expect(msg.data.metadata.http.route).to.equal('/error')
child.kill('SIGINT')
done()
}
})
})
it('should receive data from koaErrorHandler', (done) => {
if (semver.satisfies(process.version, '<= 6.0.0')) return done()
const child = launch('fixtures/apiKoaErrorHandler')
child.on('message', msg => {
if (msg === 'ready') {
const httpModule = require('http')
httpModule.get('http://localhost:3003/error')
} else if (msg.type === 'process:exception') {
expect(msg.data.message).to.equal('toto')
expect(msg.data.metadata.http.path).to.equal('/error')
expect(msg.data.metadata.http.method).to.equal('GET')
child.kill('SIGINT')
done()
}
})
})
it('should not make errors swallowed when koaErrorHandler is used', (done) => {
if (semver.satisfies(process.version, '<= 6.0.0')) return done()
const child = launch('fixtures/apiKoaErrorHandler')
child.on('message', msg => {
if (msg === 'ready') {
const httpModule = require('http')
httpModule.get('http://localhost:3003/error', ({ statusCode }) => {
expect(statusCode).to.equal(500)
child.kill('SIGINT')
done()
})
}
})
})
it('should enable tracing + metrics', (done) => {
const child = launch('fixtures/apiBackwardConfChild')
let tracingDone = false
let metricsDone = false
let finished = false
child.on('message', packet => {
if (packet.type === 'trace-span') {
expect(packet.data.hasOwnProperty('id')).to.equal(true)
expect(packet.data.hasOwnProperty('traceId')).to.equal(true)
tracingDone = true
}
if (packet.type === 'axm:monitor') {
assert(packet.data['Heap Usage'] !== undefined)
if (packet.data['HTTP'] !== undefined) {
assert(packet.data['HTTP Mean Latency'] !== undefined)
assert(packet.data['HTTP P95 Latency'] !== undefined)
metricsDone = true
}
}
if (tracingDone && metricsDone && !finished) {
finished = true
child.kill('SIGINT')
done()
}
})
})
})
describe('InitModule', () => {
it('should return module conf', () => {
process.env.mocha = JSON.stringify({
test: 'processTest',
bool: true,
boolAsString: 'true',
number: '12',
object: {
prop1: 'value1'
}
})
const conf = pmx.initModule({
test2: 'toto'
})
expect(conf.test2).to.equal('toto')
expect(conf.module_conf.test).to.equal('processTest')
expect(conf.module_conf.bool).to.equal(true)
expect(conf.module_conf.boolAsString).to.equal(true)
expect(typeof conf.module_conf.number).to.equal('number')
expect(conf.module_conf.number).to.equal(12)
expect(typeof conf.module_conf.object).to.equal('object')
expect(conf.module_conf.object.prop1).to.equal('value1')
expect(conf.module_name).to.equal('mocha')
expect(typeof conf.module_version).to.equal('string')
expect(typeof conf.module_name).to.equal('string')
expect(typeof conf.description).to.equal('string')
expect(conf.apm.type).to.equal('node')
expect(typeof conf.apm.version).to.equal('string')
})
it('should return module conf with callback', () => {
process.env.mocha = JSON.stringify(new Date())
pmx.initModule({
test2: 'toto'
}, (err, conf) => {
expect(typeof conf.module_conf).to.equal('object')
expect(typeof conf.module_version).to.equal('string')
expect(typeof conf.module_name).to.equal('string')
expect(typeof conf.description).to.equal('string')
expect(conf.apm.type).to.equal('node')
expect(typeof conf.apm.version).to.equal('string')
expect(conf.test2).to.equal('toto')
expect(conf.module_name).to.equal('mocha')
expect(err).to.equal(null)
})
})
it('should return minimal conf', () => {
// @ts-ignore
const conf = pmx.initModule()
expect(conf.module_name).to.equal('mocha')
expect(typeof conf.module_version).to.equal('string')
expect(typeof conf.module_name).to.equal('string')
expect(typeof conf.description).to.equal('string')
expect(conf.apm.type).to.equal('node')
expect(typeof conf.apm.version).to.equal('string')
})
it('should receive data from init module', (done) => {
const child = launch('fixtures/apiInitModuleChild')
child.on('message', pck => {
if (pck.type === 'axm:option:configuration' && pck.data.module_name === 'fixtures') {
const conf = pck.data
expect(conf.module_version).to.equal('0.0.1')
expect(typeof conf.module_name).to.equal('string')
expect(conf.apm.type).to.equal('node')
expect(typeof conf.apm.version).to.equal('string')
child.kill('SIGINT')
done()
}
})
})
})
describe('Multiple instantiation', () => {
it('should retrieve config of the previous instantiation', () => {
pmx.init({ metrics: { v8: true } })
let conf = pmx.getConfig()
// @ts-ignore
expect(conf.metrics.v8).to.equal(true)
// @ts-ignore
expect(conf.metrics.http).to.equal(undefined)
pmx.init({ metrics: { http: false } })
conf = pmx.getConfig()
// @ts-ignore
expect(conf.metrics.v8).to.equal(undefined)
// @ts-ignore
expect(conf.metrics.http).to.equal(false)
pmx.destroy()
})
})
}) | the_stack |
import * as $protobuf from "protobufjs";
/** Namespace ml_pipelines. */
export namespace ml_pipelines {
/** Properties of a PipelineJob. */
interface IPipelineJob {
/** PipelineJob name */
name?: (string|null);
/** PipelineJob displayName */
displayName?: (string|null);
/** PipelineJob pipelineSpec */
pipelineSpec?: (google.protobuf.IStruct|null);
/** PipelineJob labels */
labels?: ({ [k: string]: string }|null);
/** PipelineJob runtimeConfig */
runtimeConfig?: (ml_pipelines.PipelineJob.IRuntimeConfig|null);
}
/** Represents a PipelineJob. */
class PipelineJob implements IPipelineJob {
/**
* Constructs a new PipelineJob.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IPipelineJob);
/** PipelineJob name. */
public name: string;
/** PipelineJob displayName. */
public displayName: string;
/** PipelineJob pipelineSpec. */
public pipelineSpec?: (google.protobuf.IStruct|null);
/** PipelineJob labels. */
public labels: { [k: string]: string };
/** PipelineJob runtimeConfig. */
public runtimeConfig?: (ml_pipelines.PipelineJob.IRuntimeConfig|null);
/**
* Creates a new PipelineJob instance using the specified properties.
* @param [properties] Properties to set
* @returns PipelineJob instance
*/
public static create(properties?: ml_pipelines.IPipelineJob): ml_pipelines.PipelineJob;
/**
* Encodes the specified PipelineJob message. Does not implicitly {@link ml_pipelines.PipelineJob.verify|verify} messages.
* @param message PipelineJob message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IPipelineJob, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PipelineJob message, length delimited. Does not implicitly {@link ml_pipelines.PipelineJob.verify|verify} messages.
* @param message PipelineJob message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IPipelineJob, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PipelineJob message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PipelineJob
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineJob;
/**
* Decodes a PipelineJob message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PipelineJob
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineJob;
/**
* Verifies a PipelineJob message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PipelineJob message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PipelineJob
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineJob;
/**
* Creates a plain object from a PipelineJob message. Also converts values to other types if specified.
* @param message PipelineJob
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineJob, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PipelineJob to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PipelineJob {
/** Properties of a RuntimeConfig. */
interface IRuntimeConfig {
/** RuntimeConfig parameters */
parameters?: ({ [k: string]: ml_pipelines.IValue }|null);
/** RuntimeConfig gcsOutputDirectory */
gcsOutputDirectory?: (string|null);
}
/** Represents a RuntimeConfig. */
class RuntimeConfig implements IRuntimeConfig {
/**
* Constructs a new RuntimeConfig.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineJob.IRuntimeConfig);
/** RuntimeConfig parameters. */
public parameters: { [k: string]: ml_pipelines.IValue };
/** RuntimeConfig gcsOutputDirectory. */
public gcsOutputDirectory: string;
/**
* Creates a new RuntimeConfig instance using the specified properties.
* @param [properties] Properties to set
* @returns RuntimeConfig instance
*/
public static create(properties?: ml_pipelines.PipelineJob.IRuntimeConfig): ml_pipelines.PipelineJob.RuntimeConfig;
/**
* Encodes the specified RuntimeConfig message. Does not implicitly {@link ml_pipelines.PipelineJob.RuntimeConfig.verify|verify} messages.
* @param message RuntimeConfig message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineJob.IRuntimeConfig, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified RuntimeConfig message, length delimited. Does not implicitly {@link ml_pipelines.PipelineJob.RuntimeConfig.verify|verify} messages.
* @param message RuntimeConfig message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineJob.IRuntimeConfig, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a RuntimeConfig message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns RuntimeConfig
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineJob.RuntimeConfig;
/**
* Decodes a RuntimeConfig message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns RuntimeConfig
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineJob.RuntimeConfig;
/**
* Verifies a RuntimeConfig message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a RuntimeConfig message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns RuntimeConfig
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineJob.RuntimeConfig;
/**
* Creates a plain object from a RuntimeConfig message. Also converts values to other types if specified.
* @param message RuntimeConfig
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineJob.RuntimeConfig, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this RuntimeConfig to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a PipelineSpec. */
interface IPipelineSpec {
/** PipelineSpec pipelineInfo */
pipelineInfo?: (ml_pipelines.IPipelineInfo|null);
/** PipelineSpec deploymentSpec */
deploymentSpec?: (google.protobuf.IStruct|null);
/** PipelineSpec sdkVersion */
sdkVersion?: (string|null);
/** PipelineSpec schemaVersion */
schemaVersion?: (string|null);
/** PipelineSpec components */
components?: ({ [k: string]: ml_pipelines.IComponentSpec }|null);
/** PipelineSpec root */
root?: (ml_pipelines.IComponentSpec|null);
}
/** Represents a PipelineSpec. */
class PipelineSpec implements IPipelineSpec {
/**
* Constructs a new PipelineSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IPipelineSpec);
/** PipelineSpec pipelineInfo. */
public pipelineInfo?: (ml_pipelines.IPipelineInfo|null);
/** PipelineSpec deploymentSpec. */
public deploymentSpec?: (google.protobuf.IStruct|null);
/** PipelineSpec sdkVersion. */
public sdkVersion: string;
/** PipelineSpec schemaVersion. */
public schemaVersion: string;
/** PipelineSpec components. */
public components: { [k: string]: ml_pipelines.IComponentSpec };
/** PipelineSpec root. */
public root?: (ml_pipelines.IComponentSpec|null);
/**
* Creates a new PipelineSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns PipelineSpec instance
*/
public static create(properties?: ml_pipelines.IPipelineSpec): ml_pipelines.PipelineSpec;
/**
* Encodes the specified PipelineSpec message. Does not implicitly {@link ml_pipelines.PipelineSpec.verify|verify} messages.
* @param message PipelineSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IPipelineSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PipelineSpec message, length delimited. Does not implicitly {@link ml_pipelines.PipelineSpec.verify|verify} messages.
* @param message PipelineSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IPipelineSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PipelineSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PipelineSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineSpec;
/**
* Decodes a PipelineSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PipelineSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineSpec;
/**
* Verifies a PipelineSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PipelineSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PipelineSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineSpec;
/**
* Creates a plain object from a PipelineSpec message. Also converts values to other types if specified.
* @param message PipelineSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PipelineSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PipelineSpec {
/** Properties of a RuntimeParameter. */
interface IRuntimeParameter {
/** RuntimeParameter type */
type?: (ml_pipelines.PrimitiveType.PrimitiveTypeEnum|null);
/** RuntimeParameter defaultValue */
defaultValue?: (ml_pipelines.IValue|null);
}
/** Represents a RuntimeParameter. */
class RuntimeParameter implements IRuntimeParameter {
/**
* Constructs a new RuntimeParameter.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineSpec.IRuntimeParameter);
/** RuntimeParameter type. */
public type: ml_pipelines.PrimitiveType.PrimitiveTypeEnum;
/** RuntimeParameter defaultValue. */
public defaultValue?: (ml_pipelines.IValue|null);
/**
* Creates a new RuntimeParameter instance using the specified properties.
* @param [properties] Properties to set
* @returns RuntimeParameter instance
*/
public static create(properties?: ml_pipelines.PipelineSpec.IRuntimeParameter): ml_pipelines.PipelineSpec.RuntimeParameter;
/**
* Encodes the specified RuntimeParameter message. Does not implicitly {@link ml_pipelines.PipelineSpec.RuntimeParameter.verify|verify} messages.
* @param message RuntimeParameter message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineSpec.IRuntimeParameter, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified RuntimeParameter message, length delimited. Does not implicitly {@link ml_pipelines.PipelineSpec.RuntimeParameter.verify|verify} messages.
* @param message RuntimeParameter message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineSpec.IRuntimeParameter, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a RuntimeParameter message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns RuntimeParameter
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineSpec.RuntimeParameter;
/**
* Decodes a RuntimeParameter message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns RuntimeParameter
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineSpec.RuntimeParameter;
/**
* Verifies a RuntimeParameter message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a RuntimeParameter message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns RuntimeParameter
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineSpec.RuntimeParameter;
/**
* Creates a plain object from a RuntimeParameter message. Also converts values to other types if specified.
* @param message RuntimeParameter
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineSpec.RuntimeParameter, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this RuntimeParameter to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a ComponentSpec. */
interface IComponentSpec {
/** ComponentSpec inputDefinitions */
inputDefinitions?: (ml_pipelines.IComponentInputsSpec|null);
/** ComponentSpec outputDefinitions */
outputDefinitions?: (ml_pipelines.IComponentOutputsSpec|null);
/** ComponentSpec dag */
dag?: (ml_pipelines.IDagSpec|null);
/** ComponentSpec executorLabel */
executorLabel?: (string|null);
}
/** Represents a ComponentSpec. */
class ComponentSpec implements IComponentSpec {
/**
* Constructs a new ComponentSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IComponentSpec);
/** ComponentSpec inputDefinitions. */
public inputDefinitions?: (ml_pipelines.IComponentInputsSpec|null);
/** ComponentSpec outputDefinitions. */
public outputDefinitions?: (ml_pipelines.IComponentOutputsSpec|null);
/** ComponentSpec dag. */
public dag?: (ml_pipelines.IDagSpec|null);
/** ComponentSpec executorLabel. */
public executorLabel?: (string|null);
/** ComponentSpec implementation. */
public implementation?: ("dag"|"executorLabel");
/**
* Creates a new ComponentSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ComponentSpec instance
*/
public static create(properties?: ml_pipelines.IComponentSpec): ml_pipelines.ComponentSpec;
/**
* Encodes the specified ComponentSpec message. Does not implicitly {@link ml_pipelines.ComponentSpec.verify|verify} messages.
* @param message ComponentSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IComponentSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ComponentSpec message, length delimited. Does not implicitly {@link ml_pipelines.ComponentSpec.verify|verify} messages.
* @param message ComponentSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IComponentSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ComponentSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ComponentSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ComponentSpec;
/**
* Decodes a ComponentSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ComponentSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ComponentSpec;
/**
* Verifies a ComponentSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ComponentSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ComponentSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ComponentSpec;
/**
* Creates a plain object from a ComponentSpec message. Also converts values to other types if specified.
* @param message ComponentSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ComponentSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ComponentSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DagSpec. */
interface IDagSpec {
/** DagSpec tasks */
tasks?: ({ [k: string]: ml_pipelines.IPipelineTaskSpec }|null);
/** DagSpec outputs */
outputs?: (ml_pipelines.IDagOutputsSpec|null);
}
/** Represents a DagSpec. */
class DagSpec implements IDagSpec {
/**
* Constructs a new DagSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IDagSpec);
/** DagSpec tasks. */
public tasks: { [k: string]: ml_pipelines.IPipelineTaskSpec };
/** DagSpec outputs. */
public outputs?: (ml_pipelines.IDagOutputsSpec|null);
/**
* Creates a new DagSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns DagSpec instance
*/
public static create(properties?: ml_pipelines.IDagSpec): ml_pipelines.DagSpec;
/**
* Encodes the specified DagSpec message. Does not implicitly {@link ml_pipelines.DagSpec.verify|verify} messages.
* @param message DagSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IDagSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DagSpec message, length delimited. Does not implicitly {@link ml_pipelines.DagSpec.verify|verify} messages.
* @param message DagSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IDagSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DagSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DagSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.DagSpec;
/**
* Decodes a DagSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DagSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.DagSpec;
/**
* Verifies a DagSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DagSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DagSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.DagSpec;
/**
* Creates a plain object from a DagSpec message. Also converts values to other types if specified.
* @param message DagSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.DagSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DagSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DagOutputsSpec. */
interface IDagOutputsSpec {
/** DagOutputsSpec artifacts */
artifacts?: ({ [k: string]: ml_pipelines.DagOutputsSpec.IDagOutputArtifactSpec }|null);
/** DagOutputsSpec parameters */
parameters?: ({ [k: string]: ml_pipelines.DagOutputsSpec.IDagOutputParameterSpec }|null);
}
/** Represents a DagOutputsSpec. */
class DagOutputsSpec implements IDagOutputsSpec {
/**
* Constructs a new DagOutputsSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IDagOutputsSpec);
/** DagOutputsSpec artifacts. */
public artifacts: { [k: string]: ml_pipelines.DagOutputsSpec.IDagOutputArtifactSpec };
/** DagOutputsSpec parameters. */
public parameters: { [k: string]: ml_pipelines.DagOutputsSpec.IDagOutputParameterSpec };
/**
* Creates a new DagOutputsSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns DagOutputsSpec instance
*/
public static create(properties?: ml_pipelines.IDagOutputsSpec): ml_pipelines.DagOutputsSpec;
/**
* Encodes the specified DagOutputsSpec message. Does not implicitly {@link ml_pipelines.DagOutputsSpec.verify|verify} messages.
* @param message DagOutputsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IDagOutputsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DagOutputsSpec message, length delimited. Does not implicitly {@link ml_pipelines.DagOutputsSpec.verify|verify} messages.
* @param message DagOutputsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IDagOutputsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DagOutputsSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DagOutputsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.DagOutputsSpec;
/**
* Decodes a DagOutputsSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DagOutputsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.DagOutputsSpec;
/**
* Verifies a DagOutputsSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DagOutputsSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DagOutputsSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.DagOutputsSpec;
/**
* Creates a plain object from a DagOutputsSpec message. Also converts values to other types if specified.
* @param message DagOutputsSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.DagOutputsSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DagOutputsSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace DagOutputsSpec {
/** Properties of an ArtifactSelectorSpec. */
interface IArtifactSelectorSpec {
/** ArtifactSelectorSpec producerSubtask */
producerSubtask?: (string|null);
/** ArtifactSelectorSpec outputArtifactKey */
outputArtifactKey?: (string|null);
}
/** Represents an ArtifactSelectorSpec. */
class ArtifactSelectorSpec implements IArtifactSelectorSpec {
/**
* Constructs a new ArtifactSelectorSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.DagOutputsSpec.IArtifactSelectorSpec);
/** ArtifactSelectorSpec producerSubtask. */
public producerSubtask: string;
/** ArtifactSelectorSpec outputArtifactKey. */
public outputArtifactKey: string;
/**
* Creates a new ArtifactSelectorSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ArtifactSelectorSpec instance
*/
public static create(properties?: ml_pipelines.DagOutputsSpec.IArtifactSelectorSpec): ml_pipelines.DagOutputsSpec.ArtifactSelectorSpec;
/**
* Encodes the specified ArtifactSelectorSpec message. Does not implicitly {@link ml_pipelines.DagOutputsSpec.ArtifactSelectorSpec.verify|verify} messages.
* @param message ArtifactSelectorSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.DagOutputsSpec.IArtifactSelectorSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ArtifactSelectorSpec message, length delimited. Does not implicitly {@link ml_pipelines.DagOutputsSpec.ArtifactSelectorSpec.verify|verify} messages.
* @param message ArtifactSelectorSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.DagOutputsSpec.IArtifactSelectorSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ArtifactSelectorSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ArtifactSelectorSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.DagOutputsSpec.ArtifactSelectorSpec;
/**
* Decodes an ArtifactSelectorSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ArtifactSelectorSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.DagOutputsSpec.ArtifactSelectorSpec;
/**
* Verifies an ArtifactSelectorSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ArtifactSelectorSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ArtifactSelectorSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.DagOutputsSpec.ArtifactSelectorSpec;
/**
* Creates a plain object from an ArtifactSelectorSpec message. Also converts values to other types if specified.
* @param message ArtifactSelectorSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.DagOutputsSpec.ArtifactSelectorSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ArtifactSelectorSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DagOutputArtifactSpec. */
interface IDagOutputArtifactSpec {
/** DagOutputArtifactSpec artifactSelectors */
artifactSelectors?: (ml_pipelines.DagOutputsSpec.IArtifactSelectorSpec[]|null);
}
/** Represents a DagOutputArtifactSpec. */
class DagOutputArtifactSpec implements IDagOutputArtifactSpec {
/**
* Constructs a new DagOutputArtifactSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.DagOutputsSpec.IDagOutputArtifactSpec);
/** DagOutputArtifactSpec artifactSelectors. */
public artifactSelectors: ml_pipelines.DagOutputsSpec.IArtifactSelectorSpec[];
/**
* Creates a new DagOutputArtifactSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns DagOutputArtifactSpec instance
*/
public static create(properties?: ml_pipelines.DagOutputsSpec.IDagOutputArtifactSpec): ml_pipelines.DagOutputsSpec.DagOutputArtifactSpec;
/**
* Encodes the specified DagOutputArtifactSpec message. Does not implicitly {@link ml_pipelines.DagOutputsSpec.DagOutputArtifactSpec.verify|verify} messages.
* @param message DagOutputArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.DagOutputsSpec.IDagOutputArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DagOutputArtifactSpec message, length delimited. Does not implicitly {@link ml_pipelines.DagOutputsSpec.DagOutputArtifactSpec.verify|verify} messages.
* @param message DagOutputArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.DagOutputsSpec.IDagOutputArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DagOutputArtifactSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DagOutputArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.DagOutputsSpec.DagOutputArtifactSpec;
/**
* Decodes a DagOutputArtifactSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DagOutputArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.DagOutputsSpec.DagOutputArtifactSpec;
/**
* Verifies a DagOutputArtifactSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DagOutputArtifactSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DagOutputArtifactSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.DagOutputsSpec.DagOutputArtifactSpec;
/**
* Creates a plain object from a DagOutputArtifactSpec message. Also converts values to other types if specified.
* @param message DagOutputArtifactSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.DagOutputsSpec.DagOutputArtifactSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DagOutputArtifactSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ParameterSelectorSpec. */
interface IParameterSelectorSpec {
/** ParameterSelectorSpec producerSubtask */
producerSubtask?: (string|null);
/** ParameterSelectorSpec outputParameterKey */
outputParameterKey?: (string|null);
}
/** Represents a ParameterSelectorSpec. */
class ParameterSelectorSpec implements IParameterSelectorSpec {
/**
* Constructs a new ParameterSelectorSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.DagOutputsSpec.IParameterSelectorSpec);
/** ParameterSelectorSpec producerSubtask. */
public producerSubtask: string;
/** ParameterSelectorSpec outputParameterKey. */
public outputParameterKey: string;
/**
* Creates a new ParameterSelectorSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ParameterSelectorSpec instance
*/
public static create(properties?: ml_pipelines.DagOutputsSpec.IParameterSelectorSpec): ml_pipelines.DagOutputsSpec.ParameterSelectorSpec;
/**
* Encodes the specified ParameterSelectorSpec message. Does not implicitly {@link ml_pipelines.DagOutputsSpec.ParameterSelectorSpec.verify|verify} messages.
* @param message ParameterSelectorSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.DagOutputsSpec.IParameterSelectorSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ParameterSelectorSpec message, length delimited. Does not implicitly {@link ml_pipelines.DagOutputsSpec.ParameterSelectorSpec.verify|verify} messages.
* @param message ParameterSelectorSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.DagOutputsSpec.IParameterSelectorSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ParameterSelectorSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ParameterSelectorSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.DagOutputsSpec.ParameterSelectorSpec;
/**
* Decodes a ParameterSelectorSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ParameterSelectorSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.DagOutputsSpec.ParameterSelectorSpec;
/**
* Verifies a ParameterSelectorSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ParameterSelectorSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ParameterSelectorSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.DagOutputsSpec.ParameterSelectorSpec;
/**
* Creates a plain object from a ParameterSelectorSpec message. Also converts values to other types if specified.
* @param message ParameterSelectorSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.DagOutputsSpec.ParameterSelectorSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ParameterSelectorSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ParameterSelectorsSpec. */
interface IParameterSelectorsSpec {
/** ParameterSelectorsSpec parameterSelectors */
parameterSelectors?: (ml_pipelines.DagOutputsSpec.IParameterSelectorSpec[]|null);
}
/** Represents a ParameterSelectorsSpec. */
class ParameterSelectorsSpec implements IParameterSelectorsSpec {
/**
* Constructs a new ParameterSelectorsSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.DagOutputsSpec.IParameterSelectorsSpec);
/** ParameterSelectorsSpec parameterSelectors. */
public parameterSelectors: ml_pipelines.DagOutputsSpec.IParameterSelectorSpec[];
/**
* Creates a new ParameterSelectorsSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ParameterSelectorsSpec instance
*/
public static create(properties?: ml_pipelines.DagOutputsSpec.IParameterSelectorsSpec): ml_pipelines.DagOutputsSpec.ParameterSelectorsSpec;
/**
* Encodes the specified ParameterSelectorsSpec message. Does not implicitly {@link ml_pipelines.DagOutputsSpec.ParameterSelectorsSpec.verify|verify} messages.
* @param message ParameterSelectorsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.DagOutputsSpec.IParameterSelectorsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ParameterSelectorsSpec message, length delimited. Does not implicitly {@link ml_pipelines.DagOutputsSpec.ParameterSelectorsSpec.verify|verify} messages.
* @param message ParameterSelectorsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.DagOutputsSpec.IParameterSelectorsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ParameterSelectorsSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ParameterSelectorsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.DagOutputsSpec.ParameterSelectorsSpec;
/**
* Decodes a ParameterSelectorsSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ParameterSelectorsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.DagOutputsSpec.ParameterSelectorsSpec;
/**
* Verifies a ParameterSelectorsSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ParameterSelectorsSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ParameterSelectorsSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.DagOutputsSpec.ParameterSelectorsSpec;
/**
* Creates a plain object from a ParameterSelectorsSpec message. Also converts values to other types if specified.
* @param message ParameterSelectorsSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.DagOutputsSpec.ParameterSelectorsSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ParameterSelectorsSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a MapParameterSelectorsSpec. */
interface IMapParameterSelectorsSpec {
/** MapParameterSelectorsSpec mappedParameters */
mappedParameters?: ({ [k: string]: ml_pipelines.DagOutputsSpec.IParameterSelectorSpec }|null);
}
/** Represents a MapParameterSelectorsSpec. */
class MapParameterSelectorsSpec implements IMapParameterSelectorsSpec {
/**
* Constructs a new MapParameterSelectorsSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.DagOutputsSpec.IMapParameterSelectorsSpec);
/** MapParameterSelectorsSpec mappedParameters. */
public mappedParameters: { [k: string]: ml_pipelines.DagOutputsSpec.IParameterSelectorSpec };
/**
* Creates a new MapParameterSelectorsSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns MapParameterSelectorsSpec instance
*/
public static create(properties?: ml_pipelines.DagOutputsSpec.IMapParameterSelectorsSpec): ml_pipelines.DagOutputsSpec.MapParameterSelectorsSpec;
/**
* Encodes the specified MapParameterSelectorsSpec message. Does not implicitly {@link ml_pipelines.DagOutputsSpec.MapParameterSelectorsSpec.verify|verify} messages.
* @param message MapParameterSelectorsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.DagOutputsSpec.IMapParameterSelectorsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified MapParameterSelectorsSpec message, length delimited. Does not implicitly {@link ml_pipelines.DagOutputsSpec.MapParameterSelectorsSpec.verify|verify} messages.
* @param message MapParameterSelectorsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.DagOutputsSpec.IMapParameterSelectorsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a MapParameterSelectorsSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns MapParameterSelectorsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.DagOutputsSpec.MapParameterSelectorsSpec;
/**
* Decodes a MapParameterSelectorsSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns MapParameterSelectorsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.DagOutputsSpec.MapParameterSelectorsSpec;
/**
* Verifies a MapParameterSelectorsSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a MapParameterSelectorsSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns MapParameterSelectorsSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.DagOutputsSpec.MapParameterSelectorsSpec;
/**
* Creates a plain object from a MapParameterSelectorsSpec message. Also converts values to other types if specified.
* @param message MapParameterSelectorsSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.DagOutputsSpec.MapParameterSelectorsSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this MapParameterSelectorsSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a DagOutputParameterSpec. */
interface IDagOutputParameterSpec {
/** DagOutputParameterSpec valueFromParameter */
valueFromParameter?: (ml_pipelines.DagOutputsSpec.IParameterSelectorSpec|null);
/** DagOutputParameterSpec valueFromOneof */
valueFromOneof?: (ml_pipelines.DagOutputsSpec.IParameterSelectorsSpec|null);
}
/** Represents a DagOutputParameterSpec. */
class DagOutputParameterSpec implements IDagOutputParameterSpec {
/**
* Constructs a new DagOutputParameterSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.DagOutputsSpec.IDagOutputParameterSpec);
/** DagOutputParameterSpec valueFromParameter. */
public valueFromParameter?: (ml_pipelines.DagOutputsSpec.IParameterSelectorSpec|null);
/** DagOutputParameterSpec valueFromOneof. */
public valueFromOneof?: (ml_pipelines.DagOutputsSpec.IParameterSelectorsSpec|null);
/** DagOutputParameterSpec kind. */
public kind?: ("valueFromParameter"|"valueFromOneof");
/**
* Creates a new DagOutputParameterSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns DagOutputParameterSpec instance
*/
public static create(properties?: ml_pipelines.DagOutputsSpec.IDagOutputParameterSpec): ml_pipelines.DagOutputsSpec.DagOutputParameterSpec;
/**
* Encodes the specified DagOutputParameterSpec message. Does not implicitly {@link ml_pipelines.DagOutputsSpec.DagOutputParameterSpec.verify|verify} messages.
* @param message DagOutputParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.DagOutputsSpec.IDagOutputParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified DagOutputParameterSpec message, length delimited. Does not implicitly {@link ml_pipelines.DagOutputsSpec.DagOutputParameterSpec.verify|verify} messages.
* @param message DagOutputParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.DagOutputsSpec.IDagOutputParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a DagOutputParameterSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns DagOutputParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.DagOutputsSpec.DagOutputParameterSpec;
/**
* Decodes a DagOutputParameterSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns DagOutputParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.DagOutputsSpec.DagOutputParameterSpec;
/**
* Verifies a DagOutputParameterSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a DagOutputParameterSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns DagOutputParameterSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.DagOutputsSpec.DagOutputParameterSpec;
/**
* Creates a plain object from a DagOutputParameterSpec message. Also converts values to other types if specified.
* @param message DagOutputParameterSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.DagOutputsSpec.DagOutputParameterSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this DagOutputParameterSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a ComponentInputsSpec. */
interface IComponentInputsSpec {
/** ComponentInputsSpec artifacts */
artifacts?: ({ [k: string]: ml_pipelines.ComponentInputsSpec.IArtifactSpec }|null);
/** ComponentInputsSpec parameters */
parameters?: ({ [k: string]: ml_pipelines.ComponentInputsSpec.IParameterSpec }|null);
}
/** Represents a ComponentInputsSpec. */
class ComponentInputsSpec implements IComponentInputsSpec {
/**
* Constructs a new ComponentInputsSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IComponentInputsSpec);
/** ComponentInputsSpec artifacts. */
public artifacts: { [k: string]: ml_pipelines.ComponentInputsSpec.IArtifactSpec };
/** ComponentInputsSpec parameters. */
public parameters: { [k: string]: ml_pipelines.ComponentInputsSpec.IParameterSpec };
/**
* Creates a new ComponentInputsSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ComponentInputsSpec instance
*/
public static create(properties?: ml_pipelines.IComponentInputsSpec): ml_pipelines.ComponentInputsSpec;
/**
* Encodes the specified ComponentInputsSpec message. Does not implicitly {@link ml_pipelines.ComponentInputsSpec.verify|verify} messages.
* @param message ComponentInputsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IComponentInputsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ComponentInputsSpec message, length delimited. Does not implicitly {@link ml_pipelines.ComponentInputsSpec.verify|verify} messages.
* @param message ComponentInputsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IComponentInputsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ComponentInputsSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ComponentInputsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ComponentInputsSpec;
/**
* Decodes a ComponentInputsSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ComponentInputsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ComponentInputsSpec;
/**
* Verifies a ComponentInputsSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ComponentInputsSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ComponentInputsSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ComponentInputsSpec;
/**
* Creates a plain object from a ComponentInputsSpec message. Also converts values to other types if specified.
* @param message ComponentInputsSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ComponentInputsSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ComponentInputsSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ComponentInputsSpec {
/** Properties of an ArtifactSpec. */
interface IArtifactSpec {
/** ArtifactSpec artifactType */
artifactType?: (ml_pipelines.IArtifactTypeSchema|null);
}
/** Represents an ArtifactSpec. */
class ArtifactSpec implements IArtifactSpec {
/**
* Constructs a new ArtifactSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ComponentInputsSpec.IArtifactSpec);
/** ArtifactSpec artifactType. */
public artifactType?: (ml_pipelines.IArtifactTypeSchema|null);
/**
* Creates a new ArtifactSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ArtifactSpec instance
*/
public static create(properties?: ml_pipelines.ComponentInputsSpec.IArtifactSpec): ml_pipelines.ComponentInputsSpec.ArtifactSpec;
/**
* Encodes the specified ArtifactSpec message. Does not implicitly {@link ml_pipelines.ComponentInputsSpec.ArtifactSpec.verify|verify} messages.
* @param message ArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ComponentInputsSpec.IArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ArtifactSpec message, length delimited. Does not implicitly {@link ml_pipelines.ComponentInputsSpec.ArtifactSpec.verify|verify} messages.
* @param message ArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ComponentInputsSpec.IArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ArtifactSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ComponentInputsSpec.ArtifactSpec;
/**
* Decodes an ArtifactSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ComponentInputsSpec.ArtifactSpec;
/**
* Verifies an ArtifactSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ArtifactSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ArtifactSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ComponentInputsSpec.ArtifactSpec;
/**
* Creates a plain object from an ArtifactSpec message. Also converts values to other types if specified.
* @param message ArtifactSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ComponentInputsSpec.ArtifactSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ArtifactSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ParameterSpec. */
interface IParameterSpec {
/** ParameterSpec type */
type?: (ml_pipelines.PrimitiveType.PrimitiveTypeEnum|null);
}
/** Represents a ParameterSpec. */
class ParameterSpec implements IParameterSpec {
/**
* Constructs a new ParameterSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ComponentInputsSpec.IParameterSpec);
/** ParameterSpec type. */
public type: ml_pipelines.PrimitiveType.PrimitiveTypeEnum;
/**
* Creates a new ParameterSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ParameterSpec instance
*/
public static create(properties?: ml_pipelines.ComponentInputsSpec.IParameterSpec): ml_pipelines.ComponentInputsSpec.ParameterSpec;
/**
* Encodes the specified ParameterSpec message. Does not implicitly {@link ml_pipelines.ComponentInputsSpec.ParameterSpec.verify|verify} messages.
* @param message ParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ComponentInputsSpec.IParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ParameterSpec message, length delimited. Does not implicitly {@link ml_pipelines.ComponentInputsSpec.ParameterSpec.verify|verify} messages.
* @param message ParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ComponentInputsSpec.IParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ParameterSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ComponentInputsSpec.ParameterSpec;
/**
* Decodes a ParameterSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ComponentInputsSpec.ParameterSpec;
/**
* Verifies a ParameterSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ParameterSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ParameterSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ComponentInputsSpec.ParameterSpec;
/**
* Creates a plain object from a ParameterSpec message. Also converts values to other types if specified.
* @param message ParameterSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ComponentInputsSpec.ParameterSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ParameterSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a ComponentOutputsSpec. */
interface IComponentOutputsSpec {
/** ComponentOutputsSpec artifacts */
artifacts?: ({ [k: string]: ml_pipelines.ComponentOutputsSpec.IArtifactSpec }|null);
/** ComponentOutputsSpec parameters */
parameters?: ({ [k: string]: ml_pipelines.ComponentOutputsSpec.IParameterSpec }|null);
}
/** Represents a ComponentOutputsSpec. */
class ComponentOutputsSpec implements IComponentOutputsSpec {
/**
* Constructs a new ComponentOutputsSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IComponentOutputsSpec);
/** ComponentOutputsSpec artifacts. */
public artifacts: { [k: string]: ml_pipelines.ComponentOutputsSpec.IArtifactSpec };
/** ComponentOutputsSpec parameters. */
public parameters: { [k: string]: ml_pipelines.ComponentOutputsSpec.IParameterSpec };
/**
* Creates a new ComponentOutputsSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ComponentOutputsSpec instance
*/
public static create(properties?: ml_pipelines.IComponentOutputsSpec): ml_pipelines.ComponentOutputsSpec;
/**
* Encodes the specified ComponentOutputsSpec message. Does not implicitly {@link ml_pipelines.ComponentOutputsSpec.verify|verify} messages.
* @param message ComponentOutputsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IComponentOutputsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ComponentOutputsSpec message, length delimited. Does not implicitly {@link ml_pipelines.ComponentOutputsSpec.verify|verify} messages.
* @param message ComponentOutputsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IComponentOutputsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ComponentOutputsSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ComponentOutputsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ComponentOutputsSpec;
/**
* Decodes a ComponentOutputsSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ComponentOutputsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ComponentOutputsSpec;
/**
* Verifies a ComponentOutputsSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ComponentOutputsSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ComponentOutputsSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ComponentOutputsSpec;
/**
* Creates a plain object from a ComponentOutputsSpec message. Also converts values to other types if specified.
* @param message ComponentOutputsSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ComponentOutputsSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ComponentOutputsSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ComponentOutputsSpec {
/** Properties of an ArtifactSpec. */
interface IArtifactSpec {
/** ArtifactSpec artifactType */
artifactType?: (ml_pipelines.IArtifactTypeSchema|null);
/** ArtifactSpec properties */
properties?: ({ [k: string]: ml_pipelines.IValueOrRuntimeParameter }|null);
/** ArtifactSpec customProperties */
customProperties?: ({ [k: string]: ml_pipelines.IValueOrRuntimeParameter }|null);
/** ArtifactSpec metadata */
metadata?: (google.protobuf.IStruct|null);
}
/** Represents an ArtifactSpec. */
class ArtifactSpec implements IArtifactSpec {
/**
* Constructs a new ArtifactSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ComponentOutputsSpec.IArtifactSpec);
/** ArtifactSpec artifactType. */
public artifactType?: (ml_pipelines.IArtifactTypeSchema|null);
/** ArtifactSpec properties. */
public properties: { [k: string]: ml_pipelines.IValueOrRuntimeParameter };
/** ArtifactSpec customProperties. */
public customProperties: { [k: string]: ml_pipelines.IValueOrRuntimeParameter };
/** ArtifactSpec metadata. */
public metadata?: (google.protobuf.IStruct|null);
/**
* Creates a new ArtifactSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ArtifactSpec instance
*/
public static create(properties?: ml_pipelines.ComponentOutputsSpec.IArtifactSpec): ml_pipelines.ComponentOutputsSpec.ArtifactSpec;
/**
* Encodes the specified ArtifactSpec message. Does not implicitly {@link ml_pipelines.ComponentOutputsSpec.ArtifactSpec.verify|verify} messages.
* @param message ArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ComponentOutputsSpec.IArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ArtifactSpec message, length delimited. Does not implicitly {@link ml_pipelines.ComponentOutputsSpec.ArtifactSpec.verify|verify} messages.
* @param message ArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ComponentOutputsSpec.IArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ArtifactSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ComponentOutputsSpec.ArtifactSpec;
/**
* Decodes an ArtifactSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ComponentOutputsSpec.ArtifactSpec;
/**
* Verifies an ArtifactSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ArtifactSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ArtifactSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ComponentOutputsSpec.ArtifactSpec;
/**
* Creates a plain object from an ArtifactSpec message. Also converts values to other types if specified.
* @param message ArtifactSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ComponentOutputsSpec.ArtifactSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ArtifactSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ParameterSpec. */
interface IParameterSpec {
/** ParameterSpec type */
type?: (ml_pipelines.PrimitiveType.PrimitiveTypeEnum|null);
}
/** Represents a ParameterSpec. */
class ParameterSpec implements IParameterSpec {
/**
* Constructs a new ParameterSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ComponentOutputsSpec.IParameterSpec);
/** ParameterSpec type. */
public type: ml_pipelines.PrimitiveType.PrimitiveTypeEnum;
/**
* Creates a new ParameterSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ParameterSpec instance
*/
public static create(properties?: ml_pipelines.ComponentOutputsSpec.IParameterSpec): ml_pipelines.ComponentOutputsSpec.ParameterSpec;
/**
* Encodes the specified ParameterSpec message. Does not implicitly {@link ml_pipelines.ComponentOutputsSpec.ParameterSpec.verify|verify} messages.
* @param message ParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ComponentOutputsSpec.IParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ParameterSpec message, length delimited. Does not implicitly {@link ml_pipelines.ComponentOutputsSpec.ParameterSpec.verify|verify} messages.
* @param message ParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ComponentOutputsSpec.IParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ParameterSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ComponentOutputsSpec.ParameterSpec;
/**
* Decodes a ParameterSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ComponentOutputsSpec.ParameterSpec;
/**
* Verifies a ParameterSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ParameterSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ParameterSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ComponentOutputsSpec.ParameterSpec;
/**
* Creates a plain object from a ParameterSpec message. Also converts values to other types if specified.
* @param message ParameterSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ComponentOutputsSpec.ParameterSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ParameterSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a TaskInputsSpec. */
interface ITaskInputsSpec {
/** TaskInputsSpec parameters */
parameters?: ({ [k: string]: ml_pipelines.TaskInputsSpec.IInputParameterSpec }|null);
/** TaskInputsSpec artifacts */
artifacts?: ({ [k: string]: ml_pipelines.TaskInputsSpec.IInputArtifactSpec }|null);
}
/** Represents a TaskInputsSpec. */
class TaskInputsSpec implements ITaskInputsSpec {
/**
* Constructs a new TaskInputsSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ITaskInputsSpec);
/** TaskInputsSpec parameters. */
public parameters: { [k: string]: ml_pipelines.TaskInputsSpec.IInputParameterSpec };
/** TaskInputsSpec artifacts. */
public artifacts: { [k: string]: ml_pipelines.TaskInputsSpec.IInputArtifactSpec };
/**
* Creates a new TaskInputsSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns TaskInputsSpec instance
*/
public static create(properties?: ml_pipelines.ITaskInputsSpec): ml_pipelines.TaskInputsSpec;
/**
* Encodes the specified TaskInputsSpec message. Does not implicitly {@link ml_pipelines.TaskInputsSpec.verify|verify} messages.
* @param message TaskInputsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ITaskInputsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TaskInputsSpec message, length delimited. Does not implicitly {@link ml_pipelines.TaskInputsSpec.verify|verify} messages.
* @param message TaskInputsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ITaskInputsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TaskInputsSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TaskInputsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.TaskInputsSpec;
/**
* Decodes a TaskInputsSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TaskInputsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.TaskInputsSpec;
/**
* Verifies a TaskInputsSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TaskInputsSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TaskInputsSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.TaskInputsSpec;
/**
* Creates a plain object from a TaskInputsSpec message. Also converts values to other types if specified.
* @param message TaskInputsSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.TaskInputsSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TaskInputsSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace TaskInputsSpec {
/** Properties of an InputArtifactSpec. */
interface IInputArtifactSpec {
/** InputArtifactSpec taskOutputArtifact */
taskOutputArtifact?: (ml_pipelines.TaskInputsSpec.InputArtifactSpec.ITaskOutputArtifactSpec|null);
/** InputArtifactSpec componentInputArtifact */
componentInputArtifact?: (string|null);
}
/** Represents an InputArtifactSpec. */
class InputArtifactSpec implements IInputArtifactSpec {
/**
* Constructs a new InputArtifactSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.TaskInputsSpec.IInputArtifactSpec);
/** InputArtifactSpec taskOutputArtifact. */
public taskOutputArtifact?: (ml_pipelines.TaskInputsSpec.InputArtifactSpec.ITaskOutputArtifactSpec|null);
/** InputArtifactSpec componentInputArtifact. */
public componentInputArtifact?: (string|null);
/** InputArtifactSpec kind. */
public kind?: ("taskOutputArtifact"|"componentInputArtifact");
/**
* Creates a new InputArtifactSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns InputArtifactSpec instance
*/
public static create(properties?: ml_pipelines.TaskInputsSpec.IInputArtifactSpec): ml_pipelines.TaskInputsSpec.InputArtifactSpec;
/**
* Encodes the specified InputArtifactSpec message. Does not implicitly {@link ml_pipelines.TaskInputsSpec.InputArtifactSpec.verify|verify} messages.
* @param message InputArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.TaskInputsSpec.IInputArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified InputArtifactSpec message, length delimited. Does not implicitly {@link ml_pipelines.TaskInputsSpec.InputArtifactSpec.verify|verify} messages.
* @param message InputArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.TaskInputsSpec.IInputArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an InputArtifactSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns InputArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.TaskInputsSpec.InputArtifactSpec;
/**
* Decodes an InputArtifactSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns InputArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.TaskInputsSpec.InputArtifactSpec;
/**
* Verifies an InputArtifactSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an InputArtifactSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns InputArtifactSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.TaskInputsSpec.InputArtifactSpec;
/**
* Creates a plain object from an InputArtifactSpec message. Also converts values to other types if specified.
* @param message InputArtifactSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.TaskInputsSpec.InputArtifactSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this InputArtifactSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace InputArtifactSpec {
/** Properties of a TaskOutputArtifactSpec. */
interface ITaskOutputArtifactSpec {
/** TaskOutputArtifactSpec producerTask */
producerTask?: (string|null);
/** TaskOutputArtifactSpec outputArtifactKey */
outputArtifactKey?: (string|null);
}
/** Represents a TaskOutputArtifactSpec. */
class TaskOutputArtifactSpec implements ITaskOutputArtifactSpec {
/**
* Constructs a new TaskOutputArtifactSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.TaskInputsSpec.InputArtifactSpec.ITaskOutputArtifactSpec);
/** TaskOutputArtifactSpec producerTask. */
public producerTask: string;
/** TaskOutputArtifactSpec outputArtifactKey. */
public outputArtifactKey: string;
/**
* Creates a new TaskOutputArtifactSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns TaskOutputArtifactSpec instance
*/
public static create(properties?: ml_pipelines.TaskInputsSpec.InputArtifactSpec.ITaskOutputArtifactSpec): ml_pipelines.TaskInputsSpec.InputArtifactSpec.TaskOutputArtifactSpec;
/**
* Encodes the specified TaskOutputArtifactSpec message. Does not implicitly {@link ml_pipelines.TaskInputsSpec.InputArtifactSpec.TaskOutputArtifactSpec.verify|verify} messages.
* @param message TaskOutputArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.TaskInputsSpec.InputArtifactSpec.ITaskOutputArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TaskOutputArtifactSpec message, length delimited. Does not implicitly {@link ml_pipelines.TaskInputsSpec.InputArtifactSpec.TaskOutputArtifactSpec.verify|verify} messages.
* @param message TaskOutputArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.TaskInputsSpec.InputArtifactSpec.ITaskOutputArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TaskOutputArtifactSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TaskOutputArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.TaskInputsSpec.InputArtifactSpec.TaskOutputArtifactSpec;
/**
* Decodes a TaskOutputArtifactSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TaskOutputArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.TaskInputsSpec.InputArtifactSpec.TaskOutputArtifactSpec;
/**
* Verifies a TaskOutputArtifactSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TaskOutputArtifactSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TaskOutputArtifactSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.TaskInputsSpec.InputArtifactSpec.TaskOutputArtifactSpec;
/**
* Creates a plain object from a TaskOutputArtifactSpec message. Also converts values to other types if specified.
* @param message TaskOutputArtifactSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.TaskInputsSpec.InputArtifactSpec.TaskOutputArtifactSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TaskOutputArtifactSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an InputParameterSpec. */
interface IInputParameterSpec {
/** InputParameterSpec taskOutputParameter */
taskOutputParameter?: (ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskOutputParameterSpec|null);
/** InputParameterSpec runtimeValue */
runtimeValue?: (ml_pipelines.IValueOrRuntimeParameter|null);
/** InputParameterSpec componentInputParameter */
componentInputParameter?: (string|null);
/** InputParameterSpec taskFinalStatus */
taskFinalStatus?: (ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskFinalStatus|null);
/** InputParameterSpec parameterExpressionSelector */
parameterExpressionSelector?: (string|null);
}
/** Represents an InputParameterSpec. */
class InputParameterSpec implements IInputParameterSpec {
/**
* Constructs a new InputParameterSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.TaskInputsSpec.IInputParameterSpec);
/** InputParameterSpec taskOutputParameter. */
public taskOutputParameter?: (ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskOutputParameterSpec|null);
/** InputParameterSpec runtimeValue. */
public runtimeValue?: (ml_pipelines.IValueOrRuntimeParameter|null);
/** InputParameterSpec componentInputParameter. */
public componentInputParameter?: (string|null);
/** InputParameterSpec taskFinalStatus. */
public taskFinalStatus?: (ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskFinalStatus|null);
/** InputParameterSpec parameterExpressionSelector. */
public parameterExpressionSelector: string;
/** InputParameterSpec kind. */
public kind?: ("taskOutputParameter"|"runtimeValue"|"componentInputParameter"|"taskFinalStatus");
/**
* Creates a new InputParameterSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns InputParameterSpec instance
*/
public static create(properties?: ml_pipelines.TaskInputsSpec.IInputParameterSpec): ml_pipelines.TaskInputsSpec.InputParameterSpec;
/**
* Encodes the specified InputParameterSpec message. Does not implicitly {@link ml_pipelines.TaskInputsSpec.InputParameterSpec.verify|verify} messages.
* @param message InputParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.TaskInputsSpec.IInputParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified InputParameterSpec message, length delimited. Does not implicitly {@link ml_pipelines.TaskInputsSpec.InputParameterSpec.verify|verify} messages.
* @param message InputParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.TaskInputsSpec.IInputParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an InputParameterSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns InputParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.TaskInputsSpec.InputParameterSpec;
/**
* Decodes an InputParameterSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns InputParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.TaskInputsSpec.InputParameterSpec;
/**
* Verifies an InputParameterSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an InputParameterSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns InputParameterSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.TaskInputsSpec.InputParameterSpec;
/**
* Creates a plain object from an InputParameterSpec message. Also converts values to other types if specified.
* @param message InputParameterSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.TaskInputsSpec.InputParameterSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this InputParameterSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace InputParameterSpec {
/** Properties of a TaskOutputParameterSpec. */
interface ITaskOutputParameterSpec {
/** TaskOutputParameterSpec producerTask */
producerTask?: (string|null);
/** TaskOutputParameterSpec outputParameterKey */
outputParameterKey?: (string|null);
}
/** Represents a TaskOutputParameterSpec. */
class TaskOutputParameterSpec implements ITaskOutputParameterSpec {
/**
* Constructs a new TaskOutputParameterSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskOutputParameterSpec);
/** TaskOutputParameterSpec producerTask. */
public producerTask: string;
/** TaskOutputParameterSpec outputParameterKey. */
public outputParameterKey: string;
/**
* Creates a new TaskOutputParameterSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns TaskOutputParameterSpec instance
*/
public static create(properties?: ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskOutputParameterSpec): ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskOutputParameterSpec;
/**
* Encodes the specified TaskOutputParameterSpec message. Does not implicitly {@link ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskOutputParameterSpec.verify|verify} messages.
* @param message TaskOutputParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskOutputParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TaskOutputParameterSpec message, length delimited. Does not implicitly {@link ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskOutputParameterSpec.verify|verify} messages.
* @param message TaskOutputParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskOutputParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TaskOutputParameterSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TaskOutputParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskOutputParameterSpec;
/**
* Decodes a TaskOutputParameterSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TaskOutputParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskOutputParameterSpec;
/**
* Verifies a TaskOutputParameterSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TaskOutputParameterSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TaskOutputParameterSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskOutputParameterSpec;
/**
* Creates a plain object from a TaskOutputParameterSpec message. Also converts values to other types if specified.
* @param message TaskOutputParameterSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskOutputParameterSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TaskOutputParameterSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TaskFinalStatus. */
interface ITaskFinalStatus {
/** TaskFinalStatus producerTask */
producerTask?: (string|null);
}
/** Represents a TaskFinalStatus. */
class TaskFinalStatus implements ITaskFinalStatus {
/**
* Constructs a new TaskFinalStatus.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskFinalStatus);
/** TaskFinalStatus producerTask. */
public producerTask: string;
/**
* Creates a new TaskFinalStatus instance using the specified properties.
* @param [properties] Properties to set
* @returns TaskFinalStatus instance
*/
public static create(properties?: ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskFinalStatus): ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskFinalStatus;
/**
* Encodes the specified TaskFinalStatus message. Does not implicitly {@link ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskFinalStatus.verify|verify} messages.
* @param message TaskFinalStatus message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskFinalStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TaskFinalStatus message, length delimited. Does not implicitly {@link ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskFinalStatus.verify|verify} messages.
* @param message TaskFinalStatus message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.TaskInputsSpec.InputParameterSpec.ITaskFinalStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TaskFinalStatus message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TaskFinalStatus
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskFinalStatus;
/**
* Decodes a TaskFinalStatus message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TaskFinalStatus
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskFinalStatus;
/**
* Verifies a TaskFinalStatus message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TaskFinalStatus message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TaskFinalStatus
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskFinalStatus;
/**
* Creates a plain object from a TaskFinalStatus message. Also converts values to other types if specified.
* @param message TaskFinalStatus
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.TaskInputsSpec.InputParameterSpec.TaskFinalStatus, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TaskFinalStatus to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
}
/** Properties of a TaskOutputsSpec. */
interface ITaskOutputsSpec {
/** TaskOutputsSpec parameters */
parameters?: ({ [k: string]: ml_pipelines.TaskOutputsSpec.IOutputParameterSpec }|null);
/** TaskOutputsSpec artifacts */
artifacts?: ({ [k: string]: ml_pipelines.TaskOutputsSpec.IOutputArtifactSpec }|null);
}
/** Represents a TaskOutputsSpec. */
class TaskOutputsSpec implements ITaskOutputsSpec {
/**
* Constructs a new TaskOutputsSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ITaskOutputsSpec);
/** TaskOutputsSpec parameters. */
public parameters: { [k: string]: ml_pipelines.TaskOutputsSpec.IOutputParameterSpec };
/** TaskOutputsSpec artifacts. */
public artifacts: { [k: string]: ml_pipelines.TaskOutputsSpec.IOutputArtifactSpec };
/**
* Creates a new TaskOutputsSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns TaskOutputsSpec instance
*/
public static create(properties?: ml_pipelines.ITaskOutputsSpec): ml_pipelines.TaskOutputsSpec;
/**
* Encodes the specified TaskOutputsSpec message. Does not implicitly {@link ml_pipelines.TaskOutputsSpec.verify|verify} messages.
* @param message TaskOutputsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ITaskOutputsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TaskOutputsSpec message, length delimited. Does not implicitly {@link ml_pipelines.TaskOutputsSpec.verify|verify} messages.
* @param message TaskOutputsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ITaskOutputsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TaskOutputsSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TaskOutputsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.TaskOutputsSpec;
/**
* Decodes a TaskOutputsSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TaskOutputsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.TaskOutputsSpec;
/**
* Verifies a TaskOutputsSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TaskOutputsSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TaskOutputsSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.TaskOutputsSpec;
/**
* Creates a plain object from a TaskOutputsSpec message. Also converts values to other types if specified.
* @param message TaskOutputsSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.TaskOutputsSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TaskOutputsSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace TaskOutputsSpec {
/** Properties of an OutputArtifactSpec. */
interface IOutputArtifactSpec {
/** OutputArtifactSpec artifactType */
artifactType?: (ml_pipelines.IArtifactTypeSchema|null);
/** OutputArtifactSpec properties */
properties?: ({ [k: string]: ml_pipelines.IValueOrRuntimeParameter }|null);
/** OutputArtifactSpec customProperties */
customProperties?: ({ [k: string]: ml_pipelines.IValueOrRuntimeParameter }|null);
}
/** Represents an OutputArtifactSpec. */
class OutputArtifactSpec implements IOutputArtifactSpec {
/**
* Constructs a new OutputArtifactSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.TaskOutputsSpec.IOutputArtifactSpec);
/** OutputArtifactSpec artifactType. */
public artifactType?: (ml_pipelines.IArtifactTypeSchema|null);
/** OutputArtifactSpec properties. */
public properties: { [k: string]: ml_pipelines.IValueOrRuntimeParameter };
/** OutputArtifactSpec customProperties. */
public customProperties: { [k: string]: ml_pipelines.IValueOrRuntimeParameter };
/**
* Creates a new OutputArtifactSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns OutputArtifactSpec instance
*/
public static create(properties?: ml_pipelines.TaskOutputsSpec.IOutputArtifactSpec): ml_pipelines.TaskOutputsSpec.OutputArtifactSpec;
/**
* Encodes the specified OutputArtifactSpec message. Does not implicitly {@link ml_pipelines.TaskOutputsSpec.OutputArtifactSpec.verify|verify} messages.
* @param message OutputArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.TaskOutputsSpec.IOutputArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OutputArtifactSpec message, length delimited. Does not implicitly {@link ml_pipelines.TaskOutputsSpec.OutputArtifactSpec.verify|verify} messages.
* @param message OutputArtifactSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.TaskOutputsSpec.IOutputArtifactSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OutputArtifactSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OutputArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.TaskOutputsSpec.OutputArtifactSpec;
/**
* Decodes an OutputArtifactSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OutputArtifactSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.TaskOutputsSpec.OutputArtifactSpec;
/**
* Verifies an OutputArtifactSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OutputArtifactSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OutputArtifactSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.TaskOutputsSpec.OutputArtifactSpec;
/**
* Creates a plain object from an OutputArtifactSpec message. Also converts values to other types if specified.
* @param message OutputArtifactSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.TaskOutputsSpec.OutputArtifactSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OutputArtifactSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an OutputParameterSpec. */
interface IOutputParameterSpec {
/** OutputParameterSpec type */
type?: (ml_pipelines.PrimitiveType.PrimitiveTypeEnum|null);
}
/** Represents an OutputParameterSpec. */
class OutputParameterSpec implements IOutputParameterSpec {
/**
* Constructs a new OutputParameterSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.TaskOutputsSpec.IOutputParameterSpec);
/** OutputParameterSpec type. */
public type: ml_pipelines.PrimitiveType.PrimitiveTypeEnum;
/**
* Creates a new OutputParameterSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns OutputParameterSpec instance
*/
public static create(properties?: ml_pipelines.TaskOutputsSpec.IOutputParameterSpec): ml_pipelines.TaskOutputsSpec.OutputParameterSpec;
/**
* Encodes the specified OutputParameterSpec message. Does not implicitly {@link ml_pipelines.TaskOutputsSpec.OutputParameterSpec.verify|verify} messages.
* @param message OutputParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.TaskOutputsSpec.IOutputParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OutputParameterSpec message, length delimited. Does not implicitly {@link ml_pipelines.TaskOutputsSpec.OutputParameterSpec.verify|verify} messages.
* @param message OutputParameterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.TaskOutputsSpec.IOutputParameterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OutputParameterSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OutputParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.TaskOutputsSpec.OutputParameterSpec;
/**
* Decodes an OutputParameterSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OutputParameterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.TaskOutputsSpec.OutputParameterSpec;
/**
* Verifies an OutputParameterSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OutputParameterSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OutputParameterSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.TaskOutputsSpec.OutputParameterSpec;
/**
* Creates a plain object from an OutputParameterSpec message. Also converts values to other types if specified.
* @param message OutputParameterSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.TaskOutputsSpec.OutputParameterSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OutputParameterSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a PrimitiveType. */
interface IPrimitiveType {
}
/** Represents a PrimitiveType. */
class PrimitiveType implements IPrimitiveType {
/**
* Constructs a new PrimitiveType.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IPrimitiveType);
/**
* Creates a new PrimitiveType instance using the specified properties.
* @param [properties] Properties to set
* @returns PrimitiveType instance
*/
public static create(properties?: ml_pipelines.IPrimitiveType): ml_pipelines.PrimitiveType;
/**
* Encodes the specified PrimitiveType message. Does not implicitly {@link ml_pipelines.PrimitiveType.verify|verify} messages.
* @param message PrimitiveType message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IPrimitiveType, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PrimitiveType message, length delimited. Does not implicitly {@link ml_pipelines.PrimitiveType.verify|verify} messages.
* @param message PrimitiveType message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IPrimitiveType, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PrimitiveType message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PrimitiveType
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PrimitiveType;
/**
* Decodes a PrimitiveType message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PrimitiveType
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PrimitiveType;
/**
* Verifies a PrimitiveType message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PrimitiveType message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PrimitiveType
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PrimitiveType;
/**
* Creates a plain object from a PrimitiveType message. Also converts values to other types if specified.
* @param message PrimitiveType
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PrimitiveType, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PrimitiveType to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PrimitiveType {
/** PrimitiveTypeEnum enum. */
enum PrimitiveTypeEnum {
PRIMITIVE_TYPE_UNSPECIFIED = 0,
INT = 1,
DOUBLE = 2,
STRING = 3
}
}
/** Properties of a PipelineTaskSpec. */
interface IPipelineTaskSpec {
/** PipelineTaskSpec taskInfo */
taskInfo?: (ml_pipelines.IPipelineTaskInfo|null);
/** PipelineTaskSpec inputs */
inputs?: (ml_pipelines.ITaskInputsSpec|null);
/** PipelineTaskSpec dependentTasks */
dependentTasks?: (string[]|null);
/** PipelineTaskSpec cachingOptions */
cachingOptions?: (ml_pipelines.PipelineTaskSpec.ICachingOptions|null);
/** PipelineTaskSpec componentRef */
componentRef?: (ml_pipelines.IComponentRef|null);
/** PipelineTaskSpec triggerPolicy */
triggerPolicy?: (ml_pipelines.PipelineTaskSpec.ITriggerPolicy|null);
/** PipelineTaskSpec artifactIterator */
artifactIterator?: (ml_pipelines.IArtifactIteratorSpec|null);
/** PipelineTaskSpec parameterIterator */
parameterIterator?: (ml_pipelines.IParameterIteratorSpec|null);
}
/** Represents a PipelineTaskSpec. */
class PipelineTaskSpec implements IPipelineTaskSpec {
/**
* Constructs a new PipelineTaskSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IPipelineTaskSpec);
/** PipelineTaskSpec taskInfo. */
public taskInfo?: (ml_pipelines.IPipelineTaskInfo|null);
/** PipelineTaskSpec inputs. */
public inputs?: (ml_pipelines.ITaskInputsSpec|null);
/** PipelineTaskSpec dependentTasks. */
public dependentTasks: string[];
/** PipelineTaskSpec cachingOptions. */
public cachingOptions?: (ml_pipelines.PipelineTaskSpec.ICachingOptions|null);
/** PipelineTaskSpec componentRef. */
public componentRef?: (ml_pipelines.IComponentRef|null);
/** PipelineTaskSpec triggerPolicy. */
public triggerPolicy?: (ml_pipelines.PipelineTaskSpec.ITriggerPolicy|null);
/** PipelineTaskSpec artifactIterator. */
public artifactIterator?: (ml_pipelines.IArtifactIteratorSpec|null);
/** PipelineTaskSpec parameterIterator. */
public parameterIterator?: (ml_pipelines.IParameterIteratorSpec|null);
/** PipelineTaskSpec iterator. */
public iterator?: ("artifactIterator"|"parameterIterator");
/**
* Creates a new PipelineTaskSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns PipelineTaskSpec instance
*/
public static create(properties?: ml_pipelines.IPipelineTaskSpec): ml_pipelines.PipelineTaskSpec;
/**
* Encodes the specified PipelineTaskSpec message. Does not implicitly {@link ml_pipelines.PipelineTaskSpec.verify|verify} messages.
* @param message PipelineTaskSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IPipelineTaskSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PipelineTaskSpec message, length delimited. Does not implicitly {@link ml_pipelines.PipelineTaskSpec.verify|verify} messages.
* @param message PipelineTaskSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IPipelineTaskSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PipelineTaskSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PipelineTaskSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineTaskSpec;
/**
* Decodes a PipelineTaskSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PipelineTaskSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineTaskSpec;
/**
* Verifies a PipelineTaskSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PipelineTaskSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PipelineTaskSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineTaskSpec;
/**
* Creates a plain object from a PipelineTaskSpec message. Also converts values to other types if specified.
* @param message PipelineTaskSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineTaskSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PipelineTaskSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PipelineTaskSpec {
/** Properties of a CachingOptions. */
interface ICachingOptions {
/** CachingOptions enableCache */
enableCache?: (boolean|null);
}
/** Represents a CachingOptions. */
class CachingOptions implements ICachingOptions {
/**
* Constructs a new CachingOptions.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineTaskSpec.ICachingOptions);
/** CachingOptions enableCache. */
public enableCache: boolean;
/**
* Creates a new CachingOptions instance using the specified properties.
* @param [properties] Properties to set
* @returns CachingOptions instance
*/
public static create(properties?: ml_pipelines.PipelineTaskSpec.ICachingOptions): ml_pipelines.PipelineTaskSpec.CachingOptions;
/**
* Encodes the specified CachingOptions message. Does not implicitly {@link ml_pipelines.PipelineTaskSpec.CachingOptions.verify|verify} messages.
* @param message CachingOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineTaskSpec.ICachingOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified CachingOptions message, length delimited. Does not implicitly {@link ml_pipelines.PipelineTaskSpec.CachingOptions.verify|verify} messages.
* @param message CachingOptions message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineTaskSpec.ICachingOptions, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a CachingOptions message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns CachingOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineTaskSpec.CachingOptions;
/**
* Decodes a CachingOptions message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns CachingOptions
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineTaskSpec.CachingOptions;
/**
* Verifies a CachingOptions message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a CachingOptions message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns CachingOptions
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineTaskSpec.CachingOptions;
/**
* Creates a plain object from a CachingOptions message. Also converts values to other types if specified.
* @param message CachingOptions
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineTaskSpec.CachingOptions, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this CachingOptions to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TriggerPolicy. */
interface ITriggerPolicy {
/** TriggerPolicy condition */
condition?: (string|null);
/** TriggerPolicy strategy */
strategy?: (ml_pipelines.PipelineTaskSpec.TriggerPolicy.TriggerStrategy|null);
}
/** Represents a TriggerPolicy. */
class TriggerPolicy implements ITriggerPolicy {
/**
* Constructs a new TriggerPolicy.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineTaskSpec.ITriggerPolicy);
/** TriggerPolicy condition. */
public condition: string;
/** TriggerPolicy strategy. */
public strategy: ml_pipelines.PipelineTaskSpec.TriggerPolicy.TriggerStrategy;
/**
* Creates a new TriggerPolicy instance using the specified properties.
* @param [properties] Properties to set
* @returns TriggerPolicy instance
*/
public static create(properties?: ml_pipelines.PipelineTaskSpec.ITriggerPolicy): ml_pipelines.PipelineTaskSpec.TriggerPolicy;
/**
* Encodes the specified TriggerPolicy message. Does not implicitly {@link ml_pipelines.PipelineTaskSpec.TriggerPolicy.verify|verify} messages.
* @param message TriggerPolicy message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineTaskSpec.ITriggerPolicy, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TriggerPolicy message, length delimited. Does not implicitly {@link ml_pipelines.PipelineTaskSpec.TriggerPolicy.verify|verify} messages.
* @param message TriggerPolicy message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineTaskSpec.ITriggerPolicy, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TriggerPolicy message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TriggerPolicy
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineTaskSpec.TriggerPolicy;
/**
* Decodes a TriggerPolicy message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TriggerPolicy
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineTaskSpec.TriggerPolicy;
/**
* Verifies a TriggerPolicy message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TriggerPolicy message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TriggerPolicy
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineTaskSpec.TriggerPolicy;
/**
* Creates a plain object from a TriggerPolicy message. Also converts values to other types if specified.
* @param message TriggerPolicy
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineTaskSpec.TriggerPolicy, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TriggerPolicy to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace TriggerPolicy {
/** TriggerStrategy enum. */
enum TriggerStrategy {
TRIGGER_STRATEGY_UNSPECIFIED = 0,
ALL_UPSTREAM_TASKS_SUCCEEDED = 1,
ALL_UPSTREAM_TASKS_COMPLETED = 2
}
}
}
/** Properties of an ArtifactIteratorSpec. */
interface IArtifactIteratorSpec {
/** ArtifactIteratorSpec items */
items?: (ml_pipelines.ArtifactIteratorSpec.IItemsSpec|null);
/** ArtifactIteratorSpec itemInput */
itemInput?: (string|null);
}
/** Represents an ArtifactIteratorSpec. */
class ArtifactIteratorSpec implements IArtifactIteratorSpec {
/**
* Constructs a new ArtifactIteratorSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IArtifactIteratorSpec);
/** ArtifactIteratorSpec items. */
public items?: (ml_pipelines.ArtifactIteratorSpec.IItemsSpec|null);
/** ArtifactIteratorSpec itemInput. */
public itemInput: string;
/**
* Creates a new ArtifactIteratorSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ArtifactIteratorSpec instance
*/
public static create(properties?: ml_pipelines.IArtifactIteratorSpec): ml_pipelines.ArtifactIteratorSpec;
/**
* Encodes the specified ArtifactIteratorSpec message. Does not implicitly {@link ml_pipelines.ArtifactIteratorSpec.verify|verify} messages.
* @param message ArtifactIteratorSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IArtifactIteratorSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ArtifactIteratorSpec message, length delimited. Does not implicitly {@link ml_pipelines.ArtifactIteratorSpec.verify|verify} messages.
* @param message ArtifactIteratorSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IArtifactIteratorSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ArtifactIteratorSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ArtifactIteratorSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ArtifactIteratorSpec;
/**
* Decodes an ArtifactIteratorSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ArtifactIteratorSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ArtifactIteratorSpec;
/**
* Verifies an ArtifactIteratorSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ArtifactIteratorSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ArtifactIteratorSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ArtifactIteratorSpec;
/**
* Creates a plain object from an ArtifactIteratorSpec message. Also converts values to other types if specified.
* @param message ArtifactIteratorSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ArtifactIteratorSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ArtifactIteratorSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ArtifactIteratorSpec {
/** Properties of an ItemsSpec. */
interface IItemsSpec {
/** ItemsSpec inputArtifact */
inputArtifact?: (string|null);
}
/** Represents an ItemsSpec. */
class ItemsSpec implements IItemsSpec {
/**
* Constructs a new ItemsSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ArtifactIteratorSpec.IItemsSpec);
/** ItemsSpec inputArtifact. */
public inputArtifact: string;
/**
* Creates a new ItemsSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ItemsSpec instance
*/
public static create(properties?: ml_pipelines.ArtifactIteratorSpec.IItemsSpec): ml_pipelines.ArtifactIteratorSpec.ItemsSpec;
/**
* Encodes the specified ItemsSpec message. Does not implicitly {@link ml_pipelines.ArtifactIteratorSpec.ItemsSpec.verify|verify} messages.
* @param message ItemsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ArtifactIteratorSpec.IItemsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ItemsSpec message, length delimited. Does not implicitly {@link ml_pipelines.ArtifactIteratorSpec.ItemsSpec.verify|verify} messages.
* @param message ItemsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ArtifactIteratorSpec.IItemsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ItemsSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ItemsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ArtifactIteratorSpec.ItemsSpec;
/**
* Decodes an ItemsSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ItemsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ArtifactIteratorSpec.ItemsSpec;
/**
* Verifies an ItemsSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ItemsSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ItemsSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ArtifactIteratorSpec.ItemsSpec;
/**
* Creates a plain object from an ItemsSpec message. Also converts values to other types if specified.
* @param message ItemsSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ArtifactIteratorSpec.ItemsSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ItemsSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a ParameterIteratorSpec. */
interface IParameterIteratorSpec {
/** ParameterIteratorSpec items */
items?: (ml_pipelines.ParameterIteratorSpec.IItemsSpec|null);
/** ParameterIteratorSpec itemInput */
itemInput?: (string|null);
}
/** Represents a ParameterIteratorSpec. */
class ParameterIteratorSpec implements IParameterIteratorSpec {
/**
* Constructs a new ParameterIteratorSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IParameterIteratorSpec);
/** ParameterIteratorSpec items. */
public items?: (ml_pipelines.ParameterIteratorSpec.IItemsSpec|null);
/** ParameterIteratorSpec itemInput. */
public itemInput: string;
/**
* Creates a new ParameterIteratorSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ParameterIteratorSpec instance
*/
public static create(properties?: ml_pipelines.IParameterIteratorSpec): ml_pipelines.ParameterIteratorSpec;
/**
* Encodes the specified ParameterIteratorSpec message. Does not implicitly {@link ml_pipelines.ParameterIteratorSpec.verify|verify} messages.
* @param message ParameterIteratorSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IParameterIteratorSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ParameterIteratorSpec message, length delimited. Does not implicitly {@link ml_pipelines.ParameterIteratorSpec.verify|verify} messages.
* @param message ParameterIteratorSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IParameterIteratorSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ParameterIteratorSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ParameterIteratorSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ParameterIteratorSpec;
/**
* Decodes a ParameterIteratorSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ParameterIteratorSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ParameterIteratorSpec;
/**
* Verifies a ParameterIteratorSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ParameterIteratorSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ParameterIteratorSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ParameterIteratorSpec;
/**
* Creates a plain object from a ParameterIteratorSpec message. Also converts values to other types if specified.
* @param message ParameterIteratorSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ParameterIteratorSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ParameterIteratorSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ParameterIteratorSpec {
/** Properties of an ItemsSpec. */
interface IItemsSpec {
/** ItemsSpec raw */
raw?: (string|null);
/** ItemsSpec inputParameter */
inputParameter?: (string|null);
}
/** Represents an ItemsSpec. */
class ItemsSpec implements IItemsSpec {
/**
* Constructs a new ItemsSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ParameterIteratorSpec.IItemsSpec);
/** ItemsSpec raw. */
public raw?: (string|null);
/** ItemsSpec inputParameter. */
public inputParameter?: (string|null);
/** ItemsSpec kind. */
public kind?: ("raw"|"inputParameter");
/**
* Creates a new ItemsSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ItemsSpec instance
*/
public static create(properties?: ml_pipelines.ParameterIteratorSpec.IItemsSpec): ml_pipelines.ParameterIteratorSpec.ItemsSpec;
/**
* Encodes the specified ItemsSpec message. Does not implicitly {@link ml_pipelines.ParameterIteratorSpec.ItemsSpec.verify|verify} messages.
* @param message ItemsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ParameterIteratorSpec.IItemsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ItemsSpec message, length delimited. Does not implicitly {@link ml_pipelines.ParameterIteratorSpec.ItemsSpec.verify|verify} messages.
* @param message ItemsSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ParameterIteratorSpec.IItemsSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ItemsSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ItemsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ParameterIteratorSpec.ItemsSpec;
/**
* Decodes an ItemsSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ItemsSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ParameterIteratorSpec.ItemsSpec;
/**
* Verifies an ItemsSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ItemsSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ItemsSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ParameterIteratorSpec.ItemsSpec;
/**
* Creates a plain object from an ItemsSpec message. Also converts values to other types if specified.
* @param message ItemsSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ParameterIteratorSpec.ItemsSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ItemsSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a ComponentRef. */
interface IComponentRef {
/** ComponentRef name */
name?: (string|null);
}
/** Represents a ComponentRef. */
class ComponentRef implements IComponentRef {
/**
* Constructs a new ComponentRef.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IComponentRef);
/** ComponentRef name. */
public name: string;
/**
* Creates a new ComponentRef instance using the specified properties.
* @param [properties] Properties to set
* @returns ComponentRef instance
*/
public static create(properties?: ml_pipelines.IComponentRef): ml_pipelines.ComponentRef;
/**
* Encodes the specified ComponentRef message. Does not implicitly {@link ml_pipelines.ComponentRef.verify|verify} messages.
* @param message ComponentRef message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IComponentRef, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ComponentRef message, length delimited. Does not implicitly {@link ml_pipelines.ComponentRef.verify|verify} messages.
* @param message ComponentRef message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IComponentRef, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ComponentRef message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ComponentRef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ComponentRef;
/**
* Decodes a ComponentRef message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ComponentRef
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ComponentRef;
/**
* Verifies a ComponentRef message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ComponentRef message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ComponentRef
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ComponentRef;
/**
* Creates a plain object from a ComponentRef message. Also converts values to other types if specified.
* @param message ComponentRef
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ComponentRef, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ComponentRef to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PipelineInfo. */
interface IPipelineInfo {
/** PipelineInfo name */
name?: (string|null);
}
/** Represents a PipelineInfo. */
class PipelineInfo implements IPipelineInfo {
/**
* Constructs a new PipelineInfo.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IPipelineInfo);
/** PipelineInfo name. */
public name: string;
/**
* Creates a new PipelineInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns PipelineInfo instance
*/
public static create(properties?: ml_pipelines.IPipelineInfo): ml_pipelines.PipelineInfo;
/**
* Encodes the specified PipelineInfo message. Does not implicitly {@link ml_pipelines.PipelineInfo.verify|verify} messages.
* @param message PipelineInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IPipelineInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PipelineInfo message, length delimited. Does not implicitly {@link ml_pipelines.PipelineInfo.verify|verify} messages.
* @param message PipelineInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IPipelineInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PipelineInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PipelineInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineInfo;
/**
* Decodes a PipelineInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PipelineInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineInfo;
/**
* Verifies a PipelineInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PipelineInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PipelineInfo
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineInfo;
/**
* Creates a plain object from a PipelineInfo message. Also converts values to other types if specified.
* @param message PipelineInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PipelineInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an ArtifactTypeSchema. */
interface IArtifactTypeSchema {
/** ArtifactTypeSchema schemaTitle */
schemaTitle?: (string|null);
/** ArtifactTypeSchema schemaUri */
schemaUri?: (string|null);
/** ArtifactTypeSchema instanceSchema */
instanceSchema?: (string|null);
/** ArtifactTypeSchema schemaVersion */
schemaVersion?: (string|null);
}
/** Represents an ArtifactTypeSchema. */
class ArtifactTypeSchema implements IArtifactTypeSchema {
/**
* Constructs a new ArtifactTypeSchema.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IArtifactTypeSchema);
/** ArtifactTypeSchema schemaTitle. */
public schemaTitle?: (string|null);
/** ArtifactTypeSchema schemaUri. */
public schemaUri?: (string|null);
/** ArtifactTypeSchema instanceSchema. */
public instanceSchema?: (string|null);
/** ArtifactTypeSchema schemaVersion. */
public schemaVersion: string;
/** ArtifactTypeSchema kind. */
public kind?: ("schemaTitle"|"schemaUri"|"instanceSchema");
/**
* Creates a new ArtifactTypeSchema instance using the specified properties.
* @param [properties] Properties to set
* @returns ArtifactTypeSchema instance
*/
public static create(properties?: ml_pipelines.IArtifactTypeSchema): ml_pipelines.ArtifactTypeSchema;
/**
* Encodes the specified ArtifactTypeSchema message. Does not implicitly {@link ml_pipelines.ArtifactTypeSchema.verify|verify} messages.
* @param message ArtifactTypeSchema message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IArtifactTypeSchema, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ArtifactTypeSchema message, length delimited. Does not implicitly {@link ml_pipelines.ArtifactTypeSchema.verify|verify} messages.
* @param message ArtifactTypeSchema message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IArtifactTypeSchema, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ArtifactTypeSchema message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ArtifactTypeSchema
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ArtifactTypeSchema;
/**
* Decodes an ArtifactTypeSchema message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ArtifactTypeSchema
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ArtifactTypeSchema;
/**
* Verifies an ArtifactTypeSchema message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ArtifactTypeSchema message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ArtifactTypeSchema
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ArtifactTypeSchema;
/**
* Creates a plain object from an ArtifactTypeSchema message. Also converts values to other types if specified.
* @param message ArtifactTypeSchema
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ArtifactTypeSchema, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ArtifactTypeSchema to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PipelineTaskInfo. */
interface IPipelineTaskInfo {
/** PipelineTaskInfo name */
name?: (string|null);
}
/** Represents a PipelineTaskInfo. */
class PipelineTaskInfo implements IPipelineTaskInfo {
/**
* Constructs a new PipelineTaskInfo.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IPipelineTaskInfo);
/** PipelineTaskInfo name. */
public name: string;
/**
* Creates a new PipelineTaskInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns PipelineTaskInfo instance
*/
public static create(properties?: ml_pipelines.IPipelineTaskInfo): ml_pipelines.PipelineTaskInfo;
/**
* Encodes the specified PipelineTaskInfo message. Does not implicitly {@link ml_pipelines.PipelineTaskInfo.verify|verify} messages.
* @param message PipelineTaskInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IPipelineTaskInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PipelineTaskInfo message, length delimited. Does not implicitly {@link ml_pipelines.PipelineTaskInfo.verify|verify} messages.
* @param message PipelineTaskInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IPipelineTaskInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PipelineTaskInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PipelineTaskInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineTaskInfo;
/**
* Decodes a PipelineTaskInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PipelineTaskInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineTaskInfo;
/**
* Verifies a PipelineTaskInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PipelineTaskInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PipelineTaskInfo
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineTaskInfo;
/**
* Creates a plain object from a PipelineTaskInfo message. Also converts values to other types if specified.
* @param message PipelineTaskInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineTaskInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PipelineTaskInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ValueOrRuntimeParameter. */
interface IValueOrRuntimeParameter {
/** ValueOrRuntimeParameter constantValue */
constantValue?: (ml_pipelines.IValue|null);
/** ValueOrRuntimeParameter runtimeParameter */
runtimeParameter?: (string|null);
}
/** Represents a ValueOrRuntimeParameter. */
class ValueOrRuntimeParameter implements IValueOrRuntimeParameter {
/**
* Constructs a new ValueOrRuntimeParameter.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IValueOrRuntimeParameter);
/** ValueOrRuntimeParameter constantValue. */
public constantValue?: (ml_pipelines.IValue|null);
/** ValueOrRuntimeParameter runtimeParameter. */
public runtimeParameter?: (string|null);
/** ValueOrRuntimeParameter value. */
public value?: ("constantValue"|"runtimeParameter");
/**
* Creates a new ValueOrRuntimeParameter instance using the specified properties.
* @param [properties] Properties to set
* @returns ValueOrRuntimeParameter instance
*/
public static create(properties?: ml_pipelines.IValueOrRuntimeParameter): ml_pipelines.ValueOrRuntimeParameter;
/**
* Encodes the specified ValueOrRuntimeParameter message. Does not implicitly {@link ml_pipelines.ValueOrRuntimeParameter.verify|verify} messages.
* @param message ValueOrRuntimeParameter message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IValueOrRuntimeParameter, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ValueOrRuntimeParameter message, length delimited. Does not implicitly {@link ml_pipelines.ValueOrRuntimeParameter.verify|verify} messages.
* @param message ValueOrRuntimeParameter message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IValueOrRuntimeParameter, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ValueOrRuntimeParameter message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ValueOrRuntimeParameter
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ValueOrRuntimeParameter;
/**
* Decodes a ValueOrRuntimeParameter message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ValueOrRuntimeParameter
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ValueOrRuntimeParameter;
/**
* Verifies a ValueOrRuntimeParameter message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ValueOrRuntimeParameter message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ValueOrRuntimeParameter
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ValueOrRuntimeParameter;
/**
* Creates a plain object from a ValueOrRuntimeParameter message. Also converts values to other types if specified.
* @param message ValueOrRuntimeParameter
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ValueOrRuntimeParameter, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ValueOrRuntimeParameter to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PipelineDeploymentConfig. */
interface IPipelineDeploymentConfig {
/** PipelineDeploymentConfig executors */
executors?: ({ [k: string]: ml_pipelines.PipelineDeploymentConfig.IExecutorSpec }|null);
}
/** Represents a PipelineDeploymentConfig. */
class PipelineDeploymentConfig implements IPipelineDeploymentConfig {
/**
* Constructs a new PipelineDeploymentConfig.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IPipelineDeploymentConfig);
/** PipelineDeploymentConfig executors. */
public executors: { [k: string]: ml_pipelines.PipelineDeploymentConfig.IExecutorSpec };
/**
* Creates a new PipelineDeploymentConfig instance using the specified properties.
* @param [properties] Properties to set
* @returns PipelineDeploymentConfig instance
*/
public static create(properties?: ml_pipelines.IPipelineDeploymentConfig): ml_pipelines.PipelineDeploymentConfig;
/**
* Encodes the specified PipelineDeploymentConfig message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.verify|verify} messages.
* @param message PipelineDeploymentConfig message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IPipelineDeploymentConfig, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PipelineDeploymentConfig message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.verify|verify} messages.
* @param message PipelineDeploymentConfig message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IPipelineDeploymentConfig, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PipelineDeploymentConfig message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PipelineDeploymentConfig
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig;
/**
* Decodes a PipelineDeploymentConfig message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PipelineDeploymentConfig
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig;
/**
* Verifies a PipelineDeploymentConfig message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PipelineDeploymentConfig message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PipelineDeploymentConfig
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig;
/**
* Creates a plain object from a PipelineDeploymentConfig message. Also converts values to other types if specified.
* @param message PipelineDeploymentConfig
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PipelineDeploymentConfig to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PipelineDeploymentConfig {
/** Properties of a PipelineContainerSpec. */
interface IPipelineContainerSpec {
/** PipelineContainerSpec image */
image?: (string|null);
/** PipelineContainerSpec command */
command?: (string[]|null);
/** PipelineContainerSpec args */
args?: (string[]|null);
/** PipelineContainerSpec lifecycle */
lifecycle?: (ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ILifecycle|null);
/** PipelineContainerSpec resources */
resources?: (ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.IResourceSpec|null);
}
/** Represents a PipelineContainerSpec. */
class PipelineContainerSpec implements IPipelineContainerSpec {
/**
* Constructs a new PipelineContainerSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineDeploymentConfig.IPipelineContainerSpec);
/** PipelineContainerSpec image. */
public image: string;
/** PipelineContainerSpec command. */
public command: string[];
/** PipelineContainerSpec args. */
public args: string[];
/** PipelineContainerSpec lifecycle. */
public lifecycle?: (ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ILifecycle|null);
/** PipelineContainerSpec resources. */
public resources?: (ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.IResourceSpec|null);
/**
* Creates a new PipelineContainerSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns PipelineContainerSpec instance
*/
public static create(properties?: ml_pipelines.PipelineDeploymentConfig.IPipelineContainerSpec): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec;
/**
* Encodes the specified PipelineContainerSpec message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.verify|verify} messages.
* @param message PipelineContainerSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineDeploymentConfig.IPipelineContainerSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PipelineContainerSpec message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.verify|verify} messages.
* @param message PipelineContainerSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineDeploymentConfig.IPipelineContainerSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PipelineContainerSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PipelineContainerSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec;
/**
* Decodes a PipelineContainerSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PipelineContainerSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec;
/**
* Verifies a PipelineContainerSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PipelineContainerSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PipelineContainerSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec;
/**
* Creates a plain object from a PipelineContainerSpec message. Also converts values to other types if specified.
* @param message PipelineContainerSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PipelineContainerSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PipelineContainerSpec {
/** Properties of a Lifecycle. */
interface ILifecycle {
/** Lifecycle preCacheCheck */
preCacheCheck?: (ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.IExec|null);
}
/** Represents a Lifecycle. */
class Lifecycle implements ILifecycle {
/**
* Constructs a new Lifecycle.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ILifecycle);
/** Lifecycle preCacheCheck. */
public preCacheCheck?: (ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.IExec|null);
/**
* Creates a new Lifecycle instance using the specified properties.
* @param [properties] Properties to set
* @returns Lifecycle instance
*/
public static create(properties?: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ILifecycle): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle;
/**
* Encodes the specified Lifecycle message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.verify|verify} messages.
* @param message Lifecycle message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ILifecycle, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Lifecycle message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.verify|verify} messages.
* @param message Lifecycle message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ILifecycle, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Lifecycle message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Lifecycle
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle;
/**
* Decodes a Lifecycle message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Lifecycle
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle;
/**
* Verifies a Lifecycle message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Lifecycle message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Lifecycle
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle;
/**
* Creates a plain object from a Lifecycle message. Also converts values to other types if specified.
* @param message Lifecycle
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Lifecycle to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace Lifecycle {
/** Properties of an Exec. */
interface IExec {
/** Exec command */
command?: (string[]|null);
/** Exec args */
args?: (string[]|null);
}
/** Represents an Exec. */
class Exec implements IExec {
/**
* Constructs a new Exec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.IExec);
/** Exec command. */
public command: string[];
/** Exec args. */
public args: string[];
/**
* Creates a new Exec instance using the specified properties.
* @param [properties] Properties to set
* @returns Exec instance
*/
public static create(properties?: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.IExec): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.Exec;
/**
* Encodes the specified Exec message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.Exec.verify|verify} messages.
* @param message Exec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.IExec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Exec message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.Exec.verify|verify} messages.
* @param message Exec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.IExec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Exec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Exec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.Exec;
/**
* Decodes an Exec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Exec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.Exec;
/**
* Verifies an Exec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Exec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Exec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.Exec;
/**
* Creates a plain object from an Exec message. Also converts values to other types if specified.
* @param message Exec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.Lifecycle.Exec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Exec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a ResourceSpec. */
interface IResourceSpec {
/** ResourceSpec cpuLimit */
cpuLimit?: (number|null);
/** ResourceSpec memoryLimit */
memoryLimit?: (number|null);
/** ResourceSpec accelerator */
accelerator?: (ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.IAcceleratorConfig|null);
}
/** Represents a ResourceSpec. */
class ResourceSpec implements IResourceSpec {
/**
* Constructs a new ResourceSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.IResourceSpec);
/** ResourceSpec cpuLimit. */
public cpuLimit: number;
/** ResourceSpec memoryLimit. */
public memoryLimit: number;
/** ResourceSpec accelerator. */
public accelerator?: (ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.IAcceleratorConfig|null);
/**
* Creates a new ResourceSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ResourceSpec instance
*/
public static create(properties?: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.IResourceSpec): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec;
/**
* Encodes the specified ResourceSpec message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.verify|verify} messages.
* @param message ResourceSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.IResourceSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ResourceSpec message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.verify|verify} messages.
* @param message ResourceSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.IResourceSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ResourceSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ResourceSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec;
/**
* Decodes a ResourceSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ResourceSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec;
/**
* Verifies a ResourceSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ResourceSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ResourceSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec;
/**
* Creates a plain object from a ResourceSpec message. Also converts values to other types if specified.
* @param message ResourceSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ResourceSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ResourceSpec {
/** Properties of an AcceleratorConfig. */
interface IAcceleratorConfig {
/** AcceleratorConfig type */
type?: (string|null);
/** AcceleratorConfig count */
count?: (number|Long|null);
}
/** Represents an AcceleratorConfig. */
class AcceleratorConfig implements IAcceleratorConfig {
/**
* Constructs a new AcceleratorConfig.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.IAcceleratorConfig);
/** AcceleratorConfig type. */
public type: string;
/** AcceleratorConfig count. */
public count: (number|Long);
/**
* Creates a new AcceleratorConfig instance using the specified properties.
* @param [properties] Properties to set
* @returns AcceleratorConfig instance
*/
public static create(properties?: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.IAcceleratorConfig): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.AcceleratorConfig;
/**
* Encodes the specified AcceleratorConfig message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.AcceleratorConfig.verify|verify} messages.
* @param message AcceleratorConfig message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.IAcceleratorConfig, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AcceleratorConfig message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.AcceleratorConfig.verify|verify} messages.
* @param message AcceleratorConfig message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.IAcceleratorConfig, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AcceleratorConfig message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AcceleratorConfig
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.AcceleratorConfig;
/**
* Decodes an AcceleratorConfig message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AcceleratorConfig
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.AcceleratorConfig;
/**
* Verifies an AcceleratorConfig message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AcceleratorConfig message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AcceleratorConfig
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.AcceleratorConfig;
/**
* Creates a plain object from an AcceleratorConfig message. Also converts values to other types if specified.
* @param message AcceleratorConfig
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig.PipelineContainerSpec.ResourceSpec.AcceleratorConfig, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AcceleratorConfig to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
}
/** Properties of an ImporterSpec. */
interface IImporterSpec {
/** ImporterSpec artifactUri */
artifactUri?: (ml_pipelines.IValueOrRuntimeParameter|null);
/** ImporterSpec typeSchema */
typeSchema?: (ml_pipelines.IArtifactTypeSchema|null);
/** ImporterSpec properties */
properties?: ({ [k: string]: ml_pipelines.IValueOrRuntimeParameter }|null);
/** ImporterSpec customProperties */
customProperties?: ({ [k: string]: ml_pipelines.IValueOrRuntimeParameter }|null);
/** ImporterSpec metadata */
metadata?: (google.protobuf.IStruct|null);
/** ImporterSpec reimport */
reimport?: (boolean|null);
}
/** Represents an ImporterSpec. */
class ImporterSpec implements IImporterSpec {
/**
* Constructs a new ImporterSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineDeploymentConfig.IImporterSpec);
/** ImporterSpec artifactUri. */
public artifactUri?: (ml_pipelines.IValueOrRuntimeParameter|null);
/** ImporterSpec typeSchema. */
public typeSchema?: (ml_pipelines.IArtifactTypeSchema|null);
/** ImporterSpec properties. */
public properties: { [k: string]: ml_pipelines.IValueOrRuntimeParameter };
/** ImporterSpec customProperties. */
public customProperties: { [k: string]: ml_pipelines.IValueOrRuntimeParameter };
/** ImporterSpec metadata. */
public metadata?: (google.protobuf.IStruct|null);
/** ImporterSpec reimport. */
public reimport: boolean;
/**
* Creates a new ImporterSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ImporterSpec instance
*/
public static create(properties?: ml_pipelines.PipelineDeploymentConfig.IImporterSpec): ml_pipelines.PipelineDeploymentConfig.ImporterSpec;
/**
* Encodes the specified ImporterSpec message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.ImporterSpec.verify|verify} messages.
* @param message ImporterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineDeploymentConfig.IImporterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ImporterSpec message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.ImporterSpec.verify|verify} messages.
* @param message ImporterSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineDeploymentConfig.IImporterSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ImporterSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ImporterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig.ImporterSpec;
/**
* Decodes an ImporterSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ImporterSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig.ImporterSpec;
/**
* Verifies an ImporterSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ImporterSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ImporterSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig.ImporterSpec;
/**
* Creates a plain object from an ImporterSpec message. Also converts values to other types if specified.
* @param message ImporterSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig.ImporterSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ImporterSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ResolverSpec. */
interface IResolverSpec {
/** ResolverSpec outputArtifactQueries */
outputArtifactQueries?: ({ [k: string]: ml_pipelines.PipelineDeploymentConfig.ResolverSpec.IArtifactQuerySpec }|null);
}
/** Represents a ResolverSpec. */
class ResolverSpec implements IResolverSpec {
/**
* Constructs a new ResolverSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineDeploymentConfig.IResolverSpec);
/** ResolverSpec outputArtifactQueries. */
public outputArtifactQueries: { [k: string]: ml_pipelines.PipelineDeploymentConfig.ResolverSpec.IArtifactQuerySpec };
/**
* Creates a new ResolverSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ResolverSpec instance
*/
public static create(properties?: ml_pipelines.PipelineDeploymentConfig.IResolverSpec): ml_pipelines.PipelineDeploymentConfig.ResolverSpec;
/**
* Encodes the specified ResolverSpec message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.ResolverSpec.verify|verify} messages.
* @param message ResolverSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineDeploymentConfig.IResolverSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ResolverSpec message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.ResolverSpec.verify|verify} messages.
* @param message ResolverSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineDeploymentConfig.IResolverSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ResolverSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ResolverSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig.ResolverSpec;
/**
* Decodes a ResolverSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ResolverSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig.ResolverSpec;
/**
* Verifies a ResolverSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ResolverSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ResolverSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig.ResolverSpec;
/**
* Creates a plain object from a ResolverSpec message. Also converts values to other types if specified.
* @param message ResolverSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig.ResolverSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ResolverSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ResolverSpec {
/** Properties of an ArtifactQuerySpec. */
interface IArtifactQuerySpec {
/** ArtifactQuerySpec filter */
filter?: (string|null);
/** ArtifactQuerySpec limit */
limit?: (number|null);
}
/** Represents an ArtifactQuerySpec. */
class ArtifactQuerySpec implements IArtifactQuerySpec {
/**
* Constructs a new ArtifactQuerySpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineDeploymentConfig.ResolverSpec.IArtifactQuerySpec);
/** ArtifactQuerySpec filter. */
public filter: string;
/** ArtifactQuerySpec limit. */
public limit: number;
/**
* Creates a new ArtifactQuerySpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ArtifactQuerySpec instance
*/
public static create(properties?: ml_pipelines.PipelineDeploymentConfig.ResolverSpec.IArtifactQuerySpec): ml_pipelines.PipelineDeploymentConfig.ResolverSpec.ArtifactQuerySpec;
/**
* Encodes the specified ArtifactQuerySpec message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.ResolverSpec.ArtifactQuerySpec.verify|verify} messages.
* @param message ArtifactQuerySpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineDeploymentConfig.ResolverSpec.IArtifactQuerySpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ArtifactQuerySpec message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.ResolverSpec.ArtifactQuerySpec.verify|verify} messages.
* @param message ArtifactQuerySpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineDeploymentConfig.ResolverSpec.IArtifactQuerySpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ArtifactQuerySpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ArtifactQuerySpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig.ResolverSpec.ArtifactQuerySpec;
/**
* Decodes an ArtifactQuerySpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ArtifactQuerySpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig.ResolverSpec.ArtifactQuerySpec;
/**
* Verifies an ArtifactQuerySpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ArtifactQuerySpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ArtifactQuerySpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig.ResolverSpec.ArtifactQuerySpec;
/**
* Creates a plain object from an ArtifactQuerySpec message. Also converts values to other types if specified.
* @param message ArtifactQuerySpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig.ResolverSpec.ArtifactQuerySpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ArtifactQuerySpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a AIPlatformCustomJobSpec. */
interface IAIPlatformCustomJobSpec {
/** AIPlatformCustomJobSpec customJob */
customJob?: (google.protobuf.IStruct|null);
}
/** Represents a AIPlatformCustomJobSpec. */
class AIPlatformCustomJobSpec implements IAIPlatformCustomJobSpec {
/**
* Constructs a new AIPlatformCustomJobSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineDeploymentConfig.IAIPlatformCustomJobSpec);
/** AIPlatformCustomJobSpec customJob. */
public customJob?: (google.protobuf.IStruct|null);
/**
* Creates a new AIPlatformCustomJobSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns AIPlatformCustomJobSpec instance
*/
public static create(properties?: ml_pipelines.PipelineDeploymentConfig.IAIPlatformCustomJobSpec): ml_pipelines.PipelineDeploymentConfig.AIPlatformCustomJobSpec;
/**
* Encodes the specified AIPlatformCustomJobSpec message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.AIPlatformCustomJobSpec.verify|verify} messages.
* @param message AIPlatformCustomJobSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineDeploymentConfig.IAIPlatformCustomJobSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AIPlatformCustomJobSpec message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.AIPlatformCustomJobSpec.verify|verify} messages.
* @param message AIPlatformCustomJobSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineDeploymentConfig.IAIPlatformCustomJobSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a AIPlatformCustomJobSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AIPlatformCustomJobSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig.AIPlatformCustomJobSpec;
/**
* Decodes a AIPlatformCustomJobSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AIPlatformCustomJobSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig.AIPlatformCustomJobSpec;
/**
* Verifies a AIPlatformCustomJobSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a AIPlatformCustomJobSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AIPlatformCustomJobSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig.AIPlatformCustomJobSpec;
/**
* Creates a plain object from a AIPlatformCustomJobSpec message. Also converts values to other types if specified.
* @param message AIPlatformCustomJobSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig.AIPlatformCustomJobSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AIPlatformCustomJobSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an ExecutorSpec. */
interface IExecutorSpec {
/** ExecutorSpec container */
container?: (ml_pipelines.PipelineDeploymentConfig.IPipelineContainerSpec|null);
/** ExecutorSpec importer */
importer?: (ml_pipelines.PipelineDeploymentConfig.IImporterSpec|null);
/** ExecutorSpec resolver */
resolver?: (ml_pipelines.PipelineDeploymentConfig.IResolverSpec|null);
/** ExecutorSpec customJob */
customJob?: (ml_pipelines.PipelineDeploymentConfig.IAIPlatformCustomJobSpec|null);
}
/** Represents an ExecutorSpec. */
class ExecutorSpec implements IExecutorSpec {
/**
* Constructs a new ExecutorSpec.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.PipelineDeploymentConfig.IExecutorSpec);
/** ExecutorSpec container. */
public container?: (ml_pipelines.PipelineDeploymentConfig.IPipelineContainerSpec|null);
/** ExecutorSpec importer. */
public importer?: (ml_pipelines.PipelineDeploymentConfig.IImporterSpec|null);
/** ExecutorSpec resolver. */
public resolver?: (ml_pipelines.PipelineDeploymentConfig.IResolverSpec|null);
/** ExecutorSpec customJob. */
public customJob?: (ml_pipelines.PipelineDeploymentConfig.IAIPlatformCustomJobSpec|null);
/** ExecutorSpec spec. */
public spec?: ("container"|"importer"|"resolver"|"customJob");
/**
* Creates a new ExecutorSpec instance using the specified properties.
* @param [properties] Properties to set
* @returns ExecutorSpec instance
*/
public static create(properties?: ml_pipelines.PipelineDeploymentConfig.IExecutorSpec): ml_pipelines.PipelineDeploymentConfig.ExecutorSpec;
/**
* Encodes the specified ExecutorSpec message. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.ExecutorSpec.verify|verify} messages.
* @param message ExecutorSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.PipelineDeploymentConfig.IExecutorSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ExecutorSpec message, length delimited. Does not implicitly {@link ml_pipelines.PipelineDeploymentConfig.ExecutorSpec.verify|verify} messages.
* @param message ExecutorSpec message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.PipelineDeploymentConfig.IExecutorSpec, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ExecutorSpec message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ExecutorSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineDeploymentConfig.ExecutorSpec;
/**
* Decodes an ExecutorSpec message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ExecutorSpec
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineDeploymentConfig.ExecutorSpec;
/**
* Verifies an ExecutorSpec message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ExecutorSpec message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ExecutorSpec
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineDeploymentConfig.ExecutorSpec;
/**
* Creates a plain object from an ExecutorSpec message. Also converts values to other types if specified.
* @param message ExecutorSpec
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineDeploymentConfig.ExecutorSpec, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ExecutorSpec to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of a Value. */
interface IValue {
/** Value intValue */
intValue?: (number|Long|null);
/** Value doubleValue */
doubleValue?: (number|null);
/** Value stringValue */
stringValue?: (string|null);
}
/** Represents a Value. */
class Value implements IValue {
/**
* Constructs a new Value.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IValue);
/** Value intValue. */
public intValue?: (number|Long|null);
/** Value doubleValue. */
public doubleValue?: (number|null);
/** Value stringValue. */
public stringValue?: (string|null);
/** Value value. */
public value?: ("intValue"|"doubleValue"|"stringValue");
/**
* Creates a new Value instance using the specified properties.
* @param [properties] Properties to set
* @returns Value instance
*/
public static create(properties?: ml_pipelines.IValue): ml_pipelines.Value;
/**
* Encodes the specified Value message. Does not implicitly {@link ml_pipelines.Value.verify|verify} messages.
* @param message Value message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IValue, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Value message, length delimited. Does not implicitly {@link ml_pipelines.Value.verify|verify} messages.
* @param message Value message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IValue, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Value message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Value
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.Value;
/**
* Decodes a Value message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Value
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.Value;
/**
* Verifies a Value message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Value message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Value
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.Value;
/**
* Creates a plain object from a Value message. Also converts values to other types if specified.
* @param message Value
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.Value, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Value to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a RuntimeArtifact. */
interface IRuntimeArtifact {
/** RuntimeArtifact name */
name?: (string|null);
/** RuntimeArtifact type */
type?: (ml_pipelines.IArtifactTypeSchema|null);
/** RuntimeArtifact uri */
uri?: (string|null);
/** RuntimeArtifact properties */
properties?: ({ [k: string]: ml_pipelines.IValue }|null);
/** RuntimeArtifact customProperties */
customProperties?: ({ [k: string]: ml_pipelines.IValue }|null);
/** RuntimeArtifact metadata */
metadata?: (google.protobuf.IStruct|null);
}
/** Represents a RuntimeArtifact. */
class RuntimeArtifact implements IRuntimeArtifact {
/**
* Constructs a new RuntimeArtifact.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IRuntimeArtifact);
/** RuntimeArtifact name. */
public name: string;
/** RuntimeArtifact type. */
public type?: (ml_pipelines.IArtifactTypeSchema|null);
/** RuntimeArtifact uri. */
public uri: string;
/** RuntimeArtifact properties. */
public properties: { [k: string]: ml_pipelines.IValue };
/** RuntimeArtifact customProperties. */
public customProperties: { [k: string]: ml_pipelines.IValue };
/** RuntimeArtifact metadata. */
public metadata?: (google.protobuf.IStruct|null);
/**
* Creates a new RuntimeArtifact instance using the specified properties.
* @param [properties] Properties to set
* @returns RuntimeArtifact instance
*/
public static create(properties?: ml_pipelines.IRuntimeArtifact): ml_pipelines.RuntimeArtifact;
/**
* Encodes the specified RuntimeArtifact message. Does not implicitly {@link ml_pipelines.RuntimeArtifact.verify|verify} messages.
* @param message RuntimeArtifact message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IRuntimeArtifact, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified RuntimeArtifact message, length delimited. Does not implicitly {@link ml_pipelines.RuntimeArtifact.verify|verify} messages.
* @param message RuntimeArtifact message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IRuntimeArtifact, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a RuntimeArtifact message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns RuntimeArtifact
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.RuntimeArtifact;
/**
* Decodes a RuntimeArtifact message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns RuntimeArtifact
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.RuntimeArtifact;
/**
* Verifies a RuntimeArtifact message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a RuntimeArtifact message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns RuntimeArtifact
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.RuntimeArtifact;
/**
* Creates a plain object from a RuntimeArtifact message. Also converts values to other types if specified.
* @param message RuntimeArtifact
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.RuntimeArtifact, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this RuntimeArtifact to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an ArtifactList. */
interface IArtifactList {
/** ArtifactList artifacts */
artifacts?: (ml_pipelines.IRuntimeArtifact[]|null);
}
/** Represents an ArtifactList. */
class ArtifactList implements IArtifactList {
/**
* Constructs a new ArtifactList.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IArtifactList);
/** ArtifactList artifacts. */
public artifacts: ml_pipelines.IRuntimeArtifact[];
/**
* Creates a new ArtifactList instance using the specified properties.
* @param [properties] Properties to set
* @returns ArtifactList instance
*/
public static create(properties?: ml_pipelines.IArtifactList): ml_pipelines.ArtifactList;
/**
* Encodes the specified ArtifactList message. Does not implicitly {@link ml_pipelines.ArtifactList.verify|verify} messages.
* @param message ArtifactList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IArtifactList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ArtifactList message, length delimited. Does not implicitly {@link ml_pipelines.ArtifactList.verify|verify} messages.
* @param message ArtifactList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IArtifactList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ArtifactList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ArtifactList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ArtifactList;
/**
* Decodes an ArtifactList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ArtifactList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ArtifactList;
/**
* Verifies an ArtifactList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ArtifactList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ArtifactList
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ArtifactList;
/**
* Creates a plain object from an ArtifactList message. Also converts values to other types if specified.
* @param message ArtifactList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ArtifactList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ArtifactList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an ExecutorInput. */
interface IExecutorInput {
/** ExecutorInput inputs */
inputs?: (ml_pipelines.ExecutorInput.IInputs|null);
/** ExecutorInput outputs */
outputs?: (ml_pipelines.ExecutorInput.IOutputs|null);
}
/** Represents an ExecutorInput. */
class ExecutorInput implements IExecutorInput {
/**
* Constructs a new ExecutorInput.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IExecutorInput);
/** ExecutorInput inputs. */
public inputs?: (ml_pipelines.ExecutorInput.IInputs|null);
/** ExecutorInput outputs. */
public outputs?: (ml_pipelines.ExecutorInput.IOutputs|null);
/**
* Creates a new ExecutorInput instance using the specified properties.
* @param [properties] Properties to set
* @returns ExecutorInput instance
*/
public static create(properties?: ml_pipelines.IExecutorInput): ml_pipelines.ExecutorInput;
/**
* Encodes the specified ExecutorInput message. Does not implicitly {@link ml_pipelines.ExecutorInput.verify|verify} messages.
* @param message ExecutorInput message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IExecutorInput, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ExecutorInput message, length delimited. Does not implicitly {@link ml_pipelines.ExecutorInput.verify|verify} messages.
* @param message ExecutorInput message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IExecutorInput, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ExecutorInput message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ExecutorInput
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ExecutorInput;
/**
* Decodes an ExecutorInput message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ExecutorInput
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ExecutorInput;
/**
* Verifies an ExecutorInput message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ExecutorInput message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ExecutorInput
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ExecutorInput;
/**
* Creates a plain object from an ExecutorInput message. Also converts values to other types if specified.
* @param message ExecutorInput
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ExecutorInput, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ExecutorInput to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace ExecutorInput {
/** Properties of an Inputs. */
interface IInputs {
/** Inputs parameters */
parameters?: ({ [k: string]: ml_pipelines.IValue }|null);
/** Inputs artifacts */
artifacts?: ({ [k: string]: ml_pipelines.IArtifactList }|null);
}
/** Represents an Inputs. */
class Inputs implements IInputs {
/**
* Constructs a new Inputs.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ExecutorInput.IInputs);
/** Inputs parameters. */
public parameters: { [k: string]: ml_pipelines.IValue };
/** Inputs artifacts. */
public artifacts: { [k: string]: ml_pipelines.IArtifactList };
/**
* Creates a new Inputs instance using the specified properties.
* @param [properties] Properties to set
* @returns Inputs instance
*/
public static create(properties?: ml_pipelines.ExecutorInput.IInputs): ml_pipelines.ExecutorInput.Inputs;
/**
* Encodes the specified Inputs message. Does not implicitly {@link ml_pipelines.ExecutorInput.Inputs.verify|verify} messages.
* @param message Inputs message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ExecutorInput.IInputs, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Inputs message, length delimited. Does not implicitly {@link ml_pipelines.ExecutorInput.Inputs.verify|verify} messages.
* @param message Inputs message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ExecutorInput.IInputs, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Inputs message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Inputs
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ExecutorInput.Inputs;
/**
* Decodes an Inputs message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Inputs
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ExecutorInput.Inputs;
/**
* Verifies an Inputs message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Inputs message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Inputs
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ExecutorInput.Inputs;
/**
* Creates a plain object from an Inputs message. Also converts values to other types if specified.
* @param message Inputs
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ExecutorInput.Inputs, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Inputs to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an OutputParameter. */
interface IOutputParameter {
/** OutputParameter outputFile */
outputFile?: (string|null);
}
/** Represents an OutputParameter. */
class OutputParameter implements IOutputParameter {
/**
* Constructs a new OutputParameter.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ExecutorInput.IOutputParameter);
/** OutputParameter outputFile. */
public outputFile: string;
/**
* Creates a new OutputParameter instance using the specified properties.
* @param [properties] Properties to set
* @returns OutputParameter instance
*/
public static create(properties?: ml_pipelines.ExecutorInput.IOutputParameter): ml_pipelines.ExecutorInput.OutputParameter;
/**
* Encodes the specified OutputParameter message. Does not implicitly {@link ml_pipelines.ExecutorInput.OutputParameter.verify|verify} messages.
* @param message OutputParameter message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ExecutorInput.IOutputParameter, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified OutputParameter message, length delimited. Does not implicitly {@link ml_pipelines.ExecutorInput.OutputParameter.verify|verify} messages.
* @param message OutputParameter message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ExecutorInput.IOutputParameter, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an OutputParameter message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns OutputParameter
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ExecutorInput.OutputParameter;
/**
* Decodes an OutputParameter message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns OutputParameter
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ExecutorInput.OutputParameter;
/**
* Verifies an OutputParameter message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an OutputParameter message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns OutputParameter
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ExecutorInput.OutputParameter;
/**
* Creates a plain object from an OutputParameter message. Also converts values to other types if specified.
* @param message OutputParameter
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ExecutorInput.OutputParameter, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this OutputParameter to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an Outputs. */
interface IOutputs {
/** Outputs parameters */
parameters?: ({ [k: string]: ml_pipelines.ExecutorInput.IOutputParameter }|null);
/** Outputs artifacts */
artifacts?: ({ [k: string]: ml_pipelines.IArtifactList }|null);
/** Outputs outputFile */
outputFile?: (string|null);
}
/** Represents an Outputs. */
class Outputs implements IOutputs {
/**
* Constructs a new Outputs.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.ExecutorInput.IOutputs);
/** Outputs parameters. */
public parameters: { [k: string]: ml_pipelines.ExecutorInput.IOutputParameter };
/** Outputs artifacts. */
public artifacts: { [k: string]: ml_pipelines.IArtifactList };
/** Outputs outputFile. */
public outputFile: string;
/**
* Creates a new Outputs instance using the specified properties.
* @param [properties] Properties to set
* @returns Outputs instance
*/
public static create(properties?: ml_pipelines.ExecutorInput.IOutputs): ml_pipelines.ExecutorInput.Outputs;
/**
* Encodes the specified Outputs message. Does not implicitly {@link ml_pipelines.ExecutorInput.Outputs.verify|verify} messages.
* @param message Outputs message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.ExecutorInput.IOutputs, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Outputs message, length delimited. Does not implicitly {@link ml_pipelines.ExecutorInput.Outputs.verify|verify} messages.
* @param message Outputs message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.ExecutorInput.IOutputs, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Outputs message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Outputs
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ExecutorInput.Outputs;
/**
* Decodes an Outputs message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Outputs
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ExecutorInput.Outputs;
/**
* Verifies an Outputs message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Outputs message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Outputs
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ExecutorInput.Outputs;
/**
* Creates a plain object from an Outputs message. Also converts values to other types if specified.
* @param message Outputs
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ExecutorInput.Outputs, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Outputs to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Properties of an ExecutorOutput. */
interface IExecutorOutput {
/** ExecutorOutput parameters */
parameters?: ({ [k: string]: ml_pipelines.IValue }|null);
/** ExecutorOutput artifacts */
artifacts?: ({ [k: string]: ml_pipelines.IArtifactList }|null);
}
/** Represents an ExecutorOutput. */
class ExecutorOutput implements IExecutorOutput {
/**
* Constructs a new ExecutorOutput.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IExecutorOutput);
/** ExecutorOutput parameters. */
public parameters: { [k: string]: ml_pipelines.IValue };
/** ExecutorOutput artifacts. */
public artifacts: { [k: string]: ml_pipelines.IArtifactList };
/**
* Creates a new ExecutorOutput instance using the specified properties.
* @param [properties] Properties to set
* @returns ExecutorOutput instance
*/
public static create(properties?: ml_pipelines.IExecutorOutput): ml_pipelines.ExecutorOutput;
/**
* Encodes the specified ExecutorOutput message. Does not implicitly {@link ml_pipelines.ExecutorOutput.verify|verify} messages.
* @param message ExecutorOutput message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IExecutorOutput, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ExecutorOutput message, length delimited. Does not implicitly {@link ml_pipelines.ExecutorOutput.verify|verify} messages.
* @param message ExecutorOutput message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IExecutorOutput, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an ExecutorOutput message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ExecutorOutput
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.ExecutorOutput;
/**
* Decodes an ExecutorOutput message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ExecutorOutput
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.ExecutorOutput;
/**
* Verifies an ExecutorOutput message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an ExecutorOutput message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ExecutorOutput
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.ExecutorOutput;
/**
* Creates a plain object from an ExecutorOutput message. Also converts values to other types if specified.
* @param message ExecutorOutput
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.ExecutorOutput, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ExecutorOutput to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PipelineTaskFinalStatus. */
interface IPipelineTaskFinalStatus {
/** PipelineTaskFinalStatus state */
state?: (string|null);
/** PipelineTaskFinalStatus error */
error?: (google.rpc.IStatus|null);
}
/** Represents a PipelineTaskFinalStatus. */
class PipelineTaskFinalStatus implements IPipelineTaskFinalStatus {
/**
* Constructs a new PipelineTaskFinalStatus.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IPipelineTaskFinalStatus);
/** PipelineTaskFinalStatus state. */
public state: string;
/** PipelineTaskFinalStatus error. */
public error?: (google.rpc.IStatus|null);
/**
* Creates a new PipelineTaskFinalStatus instance using the specified properties.
* @param [properties] Properties to set
* @returns PipelineTaskFinalStatus instance
*/
public static create(properties?: ml_pipelines.IPipelineTaskFinalStatus): ml_pipelines.PipelineTaskFinalStatus;
/**
* Encodes the specified PipelineTaskFinalStatus message. Does not implicitly {@link ml_pipelines.PipelineTaskFinalStatus.verify|verify} messages.
* @param message PipelineTaskFinalStatus message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IPipelineTaskFinalStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PipelineTaskFinalStatus message, length delimited. Does not implicitly {@link ml_pipelines.PipelineTaskFinalStatus.verify|verify} messages.
* @param message PipelineTaskFinalStatus message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IPipelineTaskFinalStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PipelineTaskFinalStatus message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PipelineTaskFinalStatus
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineTaskFinalStatus;
/**
* Decodes a PipelineTaskFinalStatus message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PipelineTaskFinalStatus
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineTaskFinalStatus;
/**
* Verifies a PipelineTaskFinalStatus message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PipelineTaskFinalStatus message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PipelineTaskFinalStatus
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineTaskFinalStatus;
/**
* Creates a plain object from a PipelineTaskFinalStatus message. Also converts values to other types if specified.
* @param message PipelineTaskFinalStatus
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineTaskFinalStatus, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PipelineTaskFinalStatus to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a PipelineStateEnum. */
interface IPipelineStateEnum {
}
/** Represents a PipelineStateEnum. */
class PipelineStateEnum implements IPipelineStateEnum {
/**
* Constructs a new PipelineStateEnum.
* @param [properties] Properties to set
*/
constructor(properties?: ml_pipelines.IPipelineStateEnum);
/**
* Creates a new PipelineStateEnum instance using the specified properties.
* @param [properties] Properties to set
* @returns PipelineStateEnum instance
*/
public static create(properties?: ml_pipelines.IPipelineStateEnum): ml_pipelines.PipelineStateEnum;
/**
* Encodes the specified PipelineStateEnum message. Does not implicitly {@link ml_pipelines.PipelineStateEnum.verify|verify} messages.
* @param message PipelineStateEnum message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: ml_pipelines.IPipelineStateEnum, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified PipelineStateEnum message, length delimited. Does not implicitly {@link ml_pipelines.PipelineStateEnum.verify|verify} messages.
* @param message PipelineStateEnum message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: ml_pipelines.IPipelineStateEnum, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a PipelineStateEnum message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns PipelineStateEnum
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ml_pipelines.PipelineStateEnum;
/**
* Decodes a PipelineStateEnum message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns PipelineStateEnum
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ml_pipelines.PipelineStateEnum;
/**
* Verifies a PipelineStateEnum message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a PipelineStateEnum message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns PipelineStateEnum
*/
public static fromObject(object: { [k: string]: any }): ml_pipelines.PipelineStateEnum;
/**
* Creates a plain object from a PipelineStateEnum message. Also converts values to other types if specified.
* @param message PipelineStateEnum
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: ml_pipelines.PipelineStateEnum, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this PipelineStateEnum to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
namespace PipelineStateEnum {
/** PipelineTaskState enum. */
enum PipelineTaskState {
TASK_STATE_UNSPECIFIED = 0,
PENDING = 1,
RUNNING_DRIVER = 2,
DRIVER_SUCCEEDED = 3,
RUNNING_EXECUTOR = 4,
SUCCEEDED = 5,
CANCEL_PENDING = 6,
CANCELLING = 7,
CANCELLED = 8,
FAILED = 9,
SKIPPED = 10,
QUEUED = 11,
NOT_TRIGGERED = 12,
UNSCHEDULABLE = 13
}
}
}
/** Namespace google. */
export namespace google {
/** Namespace protobuf. */
namespace protobuf {
/** Properties of an Any. */
interface IAny {
/** Any type_url */
type_url?: (string|null);
/** Any value */
value?: (Uint8Array|null);
}
/** Represents an Any. */
class Any implements IAny {
/**
* Constructs a new Any.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IAny);
/** Any type_url. */
public type_url: string;
/** Any value. */
public value: Uint8Array;
/**
* Creates a new Any instance using the specified properties.
* @param [properties] Properties to set
* @returns Any instance
*/
public static create(properties?: google.protobuf.IAny): google.protobuf.Any;
/**
* Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages.
* @param message Any message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Any message, length delimited. Does not implicitly {@link google.protobuf.Any.verify|verify} messages.
* @param message Any message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IAny, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an Any message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Any
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Any;
/**
* Decodes an Any message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Any
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Any;
/**
* Verifies an Any message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an Any message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Any
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Any;
/**
* Creates a plain object from an Any message. Also converts values to other types if specified.
* @param message Any
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Any, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Any to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Struct. */
interface IStruct {
/** Struct fields */
fields?: ({ [k: string]: google.protobuf.IValue }|null);
}
/** Represents a Struct. */
class Struct implements IStruct {
/**
* Constructs a new Struct.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IStruct);
/** Struct fields. */
public fields: { [k: string]: google.protobuf.IValue };
/**
* Creates a new Struct instance using the specified properties.
* @param [properties] Properties to set
* @returns Struct instance
*/
public static create(properties?: google.protobuf.IStruct): google.protobuf.Struct;
/**
* Encodes the specified Struct message. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages.
* @param message Struct message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IStruct, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Struct message, length delimited. Does not implicitly {@link google.protobuf.Struct.verify|verify} messages.
* @param message Struct message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IStruct, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Struct message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Struct
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Struct;
/**
* Decodes a Struct message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Struct
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Struct;
/**
* Verifies a Struct message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Struct message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Struct
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Struct;
/**
* Creates a plain object from a Struct message. Also converts values to other types if specified.
* @param message Struct
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Struct, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Struct to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Value. */
interface IValue {
/** Value nullValue */
nullValue?: (google.protobuf.NullValue|null);
/** Value numberValue */
numberValue?: (number|null);
/** Value stringValue */
stringValue?: (string|null);
/** Value boolValue */
boolValue?: (boolean|null);
/** Value structValue */
structValue?: (google.protobuf.IStruct|null);
/** Value listValue */
listValue?: (google.protobuf.IListValue|null);
}
/** Represents a Value. */
class Value implements IValue {
/**
* Constructs a new Value.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IValue);
/** Value nullValue. */
public nullValue?: (google.protobuf.NullValue|null);
/** Value numberValue. */
public numberValue?: (number|null);
/** Value stringValue. */
public stringValue?: (string|null);
/** Value boolValue. */
public boolValue?: (boolean|null);
/** Value structValue. */
public structValue?: (google.protobuf.IStruct|null);
/** Value listValue. */
public listValue?: (google.protobuf.IListValue|null);
/** Value kind. */
public kind?: ("nullValue"|"numberValue"|"stringValue"|"boolValue"|"structValue"|"listValue");
/**
* Creates a new Value instance using the specified properties.
* @param [properties] Properties to set
* @returns Value instance
*/
public static create(properties?: google.protobuf.IValue): google.protobuf.Value;
/**
* Encodes the specified Value message. Does not implicitly {@link google.protobuf.Value.verify|verify} messages.
* @param message Value message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IValue, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Value message, length delimited. Does not implicitly {@link google.protobuf.Value.verify|verify} messages.
* @param message Value message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IValue, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Value message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Value
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.Value;
/**
* Decodes a Value message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Value
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.Value;
/**
* Verifies a Value message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Value message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Value
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.Value;
/**
* Creates a plain object from a Value message. Also converts values to other types if specified.
* @param message Value
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.Value, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Value to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** NullValue enum. */
enum NullValue {
NULL_VALUE = 0
}
/** Properties of a ListValue. */
interface IListValue {
/** ListValue values */
values?: (google.protobuf.IValue[]|null);
}
/** Represents a ListValue. */
class ListValue implements IListValue {
/**
* Constructs a new ListValue.
* @param [properties] Properties to set
*/
constructor(properties?: google.protobuf.IListValue);
/** ListValue values. */
public values: google.protobuf.IValue[];
/**
* Creates a new ListValue instance using the specified properties.
* @param [properties] Properties to set
* @returns ListValue instance
*/
public static create(properties?: google.protobuf.IListValue): google.protobuf.ListValue;
/**
* Encodes the specified ListValue message. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages.
* @param message ListValue message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.protobuf.IListValue, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ListValue message, length delimited. Does not implicitly {@link google.protobuf.ListValue.verify|verify} messages.
* @param message ListValue message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.protobuf.IListValue, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ListValue message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ListValue
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.protobuf.ListValue;
/**
* Decodes a ListValue message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ListValue
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.protobuf.ListValue;
/**
* Verifies a ListValue message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ListValue message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ListValue
*/
public static fromObject(object: { [k: string]: any }): google.protobuf.ListValue;
/**
* Creates a plain object from a ListValue message. Also converts values to other types if specified.
* @param message ListValue
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.protobuf.ListValue, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ListValue to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
/** Namespace rpc. */
namespace rpc {
/** Properties of a Status. */
interface IStatus {
/** Status code */
code?: (number|null);
/** Status message */
message?: (string|null);
/** Status details */
details?: (google.protobuf.IAny[]|null);
}
/** Represents a Status. */
class Status implements IStatus {
/**
* Constructs a new Status.
* @param [properties] Properties to set
*/
constructor(properties?: google.rpc.IStatus);
/** Status code. */
public code: number;
/** Status message. */
public message: string;
/** Status details. */
public details: google.protobuf.IAny[];
/**
* Creates a new Status instance using the specified properties.
* @param [properties] Properties to set
* @returns Status instance
*/
public static create(properties?: google.rpc.IStatus): google.rpc.Status;
/**
* Encodes the specified Status message. Does not implicitly {@link google.rpc.Status.verify|verify} messages.
* @param message Status message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Status message, length delimited. Does not implicitly {@link google.rpc.Status.verify|verify} messages.
* @param message Status message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: google.rpc.IStatus, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Status message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Status
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): google.rpc.Status;
/**
* Decodes a Status message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Status
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): google.rpc.Status;
/**
* Verifies a Status message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Status message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Status
*/
public static fromObject(object: { [k: string]: any }): google.rpc.Status;
/**
* Creates a plain object from a Status message. Also converts values to other types if specified.
* @param message Status
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: google.rpc.Status, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Status to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
}
} | the_stack |
interface IKeyValue {
[key: string]: any
}
interface IHeaderOpts {
[key: string]: string
}
export interface ICredentialsInfo {
private_key_id: string
private_key: string
env_id: string
}
export interface ICloudBaseConfig extends IKeyValue {
debug?: boolean
timeout?: number
isHttp?: boolean
secretId?: string
secretKey?: string
env?: string | Symbol
sessionToken?: string
serviceUrl?: string
headers?: IHeaderOpts
proxy?: string
version?: string
credentials?: ICredentialsInfo
throwOnCode?: boolean
forever?: boolean
/**
* 获取跨帐号调用信息
*/
getCrossAccountInfo?: () => Promise<ICrossAccountInfo>
}
interface IInnerCloudBaseConfig extends ICloudBaseConfig {
envName?: string | Symbol
}
interface IRequestInfo {
config: IInnerCloudBaseConfig
method: string
headers: IHeaderOpts
params: ICustomParam
customApiUrl?: string
isFormData?: boolean
opts?: IKeyValue
}
interface ICommonParam {
action: string
envName?: string | Symbol
timestamp?: number
eventId?: string
wxCloudApiToken?: string
tcb_sessionToken?: string
authorization?: string
sessionToken?: string
sdk_version?: string
}
interface ICustomParam extends ICommonParam {
[propName: string]: any
}
export interface IRetryOptions {
retries?: number
factor?: number
minTimeout?: number
maxTimeout?: number
randomize?: boolean
timeouts?: number[]
timeoutOps?: {
timeout: number
cb: Function
}
}
interface ICrossAccountInfo {
/**
* 帐号凭证
*/
credential: {
secretId: string
secretKey: string
token: string
}
/**
* 认证信息加密
*/
authorization: {
mpToken?: string
}
}
export interface ICustomReqOpts {
timeout?: number
retryOptions?: IRetryOptions
/**
* 获取跨帐号调用信息
*/
getCrossAccountInfo?: () => Promise<ICrossAccountInfo>
}
export interface IErrorInfo extends IBaseRes {
code?: string
message?: string
}
export interface ICallFunctionRes extends IBaseRes {
result?: any
}
export interface IUploadFileRes extends IBaseRes {
fileID: string
}
export interface IDeleteFileItem {
code: string
fileID: string
}
export interface IDeleteFileOpts {
fileList: string[]
}
export interface IBaseRes {
requestId?: string
}
export interface IDeleteFileRes extends IBaseRes {
fileList: Array<IDeleteFileItem>
}
export interface IGetFileUrlItem {
code: string
fileID: string
tempFileURL: string
}
export interface IGetFileUrlRes extends IBaseRes {
fileList: Array<IGetFileUrlItem>
}
export interface IDownloadFileRes {
fileContent: Buffer | undefined
message: string
}
export interface ICallWxOpenApiRes extends IBaseRes {
result?: any
}
interface IReqOpts {
proxy?: string
qs?: any
json?: boolean
body?: any
formData?: any
encoding?: string
forever?: boolean
url: string
method?: string
timeout?: number
headers?: IHeaderOpts
}
export interface ICountRes extends IBaseRes {
total?: number
}
interface IReqHooks {
handleData?: (res: any, err: any, response: any, body: any) => any
}
export interface IContextParam {
memory_limit_in_mb: number
time_limit_in_ms: number
request_id: string
environ?: string
environment?: string
function_version: string
function_name: string
namespace: string
}
export interface ISCFContext {
memoryLimitInMb: number
timeLimitIns: number
requestId: string
functionVersion: string
namespace: string
functionName: string
environ?: IEnvironmentInfo
environment?: IEnvironmentInfo
}
export interface IEnvironmentInfo {
WX_CLIENTIP?: string
WX_CLIENTIPV6?: string
WX_APPID?: string
WX_OPENID?: string
WX_API_TOKEN?: string
WX_CONTEXT_KEYS?: string[]
TCB_ENV: string
TCB_SEQID: string
TRIGGER_SRC: string
TCB_SESSIONTOKEN?: string
TCB_SOURCE?: string
TCB_CONTEXT_KEYS: string[]
TENCENTCLOUD_SECRETID: string
TENCENTCLOUD_SECRETKEY: string
TENCENTCLOUD_SESSIONTOKEN: string
SCF_NAMESPACE: string
}
export interface ICompleteCloudbaseContext {
TENCENTCLOUD_RUNENV: string
SCF_NAMESPACE: string
TCB_CONTEXT_KEYS: string[]
TENCENTCLOUD_SECRETID: string
TENCENTCLOUD_SECRETKEY: string
TENCENTCLOUD_SESSIONTOKEN: string
TRIGGER_SRC: string
WX_TRIGGER_API_TOKEN_V0?: string
WX_CLIENTIP?: string
WX_CLIENTIPV6?: string
WX_CONTEXT_KEYS: string[]
_SCF_TCB_LOG?: string
LOGINTYPE?: string
WX_APPID?: string
WX_OPENID?: string
WX_UNIONID?: string
WX_API_TOKEN?: string
TCB_ENV: string
TCB_SEQID: string
QQ_OPENID?: string
QQ_APPID?: string
TCB_UUID?: string
TCB_ISANONYMOUS_USER?: string
TCB_SESSIONTOKEN?: string
TCB_CUSTOM_USER_ID?: string
TCB_SOURCE_IP?: string
TCB_SOURCE?: string
TCB_ROUTE_KEY?: string
TCB_HTTP_CONTEXT?: string
TCB_CONTEXT_CNFG?: string
TCB_TRACELOG?: string
}
export declare namespace Database {
interface GeoType {
Point: typeof Point
LineString: typeof LineString
MultiLineString: typeof MultiLineString
MultiPoint: typeof MultiPoint
MultiPolygon: typeof MultiPolygon
Polygon: typeof Polygon
}
class HiddenSymbol {
constructor(target: any)
}
class InternalSymbol extends HiddenSymbol {
constructor(target: any, __mark__: any)
static for(target: any): InternalSymbol
}
type OrderByDirection = 'desc' | 'asc'
enum QueryType {
WHERE = 'WHERE',
DOC = 'DOC'
}
interface ISerializedPoint {
type: string
coordinates: [number, number]
}
interface ISerializedLineString {
type: string
coordinates: [number, number][]
}
interface ISerializedPolygon {
type: string
coordinates: [number, number][][]
}
interface ISerializedMultiPoint {
type: string
coordinates: [number, number][]
}
interface ISerializedMultiLineString {
type: string
coordinates: [number, number][][]
}
interface ISerializedMultiPolygon {
type: string
coordinates: [number, number][][][]
}
export class Point {
readonly latitude: number
readonly longitude: number
constructor(longitude: number, latitude: number)
parse(
key: any
): {
[x: number]: {
type: string
coordinates: number[]
}
}
toJSON(): {
type: string
coordinates: number[]
}
toReadableString(): string
static validate(point: ISerializedPoint): boolean
readonly _internalType: InternalSymbol
}
export class LineString {
readonly points: Point[]
constructor(points: Point[])
parse(
key: any
): {
[x: number]: {
type: string
coordinates: number[][]
}
}
toJSON(): {
type: string
coordinates: number[][]
}
static validate(lineString: ISerializedLineString): boolean
static isClosed(lineString: LineString): boolean
readonly _internalType: InternalSymbol
}
export class MultiLineString {
readonly lines: LineString[]
constructor(lines: LineString[])
parse(
key: any
): {
[x: number]: {
type: string
coordinates: number[][][]
}
}
toJSON(): {
type: string
coordinates: number[][][]
}
static validate(multiLineString: ISerializedMultiLineString): boolean
readonly _internalType: InternalSymbol
}
export class MultiPoint {
readonly points: Point[]
constructor(points: Point[])
parse(
key: any
): {
[x: number]: {
type: string
coordinates: number[][]
}
}
toJSON(): {
type: string
coordinates: number[][]
}
static validate(multiPoint: ISerializedMultiPoint): boolean
readonly _internalType: InternalSymbol
}
export class MultiPolygon {
public readonly polygons: Polygon[]
public constructor(polygons: Polygon[])
parse(
key: any
): {
[x: number]: {
type: string
coordinates: number[][][][]
}
}
toJSON(): {
type: string
coordinates: number[][][][]
}
static validate(multiPolygon: ISerializedMultiPolygon): boolean
readonly _internalType: InternalSymbol
}
export class Polygon {
readonly lines: LineString[]
constructor(lines: LineString[])
parse(
key: any
): {
[x: number]: {
type: string
coordinates: number[][][]
}
}
toJSON(): {
type: string
coordinates: number[][][]
}
static validate(polygon: ISerializedPolygon): boolean
static isCloseLineString(lineString: any): boolean
readonly _internalType: InternalSymbol
}
export class RegExp {
$regularExpression?: {
pattern?: string
options?: string
}
constructor({ regexp, options }: { regexp: string; options: string })
parse(): {
$regularExpression: {
pattern: string
options: string
}
}
readonly _internalType: InternalSymbol
}
export class ServerDate {
readonly offset: number
constructor({ offset }?: { offset?: number })
readonly _internalType: InternalSymbol
parse(): {
$tcb_server_date: {
offset: number
}
}
}
/**
* 数据库模块的通用请求方法
*
* @author haroldhu
* @internal
*/
class DBRequest {
private config
/**
* 初始化
*
* @internal
* @param config
*/
constructor(config: IInnerCloudBaseConfig)
/**
* 发送请求
*
* @param dbParams - 数据库请求参数
* @param opts - 可选配置项
*/
send(api: string, data: any, opts?: ICustomReqOpts): Promise<any>
}
export class Db {
Geo: GeoType
command: typeof Command
RegExp: (param: { regexp: string; options: string }) => RegExp
serverDate: (opt: { offset: number }) => ServerDate
startTransaction: () => Promise<Transaction>
runTransaction: (
callback: (transaction: Transaction) => void | Promise<any>,
times?: number
) => Promise<any>
config: IInnerCloudBaseConfig
static reqClass: DBRequest
static dataVersion: string
constructor(config?: IInnerCloudBaseConfig)
collection(collName: string): CollectionReference
createCollection(collName: string): IBaseRes
}
export class DocumentReference {
readonly id: string | number
readonly _transactionId: string
readonly projection: Object
private _apiOptions
set(data: Object): Promise<IUpdateResult>
update(data: Object): Promise<IUpdateResult>
delete(): Promise<IDeleteResult>
remove(): Promise<IDeleteResult>
get(): Promise<IGetRes>
field(projection: Object): DocumentReference
}
interface IStageItem {
stageKey: string
stageValue: string
}
export class Aggregation {
_db: Db
_request: DBRequest
_stages: IStageItem[]
_collectionName: string
constructor(db?: Db, collectionName?: string)
end(): Promise<any>
unwrap(): any[]
done(): {
[x: number]: any
}[]
_pipe(stage: string, param: any): this
addFields(param: any): this
bucket(param: any): this
bucketAuto(param: any): this
count(param: any): this
geoNear(param: any): this
group(param: any): this
limit(param: any): this
match(param: any): this
project(param: any): this
lookup(param: any): this
replaceRoot(param: any): this
sample(param: any): this
skip(param: any): this
sort(param: any): this
sortByCount(param: any): this
unwind(param: any): this
}
export class CollectionReference extends Query {
protected _transactionId: string
readonly name: string
doc(docID: string | number): DocumentReference
add(data: IKeyValue): Promise<IAddRes>
aggregate(): Aggregation
options(apiOptions: QueryOption | UpdateOption): CollectionReference
}
export interface IReqOpts {
timeout: number
}
export type CenterSphere = [Point, number] | [[number, number], number]
export interface IAddRes extends IBaseRes {
ids?: string[] // 批量插入返回
id?: string
inserted?: number
ok?: number
}
export interface IGetRes extends IBaseRes {
data: any[]
total: number
limit: number
offset: number
}
export interface BaseOption {
timeout?: number
}
export interface QueryOption extends BaseOption {
limit?: number
offset?: number
projection?: Object
order?: Record<string, any>[]
}
export interface UpdateOption extends BaseOption {
multiple?: boolean
}
export class Query {
protected _transactionId: string
get(): Promise<IGetRes>
count(): Promise<ICountRes>
where(query: object): Query
options(apiOptions: QueryOption | UpdateOption): Query
orderBy(fieldPath: string, directionStr: OrderByDirection): Query
limit(limit: number): Query
skip(offset: number): Query
update(data: Object): Promise<IUpdateResult>
field(projection: any): Query
remove(): Promise<IDeleteResult>
updateAndReturn(data: Object): Promise<IUpdateAndReturnResult>
}
export enum QUERY_COMMANDS_LITERAL {
EQ = 'eq',
NEQ = 'neq',
GT = 'gt',
GTE = 'gte',
LT = 'lt',
LTE = 'lte',
IN = 'in',
NIN = 'nin',
ALL = 'all',
ELEM_MATCH = 'elemMatch',
EXISTS = 'exists',
SIZE = 'size',
MOD = 'mod',
GEO_NEAR = 'geoNear',
GEO_WITHIN = 'geoWithin',
GEO_INTERSECTS = 'geoIntersects'
}
export enum LOGIC_COMMANDS_LITERAL {
AND = 'and',
OR = 'or',
NOT = 'not',
NOR = 'nor'
}
export class LogicCommand {
fieldName: string | InternalSymbol
operator: LOGIC_COMMANDS_LITERAL | string
operands: any[]
_internalType: InternalSymbol
constructor(
operator: LOGIC_COMMANDS_LITERAL | string,
operands: any,
fieldName?: string | InternalSymbol
)
_setFieldName(fieldName: string): LogicCommand
and(...__expressions__: LogicCommand[]): LogicCommand
or(...__expressions__: LogicCommand[]): LogicCommand
}
export class QueryCommand extends LogicCommand {
operator: QUERY_COMMANDS_LITERAL
constructor(
operator: QUERY_COMMANDS_LITERAL,
operands: any,
fieldName?: string | InternalSymbol
)
toJSON():
| {
['$ne']: any
}
| {
[x: string]: any
$ne?: undefined
}
_setFieldName(fieldName: string): QueryCommand
eq(val: any): LogicCommand
neq(val: any): LogicCommand
gt(val: any): LogicCommand
gte(val: any): LogicCommand
lt(val: any): LogicCommand
lte(val: any): LogicCommand
in(list: any[]): LogicCommand
nin(list: any[]): LogicCommand
geoNear(val: IGeoNearOptions): LogicCommand
geoWithin(val: IGeoWithinOptions): LogicCommand
geoIntersects(val: IGeoIntersectsOptions): LogicCommand
}
export enum UPDATE_COMMANDS_LITERAL {
SET = 'set',
REMOVE = 'remove',
INC = 'inc',
MUL = 'mul',
PUSH = 'push',
PULL = 'pull',
PULL_ALL = 'pullAll',
POP = 'pop',
SHIFT = 'shift',
UNSHIFT = 'unshift',
ADD_TO_SET = 'addToSet',
BIT = 'bit',
RENAME = 'rename',
MAX = 'max',
MIN = 'min'
}
export class UpdateCommand {
fieldName: string | InternalSymbol
operator: UPDATE_COMMANDS_LITERAL
operands: any
_internalType: InternalSymbol
constructor(
operator: UPDATE_COMMANDS_LITERAL,
operands?: any,
fieldName?: string | InternalSymbol
)
_setFieldName(fieldName: string): UpdateCommand
}
export interface IGeoNearOptions {
geometry: Point
maxDistance?: number
minDistance?: number
}
export interface IGeoWithinOptions {
geometry?: Polygon | MultiPolygon
centerSphere?: CenterSphere
}
export interface IGeoIntersectsOptions {
geometry: Point | LineString | Polygon | MultiPoint | MultiLineString | MultiPolygon
}
interface TransactionAPI {
send(interfaceName: string, param?: any): any
}
export class Transaction {
private _id: string
private _db: Db
private _request
aborted: boolean
abortReason: any
commited: boolean
inited: boolean
constructor(db: Db)
init(): Promise<void>
collection(collName: string): CollectionReference
getTransactionId(): string
getRequestMethod(): TransactionAPI
commit(): Promise<CommitResult>
rollback(customRollbackRes: any): Promise<RollbackResult>
}
export interface CommitResult {
requestId: string
}
export interface RollbackResult {
requestId: string
}
export interface IUpdateResult extends IBaseRes {
updated?: number
upserted?: JsonString
}
export interface IUpdateAndReturnResult extends IBaseRes {
updated?: number
doc?: any
}
export interface ISetResult extends IUpdateResult {
upserted: JsonString
}
export interface IDeleteResult extends IBaseRes {
deleted: number | string
}
type JsonString = string
export type IQueryCondition = Record<string, any> | LogicCommand
export const Command: {
eq(val: any): QueryCommand
neq(val: any): QueryCommand
lt(val: any): QueryCommand
lte(val: any): QueryCommand
gt(val: any): QueryCommand
gte(val: any): QueryCommand
in(val: any): QueryCommand
nin(val: any): QueryCommand
all(val: any): QueryCommand
elemMatch(val: any): QueryCommand
exists(val: boolean): QueryCommand
size(val: number): QueryCommand
mod(val: number[]): QueryCommand
geoNear(val: any): QueryCommand
geoWithin(val: any): QueryCommand
geoIntersects(val: any): QueryCommand
and(...__expressions__: IQueryCondition[]): LogicCommand
nor(...__expressions__: IQueryCondition[]): LogicCommand
or(...__expressions__: IQueryCondition[]): LogicCommand
not(...__expressions__: IQueryCondition[]): LogicCommand
set(val: any): UpdateCommand
remove(): UpdateCommand
inc(val: number): UpdateCommand
mul(val: number): UpdateCommand
push(...args: any[]): UpdateCommand
pull(values: any): UpdateCommand
pullAll(values: any): UpdateCommand
pop(): UpdateCommand
shift(): UpdateCommand
unshift(...__values__: any[]): UpdateCommand
addToSet(values: any): UpdateCommand
rename(values: any): UpdateCommand
bit(values: any): UpdateCommand
max(values: any): UpdateCommand
min(values: any): UpdateCommand
expr(
values: AggregationOperator
): {
$expr: AggregationOperator
}
jsonSchema(
schema: any
): {
$jsonSchema: any
}
text(
values:
| string
| {
search: string
language?: string
caseSensitive?: boolean
diacriticSensitive: boolean
}
):
| {
$search: {
(regexp: string | RegExp): number
(searcher: { [Symbol.search](string: string): number }): number
}
$language?: undefined
$caseSensitive?: undefined
$diacriticSensitive?: undefined
}
| {
$search: string
$language: string
$caseSensitive: boolean
$diacriticSensitive: boolean
}
aggregate: {
pipeline(): Aggregation
abs: (param: any) => AggregationOperator
add: (param: any) => AggregationOperator
ceil: (param: any) => AggregationOperator
divide: (param: any) => AggregationOperator
exp: (param: any) => AggregationOperator
floor: (param: any) => AggregationOperator
ln: (param: any) => AggregationOperator
log: (param: any) => AggregationOperator
log10: (param: any) => AggregationOperator
mod: (param: any) => AggregationOperator
multiply: (param: any) => AggregationOperator
pow: (param: any) => AggregationOperator
sqrt: (param: any) => AggregationOperator
subtract: (param: any) => AggregationOperator
trunc: (param: any) => AggregationOperator
arrayElemAt: (param: any) => AggregationOperator
arrayToObject: (param: any) => AggregationOperator
concatArrays: (param: any) => AggregationOperator
filter: (param: any) => AggregationOperator
in: (param: any) => AggregationOperator
indexOfArray: (param: any) => AggregationOperator
isArray: (param: any) => AggregationOperator
map: (param: any) => AggregationOperator
range: (param: any) => AggregationOperator
reduce: (param: any) => AggregationOperator
reverseArray: (param: any) => AggregationOperator
size: (param: any) => AggregationOperator
slice: (param: any) => AggregationOperator
zip: (param: any) => AggregationOperator
and: (param: any) => AggregationOperator
not: (param: any) => AggregationOperator
or: (param: any) => AggregationOperator
cmp: (param: any) => AggregationOperator
eq: (param: any) => AggregationOperator
gt: (param: any) => AggregationOperator
gte: (param: any) => AggregationOperator
lt: (param: any) => AggregationOperator
lte: (param: any) => AggregationOperator
neq: (param: any) => AggregationOperator
cond: (param: any) => AggregationOperator
ifNull: (param: any) => AggregationOperator
switch: (param: any) => AggregationOperator
dateFromParts: (param: any) => AggregationOperator
dateFromString: (param: any) => AggregationOperator
dayOfMonth: (param: any) => AggregationOperator
dayOfWeek: (param: any) => AggregationOperator
dayOfYear: (param: any) => AggregationOperator
isoDayOfWeek: (param: any) => AggregationOperator
isoWeek: (param: any) => AggregationOperator
isoWeekYear: (param: any) => AggregationOperator
millisecond: (param: any) => AggregationOperator
minute: (param: any) => AggregationOperator
month: (param: any) => AggregationOperator
second: (param: any) => AggregationOperator
hour: (param: any) => AggregationOperator
week: (param: any) => AggregationOperator
year: (param: any) => AggregationOperator
literal: (param: any) => AggregationOperator
mergeObjects: (param: any) => AggregationOperator
objectToArray: (param: any) => AggregationOperator
allElementsTrue: (param: any) => AggregationOperator
anyElementTrue: (param: any) => AggregationOperator
setDifference: (param: any) => AggregationOperator
setEquals: (param: any) => AggregationOperator
setIntersection: (param: any) => AggregationOperator
setIsSubset: (param: any) => AggregationOperator
setUnion: (param: any) => AggregationOperator
concat: (param: any) => AggregationOperator
dateToString: (param: any) => AggregationOperator
indexOfBytes: (param: any) => AggregationOperator
indexOfCP: (param: any) => AggregationOperator
split: (param: any) => AggregationOperator
strLenBytes: (param: any) => AggregationOperator
strLenCP: (param: any) => AggregationOperator
strcasecmp: (param: any) => AggregationOperator
substr: (param: any) => AggregationOperator
substrBytes: (param: any) => AggregationOperator
substrCP: (param: any) => AggregationOperator
toLower: (param: any) => AggregationOperator
toUpper: (param: any) => AggregationOperator
meta: (param: any) => AggregationOperator
addToSet: (param: any) => AggregationOperator
avg: (param: any) => AggregationOperator
first: (param: any) => AggregationOperator
last: (param: any) => AggregationOperator
max: (param: any) => AggregationOperator
min: (param: any) => AggregationOperator
push: (param: any) => AggregationOperator
stdDevPop: (param: any) => AggregationOperator
stdDevSamp: (param: any) => AggregationOperator
sum: (param: any) => AggregationOperator
let: (param: any) => AggregationOperator
}
project: {
slice: (param: any) => ProjectionOperator
elemMatch: (param: any) => ProjectionOperator
}
}
export class AggregationOperator {
constructor(name: string, param: any)
}
export class ProjectionOperator {
constructor(name: string, param: any)
}
}
/**
*
*
* @class Log
*/
declare class Log {
isSupportClsReport: boolean
private src
constructor()
/**
*
*
* @param {*} logMsg
* @param {*} logLevel
* @returns
* @memberof Log
*/
transformMsg(logMsg: any): {}
/**
*
*
* @param {*} logMsg
* @param {*} logLevel
* @memberof Log
*/
baseLog(logMsg: any, logLevel: string): void
/**
*
*
* @param {*} logMsg
* @memberof Log
*/
log(logMsg: any): void
/**
*
*
* @param {*} logMsg
* @memberof Log
*/
info(logMsg: any): void
/**
*
*
* @param {*} logMsg
* @memberof Log
*/
error(logMsg: any): void
/**
*
*
* @param {*} logMsg
* @memberof Log
*/
warn(logMsg: any): void
}
declare function parseXML(str: any): Promise<unknown>
export interface IGetFileAuthorityFileItem {
type: string
path: string
}
export interface IGetFileAuthorityFileRes {
data: IGetFileAuthorityFileDataItem[]
}
export interface IGetFileAuthorityFileDataItem {
path: string
cosFileId: string
read: boolean
}
export interface ICreateTicketOpts {
refresh?: number
expire?: number
}
export interface IGetTempFileURLItem {
fileID: string
maxAge?: number
}
export interface IGetUploadMetadataRes extends IBaseRes {
data: IGetUploadMetadataItem
}
export interface IGetUploadMetadataItem {
url: string
token: string
authorization: string
fileId: string
cosFileId: string
download_url: string
}
export interface IGetAuthContextRes {
uid: string
loginType: string
appId?: string
openId?: string
}
export declare class CloudBase {
static scfContext: ISCFContext
static parseContext(context: IContextParam): ISCFContext
/**
* 获取当前函数内的所有环境变量(作为获取变量的统一方法,取值来源process.env 和 context)
*/
static getCloudbaseContext(context?: IContextParam): ICompleteCloudbaseContext
config: IInnerCloudBaseConfig
private clsLogger: Log
private extensionMap
constructor(config?: ICloudBaseConfig)
init(config?: ICloudBaseConfig): void
registerExtension(ext: any): void
invokeExtension(name: any, opts: any): Promise<any>
database(dbConfig?: any): Database.Db
/**
* 调用云函数
*
* @param param0
* @param opts
*/
callFunction(
{
name,
data
}: {
name: string
data: any
},
opts?: ICustomReqOpts
): Promise<ICallFunctionRes>
auth(): {
getUserInfo(): {
openId: string
appId: string
uid: string
customUserId: string
isAnonymous: boolean
}
getEndUserInfo(
uid?: string,
opts?: ICustomReqOpts
):
| Promise<any>
| {
userInfo: {
openId: string
appId: string
uid: string
customUserId: string
isAnonymous: boolean
}
}
getAuthContext(context: IContextParam): Promise<IGetAuthContextRes>
getClientIP(): string
createTicket: (uid: string, options?: ICreateTicketOpts) => string
}
/**
* openapi调用
*
* @param param0
* @param opts
*/
callWxOpenApi(
{
apiName,
requestData
}: {
apiName: string
apiOptions?: any
cgiName?: string
requestData: any
},
opts?: ICustomReqOpts
): Promise<ICallWxOpenApiRes>
/**
* wxpayapi调用
*
* @param param0
* @param opts
*/
callWxPayApi(
{
apiName,
requestData
}: {
apiName: string
apiOptions?: any
cgiName?: string
requestData: any
},
opts?: ICustomReqOpts
): Promise<any>
/**
* 微信云调用
*
* @param param0
* @param opts
*/
callCompatibleWxOpenApi(
{
apiName,
requestData
}: {
apiName: string
apiOptions?: any
cgiName?: string
requestData: any
},
opts?: ICustomReqOpts
): Promise<any>
/**
* 上传文件
*
* @param param0
* @param opts
*/
uploadFile(
{
cloudPath,
fileContent
}: {
cloudPath: string
fileContent: any
},
opts?: ICustomReqOpts
): Promise<IUploadFileRes>
/**
* 删除文件
*
* @param param0
* @param opts
*/
deleteFile(
{
fileList
}: {
fileList: string[]
},
opts?: ICustomReqOpts
): Promise<IDeleteFileRes>
/**
* 获取临时连接
*
* @param param0
* @param opts
*/
getTempFileURL(
{
fileList
}: {
fileList: (string | IGetTempFileURLItem)[]
},
opts?: ICustomReqOpts
): Promise<IGetFileUrlRes>
/**
* 下载文件
*
* @param params
* @param opts
*/
downloadFile(
params: {
fileID: string
tempFilePath?: string
},
opts?: ICustomReqOpts
): Promise<IDownloadFileRes>
/**
* 获取上传元数据
*
* @param param0
* @param opts
*/
getUploadMetadata(
{
cloudPath
}: {
cloudPath: string
},
opts?: ICustomReqOpts
): Promise<IGetUploadMetadataRes>
getFileAuthority({
fileList
}: {
fileList: IGetFileAuthorityFileItem[]
}): Promise<IGetFileAuthorityFileRes>
/**
* 获取logger
*/
logger(): Log
}
export const init: (config?: ICloudBaseConfig) => CloudBase
export const parseContext: (context: IContextParam) => ISCFContext
export const version: string
export const getCloudbaseContext: (context?: IContextParam) => ICompleteCloudbaseContext
/**
* 云函数下获取当前env
*/
export const SYMBOL_CURRENT_ENV: symbol | the_stack |
// FIXME
/* eslint-disable import/no-cycle */
import objectEntries from '../polyfills/objectEntries.js';
import { SYMBOL_TO_STRING_TAG } from '../polyfills/symbols.js';
import inspect from '../jsutils/inspect.js';
import keyMap from '../jsutils/keyMap.js';
import mapValue from '../jsutils/mapValue.js';
import toObjMap from '../jsutils/toObjMap.js';
import devAssert from '../jsutils/devAssert.js';
import keyValMap from '../jsutils/keyValMap.js';
import instanceOf from '../jsutils/instanceOf.js';
import didYouMean from '../jsutils/didYouMean.js';
import isObjectLike from '../jsutils/isObjectLike.js';
import identityFunc from '../jsutils/identityFunc.js';
import defineToJSON from '../jsutils/defineToJSON.js';
import suggestionList from '../jsutils/suggestionList.js';
import { Kind } from '../language/kinds.js';
import { print } from '../language/printer.js';
import { GraphQLError } from '../error/GraphQLError.js';
import { valueFromASTUntyped } from '../utilities/valueFromASTUntyped.js';
export function isType(type) {
return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type) || isListType(type) || isNonNullType(type);
}
export function assertType(type) {
if (!isType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL type.`);
}
return type;
}
/**
* There are predicates for each kind of GraphQL type.
*/
// eslint-disable-next-line no-redeclare
export function isScalarType(type) {
return instanceOf(type, GraphQLScalarType);
}
export function assertScalarType(type) {
if (!isScalarType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Scalar type.`);
}
return type;
}
// eslint-disable-next-line no-redeclare
export function isObjectType(type) {
return instanceOf(type, GraphQLObjectType);
}
export function assertObjectType(type) {
if (!isObjectType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Object type.`);
}
return type;
}
// eslint-disable-next-line no-redeclare
export function isInterfaceType(type) {
return instanceOf(type, GraphQLInterfaceType);
}
export function assertInterfaceType(type) {
if (!isInterfaceType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Interface type.`);
}
return type;
}
// eslint-disable-next-line no-redeclare
export function isUnionType(type) {
return instanceOf(type, GraphQLUnionType);
}
export function assertUnionType(type) {
if (!isUnionType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Union type.`);
}
return type;
}
// eslint-disable-next-line no-redeclare
export function isEnumType(type) {
return instanceOf(type, GraphQLEnumType);
}
export function assertEnumType(type) {
if (!isEnumType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Enum type.`);
}
return type;
}
// eslint-disable-next-line no-redeclare
export function isInputObjectType(type) {
return instanceOf(type, GraphQLInputObjectType);
}
export function assertInputObjectType(type) {
if (!isInputObjectType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Input Object type.`);
}
return type;
}
// eslint-disable-next-line no-redeclare
export function isListType(type) {
return instanceOf(type, GraphQLList);
}
export function assertListType(type) {
if (!isListType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL List type.`);
}
return type;
}
// eslint-disable-next-line no-redeclare
export function isNonNullType(type) {
return instanceOf(type, GraphQLNonNull);
}
export function assertNonNullType(type) {
if (!isNonNullType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL Non-Null type.`);
}
return type;
}
/**
* These types may be used as input types for arguments and directives.
*/
export function isInputType(type) {
return isScalarType(type) || isEnumType(type) || isInputObjectType(type) || isWrappingType(type) && isInputType(type.ofType);
}
export function assertInputType(type) {
if (!isInputType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL input type.`);
}
return type;
}
/**
* These types may be used as output types as the result of fields.
*/
export function isOutputType(type) {
return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isWrappingType(type) && isOutputType(type.ofType);
}
export function assertOutputType(type) {
if (!isOutputType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL output type.`);
}
return type;
}
/**
* These types may describe types which may be leaf values.
*/
export function isLeafType(type) {
return isScalarType(type) || isEnumType(type);
}
export function assertLeafType(type) {
if (!isLeafType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL leaf type.`);
}
return type;
}
/**
* These types may describe the parent context of a selection set.
*/
export function isCompositeType(type) {
return isObjectType(type) || isInterfaceType(type) || isUnionType(type);
}
export function assertCompositeType(type) {
if (!isCompositeType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL composite type.`);
}
return type;
}
/**
* These types may describe the parent context of a selection set.
*/
export function isAbstractType(type) {
return isInterfaceType(type) || isUnionType(type);
}
export function assertAbstractType(type) {
if (!isAbstractType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL abstract type.`);
}
return type;
}
/**
* List Type Wrapper
*
* A list is a wrapping type which points to another type.
* Lists are often created within the context of defining the fields of
* an object type.
*
* Example:
*
* const PersonType = new GraphQLObjectType({
* name: 'Person',
* fields: () => ({
* parents: { type: GraphQLList(PersonType) },
* children: { type: GraphQLList(PersonType) },
* })
* })
*
*/
// FIXME: workaround to fix issue with Babel parser
/* ::
declare class GraphQLList<+T: GraphQLType> {
+ofType: T;
static <T>(ofType: T): GraphQLList<T>;
// Note: constructors cannot be used for covariant types. Drop the "new".
constructor(ofType: GraphQLType): void;
}
*/
export function GraphQLList(ofType) {
if (this instanceof GraphQLList) {
this.ofType = assertType(ofType);
} else {
return new GraphQLList(ofType);
}
} // Need to cast through any to alter the prototype.
GraphQLList.prototype.toString = function toString() {
return '[' + String(this.ofType) + ']';
};
Object.defineProperty(GraphQLList.prototype, SYMBOL_TO_STRING_TAG, {
get() {
return 'GraphQLList';
}
});
defineToJSON(GraphQLList);
/**
* Non-Null Type Wrapper
*
* A non-null is a wrapping type which points to another type.
* Non-null types enforce that their values are never null and can ensure
* an error is raised if this ever occurs during a request. It is useful for
* fields which you can make a strong guarantee on non-nullability, for example
* usually the id field of a database row will never be null.
*
* Example:
*
* const RowType = new GraphQLObjectType({
* name: 'Row',
* fields: () => ({
* id: { type: GraphQLNonNull(GraphQLString) },
* })
* })
*
* Note: the enforcement of non-nullability occurs within the executor.
*/
// FIXME: workaround to fix issue with Babel parser
/* ::
declare class GraphQLNonNull<+T: GraphQLNullableType> {
+ofType: T;
static <T>(ofType: T): GraphQLNonNull<T>;
// Note: constructors cannot be used for covariant types. Drop the "new".
constructor(ofType: GraphQLType): void;
}
*/
export function GraphQLNonNull(ofType) {
if (this instanceof GraphQLNonNull) {
this.ofType = assertNullableType(ofType);
} else {
return new GraphQLNonNull(ofType);
}
} // Need to cast through any to alter the prototype.
GraphQLNonNull.prototype.toString = function toString() {
return String(this.ofType) + '!';
};
Object.defineProperty(GraphQLNonNull.prototype, SYMBOL_TO_STRING_TAG, {
get() {
return 'GraphQLNonNull';
}
});
defineToJSON(GraphQLNonNull);
/**
* These types wrap and modify other types
*/
export function isWrappingType(type) {
return isListType(type) || isNonNullType(type);
}
export function assertWrappingType(type) {
if (!isWrappingType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL wrapping type.`);
}
return type;
}
/**
* These types can all accept null as a value.
*/
export function isNullableType(type) {
return isType(type) && !isNonNullType(type);
}
export function assertNullableType(type) {
if (!isNullableType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL nullable type.`);
}
return type;
}
/* eslint-disable no-redeclare */
export function getNullableType(type) {
/* eslint-enable no-redeclare */
if (type) {
return isNonNullType(type) ? type.ofType : type;
}
}
/**
* These named types do not include modifiers like List or NonNull.
*/
export function isNamedType(type) {
return isScalarType(type) || isObjectType(type) || isInterfaceType(type) || isUnionType(type) || isEnumType(type) || isInputObjectType(type);
}
export function assertNamedType(type) {
if (!isNamedType(type)) {
throw new Error(`Expected ${inspect(type)} to be a GraphQL named type.`);
}
return type;
}
/* eslint-disable no-redeclare */
export function getNamedType(type) {
/* eslint-enable no-redeclare */
if (type) {
let unwrappedType = type;
while (isWrappingType(unwrappedType)) {
unwrappedType = unwrappedType.ofType;
}
return unwrappedType;
}
}
/**
* Used while defining GraphQL types to allow for circular references in
* otherwise immutable type definitions.
*/
function resolveThunk(thunk) {
// $FlowFixMe(>=0.90.0)
return typeof thunk === 'function' ? thunk() : thunk;
}
function undefineIfEmpty(arr) {
return arr && arr.length > 0 ? arr : undefined;
}
/**
* Scalar Type Definition
*
* The leaf values of any request and input values to arguments are
* Scalars (or Enums) and are defined with a name and a series of functions
* used to parse input from ast or variables and to ensure validity.
*
* If a type's serialize function does not return a value (i.e. it returns
* `undefined`) then an error will be raised and a `null` value will be returned
* in the response. If the serialize function returns `null`, then no error will
* be included in the response.
*
* Example:
*
* const OddType = new GraphQLScalarType({
* name: 'Odd',
* serialize(value) {
* if (value % 2 === 1) {
* return value;
* }
* }
* });
*
*/
export class GraphQLScalarType {
constructor(config) {
const parseValue = config.parseValue ?? identityFunc;
this.name = config.name;
this.description = config.description;
this.serialize = config.serialize ?? identityFunc;
this.parseValue = parseValue;
this.parseLiteral = config.parseLiteral ?? (node => parseValue(valueFromASTUntyped(node)));
this.extensions = config.extensions && toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
devAssert(typeof config.name === 'string', 'Must provide name.');
devAssert(config.serialize == null || typeof config.serialize === 'function', `${this.name} must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.`);
if (config.parseLiteral) {
devAssert(typeof config.parseValue === 'function' && typeof config.parseLiteral === 'function', `${this.name} must provide both "parseValue" and "parseLiteral" functions.`);
}
}
toConfig() {
return {
name: this.name,
description: this.description,
serialize: this.serialize,
parseValue: this.parseValue,
parseLiteral: this.parseLiteral,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes ?? []
};
}
toString() {
return this.name;
} // $FlowFixMe Flow doesn't support computed properties yet
get [SYMBOL_TO_STRING_TAG]() {
return 'GraphQLScalarType';
}
}
defineToJSON(GraphQLScalarType);
/**
* Object Type Definition
*
* Almost all of the GraphQL types you define will be object types. Object types
* have a name, but most importantly describe their fields.
*
* Example:
*
* const AddressType = new GraphQLObjectType({
* name: 'Address',
* fields: {
* street: { type: GraphQLString },
* number: { type: GraphQLInt },
* formatted: {
* type: GraphQLString,
* resolve(obj) {
* return obj.number + ' ' + obj.street
* }
* }
* }
* });
*
* When two types need to refer to each other, or a type needs to refer to
* itself in a field, you can use a function expression (aka a closure or a
* thunk) to supply the fields lazily.
*
* Example:
*
* const PersonType = new GraphQLObjectType({
* name: 'Person',
* fields: () => ({
* name: { type: GraphQLString },
* bestFriend: { type: PersonType },
* })
* });
*
*/
export class GraphQLObjectType {
constructor(config) {
this.name = config.name;
this.description = config.description;
this.isTypeOf = config.isTypeOf;
this.extensions = config.extensions && toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
this._fields = defineFieldMap.bind(undefined, config);
this._interfaces = defineInterfaces.bind(undefined, config);
devAssert(typeof config.name === 'string', 'Must provide name.');
devAssert(config.isTypeOf == null || typeof config.isTypeOf === 'function', `${this.name} must provide "isTypeOf" as a function, ` + `but got: ${inspect(config.isTypeOf)}.`);
}
getFields() {
if (typeof this._fields === 'function') {
this._fields = this._fields();
}
return this._fields;
}
getInterfaces() {
if (typeof this._interfaces === 'function') {
this._interfaces = this._interfaces();
}
return this._interfaces;
}
toConfig() {
return {
name: this.name,
description: this.description,
interfaces: this.getInterfaces(),
fields: fieldsToFieldsConfig(this.getFields()),
isTypeOf: this.isTypeOf,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes || []
};
}
toString() {
return this.name;
} // $FlowFixMe Flow doesn't support computed properties yet
get [SYMBOL_TO_STRING_TAG]() {
return 'GraphQLObjectType';
}
}
defineToJSON(GraphQLObjectType);
function defineInterfaces(config) {
const interfaces = resolveThunk(config.interfaces) ?? [];
devAssert(Array.isArray(interfaces), `${config.name} interfaces must be an Array or a function which returns an Array.`);
return interfaces;
}
function defineFieldMap(config) {
const fieldMap = resolveThunk(config.fields);
devAssert(isPlainObj(fieldMap), `${config.name} fields must be an object with field names as keys or a function which returns such an object.`);
return mapValue(fieldMap, (fieldConfig, fieldName) => {
devAssert(isPlainObj(fieldConfig), `${config.name}.${fieldName} field config must be an object.`);
devAssert(!('isDeprecated' in fieldConfig), `${config.name}.${fieldName} should provide "deprecationReason" instead of "isDeprecated".`);
devAssert(fieldConfig.resolve == null || typeof fieldConfig.resolve === 'function', `${config.name}.${fieldName} field resolver must be a function if ` + `provided, but got: ${inspect(fieldConfig.resolve)}.`);
const argsConfig = fieldConfig.args ?? {};
devAssert(isPlainObj(argsConfig), `${config.name}.${fieldName} args must be an object with argument names as keys.`);
const args = objectEntries(argsConfig).map(([argName, argConfig]) => ({
name: argName,
description: argConfig.description,
type: argConfig.type,
defaultValue: argConfig.defaultValue,
extensions: argConfig.extensions && toObjMap(argConfig.extensions),
astNode: argConfig.astNode
}));
return {
name: fieldName,
description: fieldConfig.description,
type: fieldConfig.type,
args,
resolve: fieldConfig.resolve,
subscribe: fieldConfig.subscribe,
isDeprecated: fieldConfig.deprecationReason != null,
deprecationReason: fieldConfig.deprecationReason,
extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions),
astNode: fieldConfig.astNode
};
});
}
function isPlainObj(obj) {
return isObjectLike(obj) && !Array.isArray(obj);
}
function fieldsToFieldsConfig(fields) {
return mapValue(fields, field => ({
description: field.description,
type: field.type,
args: argsToArgsConfig(field.args),
resolve: field.resolve,
subscribe: field.subscribe,
deprecationReason: field.deprecationReason,
extensions: field.extensions,
astNode: field.astNode
}));
}
/**
* @internal
*/
export function argsToArgsConfig(args) {
return keyValMap(args, arg => arg.name, arg => ({
description: arg.description,
type: arg.type,
defaultValue: arg.defaultValue,
extensions: arg.extensions,
astNode: arg.astNode
}));
}
export function isRequiredArgument(arg) {
return isNonNullType(arg.type) && arg.defaultValue === undefined;
}
/**
* Interface Type Definition
*
* When a field can return one of a heterogeneous set of types, a Interface type
* is used to describe what types are possible, what fields are in common across
* all types, as well as a function to determine which type is actually used
* when the field is resolved.
*
* Example:
*
* const EntityType = new GraphQLInterfaceType({
* name: 'Entity',
* fields: {
* name: { type: GraphQLString }
* }
* });
*
*/
export class GraphQLInterfaceType {
constructor(config) {
this.name = config.name;
this.description = config.description;
this.resolveType = config.resolveType;
this.extensions = config.extensions && toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
this._fields = defineFieldMap.bind(undefined, config);
this._interfaces = defineInterfaces.bind(undefined, config);
devAssert(typeof config.name === 'string', 'Must provide name.');
devAssert(config.resolveType == null || typeof config.resolveType === 'function', `${this.name} must provide "resolveType" as a function, ` + `but got: ${inspect(config.resolveType)}.`);
}
getFields() {
if (typeof this._fields === 'function') {
this._fields = this._fields();
}
return this._fields;
}
getInterfaces() {
if (typeof this._interfaces === 'function') {
this._interfaces = this._interfaces();
}
return this._interfaces;
}
toConfig() {
return {
name: this.name,
description: this.description,
interfaces: this.getInterfaces(),
fields: fieldsToFieldsConfig(this.getFields()),
resolveType: this.resolveType,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes ?? []
};
}
toString() {
return this.name;
} // $FlowFixMe Flow doesn't support computed properties yet
get [SYMBOL_TO_STRING_TAG]() {
return 'GraphQLInterfaceType';
}
}
defineToJSON(GraphQLInterfaceType);
/**
* Union Type Definition
*
* When a field can return one of a heterogeneous set of types, a Union type
* is used to describe what types are possible as well as providing a function
* to determine which type is actually used when the field is resolved.
*
* Example:
*
* const PetType = new GraphQLUnionType({
* name: 'Pet',
* types: [ DogType, CatType ],
* resolveType(value) {
* if (value instanceof Dog) {
* return DogType;
* }
* if (value instanceof Cat) {
* return CatType;
* }
* }
* });
*
*/
export class GraphQLUnionType {
constructor(config) {
this.name = config.name;
this.description = config.description;
this.resolveType = config.resolveType;
this.extensions = config.extensions && toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
this._types = defineTypes.bind(undefined, config);
devAssert(typeof config.name === 'string', 'Must provide name.');
devAssert(config.resolveType == null || typeof config.resolveType === 'function', `${this.name} must provide "resolveType" as a function, ` + `but got: ${inspect(config.resolveType)}.`);
}
getTypes() {
if (typeof this._types === 'function') {
this._types = this._types();
}
return this._types;
}
toConfig() {
return {
name: this.name,
description: this.description,
types: this.getTypes(),
resolveType: this.resolveType,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes ?? []
};
}
toString() {
return this.name;
} // $FlowFixMe Flow doesn't support computed properties yet
get [SYMBOL_TO_STRING_TAG]() {
return 'GraphQLUnionType';
}
}
defineToJSON(GraphQLUnionType);
function defineTypes(config) {
const types = resolveThunk(config.types);
devAssert(Array.isArray(types), `Must provide Array of types or a function which returns such an array for Union ${config.name}.`);
return types;
}
/**
* Enum Type Definition
*
* Some leaf values of requests and input values are Enums. GraphQL serializes
* Enum values as strings, however internally Enums can be represented by any
* kind of type, often integers.
*
* Example:
*
* const RGBType = new GraphQLEnumType({
* name: 'RGB',
* values: {
* RED: { value: 0 },
* GREEN: { value: 1 },
* BLUE: { value: 2 }
* }
* });
*
* Note: If a value is not provided in a definition, the name of the enum value
* will be used as its internal value.
*/
export class GraphQLEnumType
/* <T> */
{
constructor(config) {
this.name = config.name;
this.description = config.description;
this.extensions = config.extensions && toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
this._values = defineEnumValues(this.name, config.values);
this._valueLookup = new Map(this._values.map(enumValue => [enumValue.value, enumValue]));
this._nameLookup = keyMap(this._values, value => value.name);
devAssert(typeof config.name === 'string', 'Must provide name.');
}
getValues() {
return this._values;
}
getValue(name) {
return this._nameLookup[name];
}
serialize(outputValue) {
const enumValue = this._valueLookup.get(outputValue);
if (enumValue === undefined) {
throw new GraphQLError(`Enum "${this.name}" cannot represent value: ${inspect(outputValue)}`);
}
return enumValue.name;
}
parseValue(inputValue)
/* T */
{
if (typeof inputValue !== 'string') {
const valueStr = inspect(inputValue);
throw new GraphQLError(`Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr));
}
const enumValue = this.getValue(inputValue);
if (enumValue == null) {
throw new GraphQLError(`Value "${inputValue}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, inputValue));
}
return enumValue.value;
}
parseLiteral(valueNode, _variables)
/* T */
{
// Note: variables will be resolved to a value before calling this function.
if (valueNode.kind !== Kind.ENUM) {
const valueStr = print(valueNode);
throw new GraphQLError(`Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + didYouMeanEnumValue(this, valueStr), valueNode);
}
const enumValue = this.getValue(valueNode.value);
if (enumValue == null) {
const valueStr = print(valueNode);
throw new GraphQLError(`Value "${valueStr}" does not exist in "${this.name}" enum.` + didYouMeanEnumValue(this, valueStr), valueNode);
}
return enumValue.value;
}
toConfig() {
const values = keyValMap(this.getValues(), value => value.name, value => ({
description: value.description,
value: value.value,
deprecationReason: value.deprecationReason,
extensions: value.extensions,
astNode: value.astNode
}));
return {
name: this.name,
description: this.description,
values,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes ?? []
};
}
toString() {
return this.name;
} // $FlowFixMe Flow doesn't support computed properties yet
get [SYMBOL_TO_STRING_TAG]() {
return 'GraphQLEnumType';
}
}
defineToJSON(GraphQLEnumType);
function didYouMeanEnumValue(enumType, unknownValueStr) {
const allNames = enumType.getValues().map(value => value.name);
const suggestedValues = suggestionList(unknownValueStr, allNames);
return didYouMean('the enum value', suggestedValues);
}
function defineEnumValues(typeName, valueMap) {
devAssert(isPlainObj(valueMap), `${typeName} values must be an object with value names as keys.`);
return objectEntries(valueMap).map(([valueName, valueConfig]) => {
devAssert(isPlainObj(valueConfig), `${typeName}.${valueName} must refer to an object with a "value" key ` + `representing an internal value but got: ${inspect(valueConfig)}.`);
devAssert(!('isDeprecated' in valueConfig), `${typeName}.${valueName} should provide "deprecationReason" instead of "isDeprecated".`);
return {
name: valueName,
description: valueConfig.description,
value: valueConfig.value !== undefined ? valueConfig.value : valueName,
isDeprecated: valueConfig.deprecationReason != null,
deprecationReason: valueConfig.deprecationReason,
extensions: valueConfig.extensions && toObjMap(valueConfig.extensions),
astNode: valueConfig.astNode
};
});
}
/**
* Input Object Type Definition
*
* An input object defines a structured collection of fields which may be
* supplied to a field argument.
*
* Using `NonNull` will ensure that a value must be provided by the query
*
* Example:
*
* const GeoPoint = new GraphQLInputObjectType({
* name: 'GeoPoint',
* fields: {
* lat: { type: GraphQLNonNull(GraphQLFloat) },
* lon: { type: GraphQLNonNull(GraphQLFloat) },
* alt: { type: GraphQLFloat, defaultValue: 0 },
* }
* });
*
*/
export class GraphQLInputObjectType {
constructor(config) {
this.name = config.name;
this.description = config.description;
this.extensions = config.extensions && toObjMap(config.extensions);
this.astNode = config.astNode;
this.extensionASTNodes = undefineIfEmpty(config.extensionASTNodes);
this._fields = defineInputFieldMap.bind(undefined, config);
devAssert(typeof config.name === 'string', 'Must provide name.');
}
getFields() {
if (typeof this._fields === 'function') {
this._fields = this._fields();
}
return this._fields;
}
toConfig() {
const fields = mapValue(this.getFields(), field => ({
description: field.description,
type: field.type,
defaultValue: field.defaultValue,
extensions: field.extensions,
astNode: field.astNode
}));
return {
name: this.name,
description: this.description,
fields,
extensions: this.extensions,
astNode: this.astNode,
extensionASTNodes: this.extensionASTNodes ?? []
};
}
toString() {
return this.name;
} // $FlowFixMe Flow doesn't support computed properties yet
get [SYMBOL_TO_STRING_TAG]() {
return 'GraphQLInputObjectType';
}
}
defineToJSON(GraphQLInputObjectType);
function defineInputFieldMap(config) {
const fieldMap = resolveThunk(config.fields);
devAssert(isPlainObj(fieldMap), `${config.name} fields must be an object with field names as keys or a function which returns such an object.`);
return mapValue(fieldMap, (fieldConfig, fieldName) => {
devAssert(!('resolve' in fieldConfig), `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`);
return {
name: fieldName,
description: fieldConfig.description,
type: fieldConfig.type,
defaultValue: fieldConfig.defaultValue,
extensions: fieldConfig.extensions && toObjMap(fieldConfig.extensions),
astNode: fieldConfig.astNode
};
});
}
export function isRequiredInputField(field) {
return isNonNullType(field.type) && field.defaultValue === undefined;
} | the_stack |
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
Date: any;
Time: any;
/** The `Long` scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. */
Long: any;
};
/** 'Canvas' input values */
export type CanvasInput = {
id: Scalars['ID'];
lastUpdatedBySessionEphemeralId?: Maybe<Scalars['String']>;
lastUpdatedByUserName?: Maybe<Scalars['String']>;
project?: Maybe<CanvasProjectRelation>;
owner?: Maybe<CanvasOwnerRelation>;
};
/** Allow manipulating the relationship between the types 'Canvas' and 'User' using the field 'Canvas.owner'. */
export type CanvasOwnerRelation = {
/** Create a document of type 'User' and associate it with the current document. */
create?: Maybe<UserInput>;
/** Connect a document of type 'User' with the current document using its ID. */
connect?: Maybe<Scalars['ID']>;
};
/** Allow manipulating the relationship between the types 'Canvas' and 'Project' using the field 'Canvas.project'. */
export type CanvasProjectRelation = {
/** Create a document of type 'Project' and associate it with the current document. */
create?: Maybe<ProjectInput>;
/** Connect a document of type 'Project' with the current document using its ID. */
connect?: Maybe<Scalars['ID']>;
/** If true, disconnects this document from 'Project' */
disconnect?: Maybe<Scalars['Boolean']>;
};
export type Mutation = {
__typename?: 'Mutation';
/** Update an existing document in the collection of 'User' */
updateUser?: Maybe<User>;
/** Create a new document in the collection of 'User' */
createUser: User;
/** Update an existing document in the collection of 'Project' */
updateProject?: Maybe<Project>;
/** Delete an existing document in the collection of 'Canvas' */
deleteCanvas?: Maybe<Canvas>;
/** Delete an existing document in the collection of 'Project' */
deleteProject?: Maybe<Project>;
/** Create a new document in the collection of 'Project' */
createProject: Project;
/** Delete an existing document in the collection of 'User' */
deleteUser?: Maybe<User>;
/** Create a new document in the collection of 'Canvas' */
createCanvas: Canvas;
/** Update an existing document in the collection of 'Canvas' */
updateCanvas?: Maybe<Canvas>;
};
export type MutationUpdateUserArgs = {
id: Scalars['ID'];
data: UserInput;
};
export type MutationCreateUserArgs = {
data: UserInput;
};
export type MutationUpdateProjectArgs = {
id: Scalars['ID'];
data: ProjectInput;
};
export type MutationDeleteCanvasArgs = {
id: Scalars['ID'];
};
export type MutationDeleteProjectArgs = {
id: Scalars['ID'];
};
export type MutationCreateProjectArgs = {
data: ProjectInput;
};
export type MutationDeleteUserArgs = {
id: Scalars['ID'];
};
export type MutationCreateCanvasArgs = {
data: CanvasInput;
};
export type MutationUpdateCanvasArgs = {
id: Scalars['ID'];
data: CanvasInput;
};
/** Allow manipulating the relationship between the types 'Project' and 'Canvas' using the field 'Project.canvas'. */
export type ProjectCanvasRelation = {
/** Create a document of type 'Canvas' and associate it with the current document. */
create?: Maybe<CanvasInput>;
/** Connect a document of type 'Canvas' with the current document using its ID. */
connect?: Maybe<Scalars['ID']>;
};
/** 'Project' input values */
export type ProjectInput = {
id: Scalars['ID'];
/** Name of the project */
label: Scalars['String'];
owner?: Maybe<ProjectOwnerRelation>;
canvas?: Maybe<ProjectCanvasRelation>;
};
/** Allow manipulating the relationship between the types 'Project' and 'User' using the field 'Project.owner'. */
export type ProjectOwnerRelation = {
/** Create a document of type 'User' and associate it with the current document. */
create?: Maybe<UserInput>;
/** Connect a document of type 'User' with the current document using its ID. */
connect?: Maybe<Scalars['ID']>;
};
/** Allow manipulating the relationship between the types 'User' and 'Canvas'. */
export type UserCanvasesRelation = {
/** Create one or more documents of type 'Canvas' and associate them with the current document. */
create?: Maybe<Array<Maybe<CanvasInput>>>;
/** Connect one or more documents of type 'Canvas' with the current document using their IDs. */
connect?: Maybe<Array<Maybe<Scalars['ID']>>>;
/** Disconnect the given documents of type 'Canvas' from the current document using their IDs. */
disconnect?: Maybe<Array<Maybe<Scalars['ID']>>>;
};
/** 'User' input values */
export type UserInput = {
id: Scalars['ID'];
email: Scalars['String'];
projects?: Maybe<UserProjectsRelation>;
canvases?: Maybe<UserCanvasesRelation>;
};
/** Allow manipulating the relationship between the types 'User' and 'Project'. */
export type UserProjectsRelation = {
/** Create one or more documents of type 'Project' and associate them with the current document. */
create?: Maybe<Array<Maybe<ProjectInput>>>;
/** Connect one or more documents of type 'Project' with the current document using their IDs. */
connect?: Maybe<Array<Maybe<Scalars['ID']>>>;
/** Disconnect the given documents of type 'Project' from the current document using their IDs. */
disconnect?: Maybe<Array<Maybe<Scalars['ID']>>>;
};
/**
* The canvas contains all nodes and edges.
* Nodes and edges are not represented because they're complex shapes,
* and because we won't query them using GQL anyway. (we use GQL for that)
*/
export type Canvas = {
__typename?: 'Canvas';
project: Project;
/** The document's ID. */
_id: Scalars['ID'];
lastUpdatedByUserName?: Maybe<Scalars['String']>;
lastUpdatedBySessionEphemeralId?: Maybe<Scalars['String']>;
id: Scalars['ID'];
owner: User;
/** The document's timestamp. */
_ts: Scalars['Long'];
};
/** The pagination object for elements of type 'Canvas'. */
export type CanvasPage = {
__typename?: 'CanvasPage';
/** The elements of type 'Canvas' in this page. */
data: Array<Maybe<Canvas>>;
/** A cursor for elements coming after the current page. */
after?: Maybe<Scalars['String']>;
/** A cursor for elements coming before the current page. */
before?: Maybe<Scalars['String']>;
};
/**
* A project **belongs** to a user and is related to a canvas.
* A project can be considered as Canvas metadata.
*/
export type Project = {
__typename?: 'Project';
/** The document's ID. */
_id: Scalars['ID'];
/** Name of the project */
label: Scalars['String'];
id: Scalars['ID'];
owner: User;
canvas?: Maybe<Canvas>;
/** The document's timestamp. */
_ts: Scalars['Long'];
};
/** The pagination object for elements of type 'Project'. */
export type ProjectPage = {
__typename?: 'ProjectPage';
/** The elements of type 'Project' in this page. */
data: Array<Maybe<Project>>;
/** A cursor for elements coming after the current page. */
after?: Maybe<Scalars['String']>;
/** A cursor for elements coming before the current page. */
before?: Maybe<Scalars['String']>;
};
export type Query = {
__typename?: 'Query';
findUserByEmail?: Maybe<User>;
/** Find a document from the collection of 'User' by its id. */
findUserByID?: Maybe<User>;
/** Find a document from the collection of 'Canvas' by its id. */
findCanvasByID?: Maybe<Canvas>;
findProjectsByUserId?: Maybe<Array<Project>>;
/** Find a document from the collection of 'Project' by its id. */
findProjectByID?: Maybe<Project>;
};
export type QueryFindUserByEmailArgs = {
email: Scalars['String'];
};
export type QueryFindUserByIdArgs = {
id: Scalars['ID'];
};
export type QueryFindCanvasByIdArgs = {
id: Scalars['ID'];
};
export type QueryFindProjectsByUserIdArgs = {
id: Scalars['ID'];
};
export type QueryFindProjectByIdArgs = {
id: Scalars['ID'];
};
/**
* ###################### FaunaDB internals
* directive @embedded on OBJECT
*
* directive @collection(
* name: String!
* ) on OBJECT
*
* directive @index(
* name: String!
* ) on FIELD_DEFINITION
*
* directive @resolver(
* name: String
* paginated: Boolean! = false
* ) on FIELD_DEFINITION
*
* directive @relation(
* name: String
* ) on FIELD_DEFINITION
*
* directive @unique(
* index: String
* ) on FIELD_DEFINITION
*
* scalar Date
*
* scalar Long
*
* scalar Time
*
* schema{
* query: Query
* }
*
* ###################### Custom
*/
export type User = {
__typename?: 'User';
canvases: CanvasPage;
email: Scalars['String'];
/** The document's ID. */
_id: Scalars['ID'];
id: Scalars['ID'];
projects: ProjectPage;
/** The document's timestamp. */
_ts: Scalars['Long'];
};
/**
* ###################### FaunaDB internals
* directive @embedded on OBJECT
*
* directive @collection(
* name: String!
* ) on OBJECT
*
* directive @index(
* name: String!
* ) on FIELD_DEFINITION
*
* directive @resolver(
* name: String
* paginated: Boolean! = false
* ) on FIELD_DEFINITION
*
* directive @relation(
* name: String
* ) on FIELD_DEFINITION
*
* directive @unique(
* index: String
* ) on FIELD_DEFINITION
*
* scalar Date
*
* scalar Long
*
* scalar Time
*
* schema{
* query: Query
* }
*
* ###################### Custom
*/
export type UserCanvasesArgs = {
_size?: Maybe<Scalars['Int']>;
_cursor?: Maybe<Scalars['String']>;
};
/**
* ###################### FaunaDB internals
* directive @embedded on OBJECT
*
* directive @collection(
* name: String!
* ) on OBJECT
*
* directive @index(
* name: String!
* ) on FIELD_DEFINITION
*
* directive @resolver(
* name: String
* paginated: Boolean! = false
* ) on FIELD_DEFINITION
*
* directive @relation(
* name: String
* ) on FIELD_DEFINITION
*
* directive @unique(
* index: String
* ) on FIELD_DEFINITION
*
* scalar Date
*
* scalar Long
*
* scalar Time
*
* schema{
* query: Query
* }
*
* ###################### Custom
*/
export type UserProjectsArgs = {
_size?: Maybe<Scalars['Int']>;
_cursor?: Maybe<Scalars['String']>;
}; | the_stack |
import { StateService } from '@uirouter/core';
import angular = require('angular');
import _ = require('lodash');
class ApiPoliciesController {
private apiPoliciesByPath: any;
private policiesToCopy: any[];
private policiesMap: any;
private selectedApiPolicy: any;
private httpMethods: string[];
private httpMethodsFilter: string[];
private pathsToCompare: any;
private dndEnabled: boolean;
private pathsInitialized: any;
private httpMethodsUpdated: boolean;
private schemaByPolicyId: any;
constructor(
private ApiService,
private PolicyService,
private $mdDialog: angular.material.IDialogService,
private NotificationService,
private $scope,
private dragularService,
private $q,
private $rootScope,
private StringService,
private UserService,
private $state: StateService,
) {
'ngInject';
this.pathsInitialized = [];
this.dndEnabled = UserService.isUserHasPermissions(['api-definition-u']);
this.apiPoliciesByPath = {};
this.policiesToCopy = [];
this.policiesMap = {};
this.selectedApiPolicy = {};
this.httpMethods = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'PATCH', 'OPTIONS', 'TRACE', 'CONNECT'];
this.httpMethodsFilter = _.clone(this.httpMethods);
this.httpMethodsUpdated = false;
this.schemaByPolicyId = {};
this.listAllPolicies().then((policies) => {
_.forEach(policies, ({ policy }) => {
this.policiesToCopy.push(policy);
this.policiesMap[policy.policyId] = policy;
});
_.forEach(this.$scope.$parent.apiCtrl.api.paths, (policies, path) => {
this.apiPoliciesByPath[path] = _.cloneDeep(policies);
});
this.completeApiPolicies(this.apiPoliciesByPath);
this.initDragular();
this.pathsToCompare = this.generatePathsToCompare();
});
this.$scope.$on(
'dragulardrop',
(event, element, dropzoneElt, draggableElt, draggableObjList, draggableIndex, dropzoneObjList, dropzoneIndex) => {
if (dropzoneObjList !== null) {
// Automatically display the configuration associated to the dragged policy
this.editPolicy(dropzoneIndex, dropzoneElt.attributes['data-path'].value).then((schema) => {
// Automatically save if there is no json schema configuration attached to the dragged policy.
if (schema.id === 'empty') {
this.savePaths();
}
});
} else {
this.savePaths();
}
},
);
}
generatePathsToCompare() {
return _.map(_.keys(this.apiPoliciesByPath), (p) => {
return this.clearPathParam(p);
});
}
completeApiPolicies(pathMap) {
_.forEach(pathMap, (policies) => {
_.forEach(policies, (policy) => {
_.forEach(policy, (value, property) => {
if (property !== 'methods' && property !== 'enabled' && property !== 'description' && property !== '$$hashKey') {
policy.policyId = property;
const currentPolicy = this.policiesMap[policy.policyId];
if (currentPolicy) {
policy.name = currentPolicy.name;
policy.type = currentPolicy.type;
policy.version = currentPolicy.version;
policy.schema = currentPolicy.schema;
}
}
});
if (!policy.methods) {
policy.methods = _.clone(this.httpMethods);
} else {
policy.methods = _.map(policy.methods, (method: string) => {
return method.toUpperCase();
});
}
});
});
}
initDragular() {
const dragularSrcOptions = document.querySelector('.gravitee-policy-draggable');
this.dragularService([dragularSrcOptions], {
moves: function () {
return true;
},
copy: true,
scope: this.$scope,
containersModel: this.policiesToCopy,
classes: {
unselectable: 'gravitee-policy-draggable-selected',
},
nameSpace: 'policies',
accepts: this.acceptDragDrop,
});
}
initDragularDropZone(path) {
if (!this.pathsInitialized[path]) {
const dragularApiOptions = document.querySelector('.dropzone-' + this.StringService.hashCode(path));
if (dragularApiOptions) {
this.dragularService([dragularApiOptions], {
moves: function () {
return true;
},
copy: false,
scope: this.$scope,
containersModel: this.apiPoliciesByPath[path],
classes: {
unselectable: 'gravitee-policy-draggable-selected',
},
nameSpace: 'policies',
accepts: this.acceptDragDrop,
});
this.pathsInitialized[path] = true;
}
}
}
listAllPolicies() {
return this.PolicyService.list({ expandSchema: true }).then((policies) => {
return _.map(policies.data, (originalPolicy: any) => {
const policy = {
policyId: originalPolicy.id,
methods: this.httpMethods,
version: originalPolicy.version,
name: originalPolicy.name,
type: originalPolicy.type,
description: originalPolicy.description,
enabled: originalPolicy.enabled || true,
};
return { policy };
});
});
}
acceptDragDrop(el, target, source) {
const draggable = document.querySelector('.gravitee-policy-draggable');
return source === draggable || source === target;
}
editPolicy(index, path) {
this.$scope.policyJsonSchemaForm = ['*'];
this.selectedApiPolicy = this.apiPoliciesByPath[path][index];
if (this.schemaByPolicyId[this.selectedApiPolicy.policyId] === undefined) {
return this.PolicyService.getSchema(this.selectedApiPolicy.policyId).then((response) => {
this.$scope.policyJsonSchema = this.schemaByPolicyId[this.selectedApiPolicy.policyId] = response.data;
this.selectedApiPolicy[this.selectedApiPolicy.policyId] = this.selectedApiPolicy[this.selectedApiPolicy.policyId] || {};
this.checkEmptySchema();
return this.$scope.policyJsonSchema;
});
} else {
return this.$q(() => {
this.$scope.policyJsonSchema = this.schemaByPolicyId[this.selectedApiPolicy.policyId];
this.selectedApiPolicy[this.selectedApiPolicy.policyId] = this.selectedApiPolicy[this.selectedApiPolicy.policyId] || {};
this.checkEmptySchema();
return this.$scope.policyJsonSchema;
});
}
}
getHttpMethodClass(method, methods) {
return 'gravitee-policy-method-badge-' + method + (methods.indexOf(method) > -1 ? '-selected' : '-unselected');
}
getApiPolicyClass(policy) {
const classes = [];
// eslint-disable-next-line angular/no-private-call
const selected = this.selectedApiPolicy && this.selectedApiPolicy.$$hashKey === policy.$$hashKey;
if (selected) {
classes.push('gravitee-policy-card-selected');
}
if (!selected && !policy.enabled) {
classes.push('gravitee-policy-card-disabled');
}
if (!policy.name) {
classes.push('gravitee-policy-card-missed');
}
return classes.join(' ');
}
getDropzoneClass(path) {
return 'gravitee-policy-dropzone ' + 'gravitee-policy-dropzone-filled' + ' dropzone-' + this.StringService.hashCode(path);
}
toggleHttpMethod(method, methods) {
this.httpMethodsUpdated = true;
const index = methods.indexOf(method);
if (index > -1) {
methods.splice(index, 1);
} else {
methods.push(method);
}
}
filterByMethod(policy) {
return _.reduce(
_.map(policy.methods, (method: string) => {
return this.httpMethodsFilter.indexOf(method) < 0;
}),
(result, n) => {
return result && n;
},
);
}
removePolicy(index, path, ev) {
ev.stopPropagation();
this.selectedApiPolicy = null;
// eslint-disable-next-line angular/no-private-call
const hashKey = this.apiPoliciesByPath[path][index].$$hashKey;
this.$mdDialog
.show({
controller: 'DialogConfirmController',
controllerAs: 'ctrl',
template: require('../../../../components/dialog/confirmWarning.dialog.html'),
clickOutsideToClose: true,
locals: {
title: 'Are you sure you want to remove this policy?',
confirmButton: 'Remove',
},
})
.then((response) => {
if (response) {
_.forEach(this.apiPoliciesByPath[path], (policy, idx) => {
// eslint-disable-next-line angular/no-private-call
if (policy.$$hashKey === hashKey) {
this.apiPoliciesByPath[path].splice(idx, 1);
return false;
}
});
this.savePaths();
}
});
}
editPolicyDescription(index, path, ev) {
ev.stopPropagation();
this.selectedApiPolicy = null;
const policy = this.apiPoliciesByPath[path][index];
this.$mdDialog
.show({
controller: 'DialogEditPolicyController',
controllerAs: 'editPolicyDialogCtrl',
template: require('./dialog/policy.dialog.html'),
clickOutsideToClose: true,
locals: {
description: policy.description,
},
})
.then(
(description) => {
policy.description = description;
this.savePaths();
},
() => {
// You cancelled the dialog
},
);
}
switchPolicyEnabled(index, path, ev) {
ev.stopPropagation();
this.selectedApiPolicy = null;
const policy = this.apiPoliciesByPath[path][index];
policy.enabled = !policy.enabled;
this.savePaths();
}
savePaths() {
this.$scope.$parent.apiCtrl.api.paths = _.cloneDeep(this.apiPoliciesByPath);
_.forEach(this.$scope.$parent.apiCtrl.api.paths, (policies) => {
_.forEach(policies, (policy) => {
delete policy.policyId;
delete policy.name;
delete policy.type;
delete policy.version;
delete policy.schema;
// do not save empty fields on arrays
_.forOwn(policy, (policyAttributeValueObject) => {
_.forOwn(policyAttributeValueObject, (policyAttributeAttribute) => {
if (_.isArray(policyAttributeAttribute)) {
_.remove(policyAttributeAttribute, (policyAttributeAttributeItem) => {
return policyAttributeAttributeItem === undefined || '' === policyAttributeAttributeItem;
});
}
});
});
});
});
const api = this.$scope.$parent.apiCtrl.api;
return this.ApiService.update(api).then((updatedApi) => {
this.NotificationService.show("API '" + updatedApi.data.name + "' saved");
this.pathsToCompare = this.generatePathsToCompare();
this.httpMethodsUpdated = false;
this.$rootScope.$broadcast('apiChangeSuccess', { api: updatedApi.data });
});
}
showAddPathModal(event) {
this.$mdDialog
.show({
controller: 'AddPoliciesPathController',
controllerAs: 'addPoliciesPathCtrl',
template: require('./addPoliciesPath.html'),
parent: angular.element(document.body),
targetEvent: event,
clickOutsideToClose: true,
locals: {
paths: this.apiPoliciesByPath,
rootCtrl: this,
},
})
.then((paths) => {
this.apiPoliciesByPath = paths;
this.savePaths();
});
}
migrateApiToPolicyStudio() {
this.$mdDialog
.show({
controller: 'DialogConfirmController',
controllerAs: 'ctrl',
template: require('../../../../components/dialog/confirmWarning.dialog.html'),
clickOutsideToClose: true,
locals: {
title: 'Are you sure you want to migrate to Policy Studio?',
msg: 'The migration process will save the API definition, but it will not be deployed. You can still do a rollback from history.',
confirmButton: 'Yes, I want to migrate',
},
})
.then((response) => {
if (response) {
this.ApiService.migrateApiToPolicyStudio(this.$scope.$parent.apiCtrl.api.id).then((response) => {
this.$state.go('management.apis.detail.design.flows', { apiId: response.data.id }, { reload: true });
});
}
});
}
removePath(path) {
this.selectedApiPolicy = {};
this.$mdDialog
.show({
controller: 'DialogConfirmController',
controllerAs: 'ctrl',
template: require('../../../../components/dialog/confirmWarning.dialog.html'),
clickOutsideToClose: true,
locals: {
title: 'Are you sure you want to remove this path?',
confirmButton: 'Remove',
},
})
.then((response) => {
if (response) {
delete this.apiPoliciesByPath[path];
this.pathsInitialized[path] = false;
this.savePaths();
}
});
}
pathNotExists(path, index) {
if (!path || path.trim() === '') {
return true;
}
if (index && this.clearPathParam(path) === this.clearPathParam(this.sortedPaths()[index])) {
return true;
}
return !_.includes(this.pathsToCompare, this.clearPathParam(path));
}
pathStartWithSlash(path) {
if (!path || path.trim() === '') {
return true;
}
return path[0] === '/';
}
clearPathParam(path) {
if (path === '/') {
return '/';
} else {
return path
.trim()
.replace(/(:.*?\/)|(:.*$)/g, ':x/')
.replace(/\/+$/, '');
}
}
sortedPaths() {
const paths = _.keys(this.apiPoliciesByPath);
return _.sortBy(paths, (path) => {
return this.clearPathParam(path);
});
}
pathKeyPress(ev, el, newPath, index) {
switch (ev.keyCode) {
case 13: // enter
if (!el.$invalid) {
const oldPath: any = this.sortedPaths()[index];
this.apiPoliciesByPath[newPath] = this.apiPoliciesByPath[oldPath];
delete this.apiPoliciesByPath[oldPath];
this.savePaths();
}
break;
case 27: // escape
this.restoreOldPath(index, el);
break;
default:
break;
}
}
restoreOldPath(index, el) {
el.$setViewValue(this.sortedPaths()[index]);
el.$commitViewValue();
// TODO: check editPathForm on form
(document.forms as any).editPathForm['path' + index].value = this.sortedPaths()[index];
}
private checkEmptySchema() {
if (!this.$scope.policyJsonSchema || Object.keys(this.$scope.policyJsonSchema).length === 0) {
this.$scope.policyJsonSchema = {
type: 'object',
id: 'empty',
properties: { '': {} },
};
}
this.httpMethodsUpdated = false;
}
}
export default ApiPoliciesController; | the_stack |
import { PivotEngine, IDataOptions, IDataSet } from '../../src/base/engine';
import { pivot_dataset } from '../base/datasource.spec';
import { profile, inMB, getMemoryProfile } from '../common.spec';
describe('Calculated field', () => {
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;
}
});
let ds: IDataSet[] = pivot_dataset as IDataSet[];
let dataSourceSettings: IDataOptions = {
expandAll: false,
enableSorting: true,
allowMemberFilter: true,
sortSettings: [{ name: 'company', order: 'Descending' }],
filterSettings: [{ name: 'name', type: 'Include', items: ['Knight Wooten'] },
{ name: 'company', type: 'Include', items: ['NIPAZ'] },
{ name: 'gender', type: 'Include', items: ['male'] }],
dataSource: ds,
calculatedFieldSettings: [{ name: 'price', formula: '10+5' },
{ name: 'total', formula: '"Sum(balance)"+"Sum(quantity)"' }],
rows: [{ name: 'company' }, { name: 'state' }],
columns: [{ name: 'name' }],
values: [{ name: 'balance' }, { name: 'price', type: 'CalculatedField' },
{ name: 'quantity' }], filters: [{ name: 'gender' }]
};
let pivotEngine: PivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
it('Calculated field with simple calculation', () => {
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('15');
});
it('Calculated field with complex calculation', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '(("Sum(balance)"*10^3+"Count(quantity)")/100)+"Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('11673.65');
});
it('Calculated field using min function', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = 'min("Sum(balance)","Count(quantity)")';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1');
});
it('Calculated field using max function', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = 'max("Sum(balance)","Count(quantity)")';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1061.24');
});
it('Calculated field using abs function', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = 'abs("Sum(balance)") + "Count(quantity)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1062.24');
});
it('Calculated field using Math.min function', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = 'Math.min("Sum(balance)","Count(quantity)")';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1');
});
it('Calculated field using Math.max function', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = 'Math.max("Sum(balance)","Count(quantity)")';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1061.24');
});
it('Calculated field using Math.abs function', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = 'Math.abs("Sum(balance)") + "Count(quantity)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1062.24');
});
it('Calculated field using > condition', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '"Sum(balance)" > "Count(quantity)" ? "Count(quantity)" : "Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1');
});
it('Calculated field using < condition', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '"Sum(balance)" < "Count(quantity)" ? "Count(quantity)" : "Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1061.24');
});
it('Calculated field using >= condition', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '"Sum(balance)" >= "Count(quantity)" ? "Count(quantity)" : "Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1');
});
it('Calculated field using <= condition', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '"Sum(balance)" <= "Count(quantity)" ? "Count(quantity)" : "Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1061.24');
});
it('Calculated field using == condition', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '"Sum(balance)" == "Count(quantity)" ? "Count(quantity)" : "Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1061.24');
});
it('Calculated field using != condition', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '"Sum(balance)" != "Count(quantity)" ? "Count(quantity)" : "Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1');
});
it('Calculated field using | condition', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '"Sum(balance)" | "Count(quantity)" ? "Count(quantity)" : "Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1');
});
it('Calculated field using & condition', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '"Sum(balance)" & "Count(quantity)" ? "Count(quantity)" : "Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1');
});
it('Calculated field using isNaN condition', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = 'isNaN("Sum(balance)") ? "Count(quantity)" : "Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1061.24');
});
it('Calculated field using !isNaN condition', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '!isNaN("Sum(balance)") ? "Count(quantity)" : "Sum(balance)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('1');
});
it('Calculated field with unavailable field', () => {
dataSourceSettings.calculatedFieldSettings[0].formula = '!isNaN("Sum(balance)") ? "Count(test)" : "Sum(test)"';
pivotEngine = new PivotEngine(); pivotEngine.renderEngine(dataSourceSettings);
expect((pivotEngine.pivotValues[1][2] as IDataSet).formattedText).toBe('price');
expect((pivotEngine.pivotValues[2][2] as IDataSet).formattedText).toBe('0');
});
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 * as Comlink from "comlink";
// @ts-ignore
import parse from "shell-parse";
import Process from "../process/process";
import CommandOptions from "../command/command-options";
import WasmTerminalConfig from "../wasm-terminal-config";
import WasmTty from "../wasm-tty/wasm-tty";
import IoDeviceWindow from "../io-device-window/io-device-window";
/*ROLLUP_REPLACE_INLINE
// @ts-ignore
import processWorkerInlinedUrl from "../../lib/workers/process.worker.js";
ROLLUP_REPLACE_INLINE*/
const isFunction = (value: any) => value && (Object.prototype.toString.call(value) === "[object Function]" || "function" === typeof value || value instanceof Function);
let processWorkerBlobUrl: string | undefined;
export default class CommandRunner {
commandOptionsForProcessesToRun: Array<any>;
spawnedProcessObjects: Array<any>;
spawnedProcesses: number;
pipedStdinDataForNextProcess: Uint8Array;
isRunning: boolean;
supportsSharedArrayBuffer: boolean;
wasmTerminalConfig: WasmTerminalConfig;
commandString: string;
commandStartReadCallback: Function;
commandEndCallback: Function;
wasmTty?: WasmTty;
constructor(
wasmTerminalConfig: WasmTerminalConfig,
commandString: string,
commandStartReadCallback: Function,
commandEndCallback: Function,
wasmTty?: WasmTty
) {
this.wasmTerminalConfig = wasmTerminalConfig;
this.commandString = commandString;
this.commandStartReadCallback = commandStartReadCallback;
this.commandEndCallback = commandEndCallback;
if (wasmTty) {
this.wasmTty = wasmTty;
}
this.commandOptionsForProcessesToRun = [];
this.spawnedProcessObjects = [];
this.spawnedProcesses = 0;
this.pipedStdinDataForNextProcess = new Uint8Array();
this.isRunning = false;
this.supportsSharedArrayBuffer =
this.wasmTerminalConfig.processWorkerUrl &&
(window as any).SharedArrayBuffer &&
(window as any).Atomics;
}
async runCommand() {
// First, let's parse the string into a bash AST
const commandAst = parse(this.commandString);
try {
if (commandAst.length > 1) {
throw new Error("Only one command permitted");
}
if (commandAst[0].type !== "command") {
throw new Error("Only commands allowed");
}
// Translate our AST into Command Options
this.commandOptionsForProcessesToRun = await this._getCommandOptionsFromAST(
commandAst[0],
this.wasmTerminalConfig,
this.wasmTty
);
} catch (c) {
if (this.wasmTty) {
this.wasmTty.print("\r\n");
this.wasmTty.print(`wasm shell: parse error (${c.toString()})\r\n`);
}
console.error(c);
this.commandEndCallback();
return;
}
this.isRunning = true;
// Spawn the first process
await this._tryToSpawnProcess(0);
}
kill() {
if (!this.isRunning) {
return;
}
this.spawnedProcessObjects.forEach(processObject => {
if (processObject.worker) {
processObject.worker.terminate();
}
if (processObject.ioDeviceWindow) {
processObject.ioDeviceWindow.close();
}
});
this.commandOptionsForProcessesToRun = [];
this.spawnedProcessObjects = [];
this.isRunning = false;
this.commandEndCallback();
}
_addStdinToSharedStdin(data: Uint8Array, processObjectIndex: number) {
// Pass along the stdin to the shared object
if (!this.spawnedProcessObjects[processObjectIndex]) {
return;
}
const sharedStdin = this.spawnedProcessObjects[processObjectIndex]
.sharedStdin;
let startingIndex = 1;
if (sharedStdin[0] > 0) {
startingIndex = sharedStdin[0];
}
data.forEach((value, index) => {
sharedStdin[startingIndex + index] = value;
});
sharedStdin[0] = startingIndex + data.length - 1;
Atomics.notify(sharedStdin, 0, 1);
}
async _tryToSpawnProcess(commandOptionIndex: number) {
if (
commandOptionIndex + 1 > this.spawnedProcesses &&
this.spawnedProcessObjects.length < 2 &&
commandOptionIndex < this.commandOptionsForProcessesToRun.length
) {
this.spawnedProcesses++;
await this._spawnProcess(commandOptionIndex);
}
}
async _spawnProcess(commandOptionIndex: number) {
let spawnedProcessObject = undefined;
// Check if it is a Wasm command, that can be placed into a worker.
if (
this.commandOptionsForProcessesToRun[commandOptionIndex].module &&
this.supportsSharedArrayBuffer
) {
spawnedProcessObject = await this._spawnProcessAsWorker(
commandOptionIndex
);
} else {
spawnedProcessObject = await this._spawnProcessAsService(
commandOptionIndex
);
}
// Record this process as spawned
this.spawnedProcessObjects.push(spawnedProcessObject);
// Start the process
spawnedProcessObject.process.start(
this.pipedStdinDataForNextProcess.length > 0
? this.pipedStdinDataForNextProcess
: undefined
);
// Remove the piped stdin if we passed it
if (this.pipedStdinDataForNextProcess.length > 0) {
this.pipedStdinDataForNextProcess = new Uint8Array();
}
// Try to spawn the next process, if we haven't already
let isNextCallbackCommand = false;
if (this.commandOptionsForProcessesToRun.length > commandOptionIndex + 1) {
isNextCallbackCommand =
this.commandOptionsForProcessesToRun[commandOptionIndex + 1]
.callback !== undefined;
}
if (this.supportsSharedArrayBuffer && !isNextCallbackCommand) {
this._tryToSpawnProcess(commandOptionIndex + 1);
}
}
async _spawnProcessAsWorker(commandOptionIndex: number) {
if (!this.wasmTerminalConfig.processWorkerUrl) {
throw new Error("Terminal Config missing the Process Worker URL");
}
let processWorkerUrl = this.wasmTerminalConfig.processWorkerUrl;
/*ROLLUP_REPLACE_INLINE
processWorkerUrl = processWorkerInlinedUrl;
ROLLUP_REPLACE_INLINE*/
// Generate our process
const workerBlobUrl = await this._getBlobUrlForProcessWorker(
processWorkerUrl,
this.wasmTty
);
const processWorker = new Worker(workerBlobUrl);
const processComlink = Comlink.wrap(processWorker);
// Generate our shared buffer
const sharedStdinBuffer = new SharedArrayBuffer(8192);
// Get our filesystem state
const wasmFsJson = this.wasmTerminalConfig.wasmFs.toJSON();
// Create our Io Device Window
const sharedIoDeviceInputBuffer = new SharedArrayBuffer(8192);
const ioDeviceWindow = new IoDeviceWindow(sharedIoDeviceInputBuffer);
// @ts-ignore
const process: any = await new processComlink(
// Command Options
this.commandOptionsForProcessesToRun[commandOptionIndex],
// WasmFs File System JSON
wasmFsJson,
// Data Callback
Comlink.proxy(
this._processDataCallback.bind(this, {
commandOptionIndex,
sync: false
})
),
// End Callback
Comlink.proxy(
this._processEndCallback.bind(this, {
commandOptionIndex,
processWorker
})
),
// Error Callback
Comlink.proxy(
this._processErrorCallback.bind(this, { commandOptionIndex })
),
// Io Device Window
Comlink.proxy(ioDeviceWindow),
// Shared Array Buffer for IoDevice Input
sharedIoDeviceInputBuffer,
// Shared Array Bufer for Stdin
sharedStdinBuffer,
// Stdin read callback
Comlink.proxy(this._processStartStdinReadCallback.bind(this))
);
// Initialize the shared Stdin.
// Index 0 will be number of elements in buffer
const sharedStdin = new Int32Array(sharedStdinBuffer);
sharedStdin[0] = -1;
return {
process,
commandOptionIndex,
ioDeviceWindow,
worker: processWorker,
sharedStdin: sharedStdin
};
}
async _spawnProcessAsService(commandOptionIndex: number) {
// Get our filesystem state
const wasmFsJson = this.wasmTerminalConfig.wasmFs.toJSON();
// Create our Io Device Window
const ioDeviceWindow = new IoDeviceWindow();
const process = new Process(
// Command Options
this.commandOptionsForProcessesToRun[commandOptionIndex],
// WasmFs File System JSON
wasmFsJson,
// Data Callback
this._processDataCallback.bind(this, { commandOptionIndex, sync: true }),
// End Callback
this._processEndCallback.bind(this, { commandOptionIndex }),
// Error Callback
this._processErrorCallback.bind(this, { commandOptionIndex }),
// Io Device Window
ioDeviceWindow
);
return {
process,
commandOptionIndex,
ioDeviceWindow
};
}
_processDataCallback(
{ commandOptionIndex, sync }: { commandOptionIndex: number; sync: boolean },
data: Uint8Array
) {
if (!this.isRunning) return;
if (commandOptionIndex < this.commandOptionsForProcessesToRun.length - 1) {
// Pass along to the next spawned process
if (
// Ensure we can use shared array buffer,
// And We have more than one proccess spawned,
// And we are not the last spawned process we are trying to premptively write to
// The last && fixes a race condition from:
// https://github.com/wasmerio/wasmer-js/issues/160
this.supportsSharedArrayBuffer &&
this.spawnedProcessObjects.length > 1 &&
this.spawnedProcessObjects[this.spawnedProcessObjects.length - 1]
.commandOptionIndex > commandOptionIndex
) {
// Send the output to stdin since we are being piped
this._addStdinToSharedStdin(data, 1);
} else {
const newPipedStdinData = new Uint8Array(
data.length + this.pipedStdinDataForNextProcess.length
);
newPipedStdinData.set(this.pipedStdinDataForNextProcess);
newPipedStdinData.set(data, this.pipedStdinDataForNextProcess.length);
this.pipedStdinDataForNextProcess = newPipedStdinData;
}
} else {
// Write the output to our terminal
let dataString = new TextDecoder("utf-8").decode(data);
if (this.wasmTty) {
this.wasmTty.print(dataString, sync);
}
}
}
_processEndCallback(
endCallbackConfig: {
commandOptionIndex: number;
processWorker?: Worker;
},
wasmFsJson: any
) {
const { commandOptionIndex, processWorker } = endCallbackConfig;
if (processWorker) {
// Terminate our worker
processWorker.terminate();
}
// Sync our filesystem
if (wasmFsJson) {
this.wasmTerminalConfig.wasmFs.fromJSON(wasmFsJson);
}
if (commandOptionIndex < this.commandOptionsForProcessesToRun.length - 1) {
// Try to spawn the next process, if we haven't already
this._tryToSpawnProcess(commandOptionIndex + 1);
} else {
// We are now done!
// Call the passed end callback
this.isRunning = false;
this.commandEndCallback();
}
// Remove ourself from the spawned workers
this.spawnedProcessObjects.shift();
}
_processErrorCallback(
errorCallbackConfig: { commandOptionIndex: number },
error: string,
wasmFsJson: any
) {
const { commandOptionIndex } = errorCallbackConfig;
console.error(
`${this.commandOptionsForProcessesToRun[commandOptionIndex].args[0]}: ${error}`
);
// Sync our filesystem
if (wasmFsJson) {
this.wasmTerminalConfig.wasmFs.fromJSON(wasmFsJson);
}
// Kill the process
this.kill();
this.commandEndCallback();
}
_processStartStdinReadCallback() {
this.commandStartReadCallback().then((stdin: string) => {
const data = new TextEncoder().encode(stdin + "\n");
this._addStdinToSharedStdin(data, 0);
});
}
async _getBlobUrlForProcessWorker(
processWorkerUrl: string,
wasmTty?: WasmTty
) {
if (processWorkerBlobUrl) {
return processWorkerBlobUrl;
}
if (wasmTty) {
wasmTty.printStatus(
"[INFO] Downloading the process Web Worker (This happens once)..."
);
}
// Fetch the worker, but at least show the message for a short while
const workerString = await Promise.all([
fetch(processWorkerUrl).then(response => response.text()),
new Promise(resolve => setTimeout(resolve, 500))
]).then(responses => responses[0]);
if (wasmTty) {
wasmTty.clearStatus();
}
// Create the worker blob and URL
const workerBlob = new Blob([workerString as any]);
processWorkerBlobUrl = window.URL.createObjectURL(workerBlob);
return processWorkerBlobUrl;
}
async _getCommandOptionsFromAST(
ast: any,
wasmTerminalConfig: WasmTerminalConfig,
wasmTty?: WasmTty
): Promise<Array<CommandOptions>> {
// The array of command options we are returning
let commandOptions: Array<CommandOptions> = [];
let commandName = ast.command.value;
let commandArgs = ast.args.map((arg: any) => arg.value);
let args = [commandName, ...commandArgs];
const envEntries = Object.entries(ast.env).map(
([key, value]: [string, any]) => [key, value.value]
);
let env: any = {};
// Manually doing Object.fromEntries for compatibility with Node 10
envEntries.forEach(([key, value]) => {
env[key] = value;
});
if (wasmTty) {
const { rows, cols } = wasmTty.getTermSize();
env.LINES = rows;
env.COLUMNS = cols;
}
// Get other commands from the redirects
const redirectTask = async () => {
if (ast.redirects) {
let astRedirect = ast.redirects[0];
if (astRedirect && astRedirect.type === "pipe") {
const redirectedCommandOptions = await this._getCommandOptionsFromAST(
astRedirect.command,
wasmTerminalConfig,
wasmTty
);
// Add the child options to our command options
commandOptions = commandOptions.concat(redirectedCommandOptions);
}
}
};
// Add a Wasm module command
await redirectTask();
// Fetch the command
if (wasmTty) {
wasmTty.printStatus(`[INFO] Fetching the command ${commandName} ...`);
}
const response = await wasmTerminalConfig.fetchCommand({
args,
env
});
if (wasmTty) {
wasmTty.clearStatus();
}
if (response instanceof Uint8Array) {
// Compile the Wasm Module
const wasmModule = await WebAssembly.compile(response);
commandOptions.unshift({
args,
env,
module: wasmModule
});
} else if (isFunction(response)) {
commandOptions.unshift({
args,
env,
// @ts-ignore
callback: response
});
} else {
commandOptions.unshift(response as any);
}
return commandOptions;
}
} | the_stack |
import {
CUSTOM_ELEMENTS_SCHEMA,
DebugElement,
Component,
Input,
SimpleChanges,
SimpleChange
} from '@angular/core';
import { By } from '@angular/platform-browser';
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { StoreModule } from '@ngrx/store';
import { MockComponent } from 'ng2-mock-component';
import { runtimeChecks } from 'app/ngrx.reducers';
import { ChefPipesModule } from 'app/pipes/chef-pipes.module';
import { Node } from 'app/entities/client-runs/client-runs.model';
import { DeletableNodeControlComponent
} from '../deletable-node-control/deletable-node-control.component';
import { ClientRunsTableComponent } from './client-runs-table.component';
@Component({
selector: 'app-authorized',
template: '<ng-content *ngIf="visible"></ng-content>'
})
class MockAllowedAuthorizedComponent {
public visible = true;
@Input() anyOf: any;
@Input() allOf: any;
@Input() overrideVisible = true;
}
@Component({
selector: 'app-authorized',
template: '<ng-content *ngIf="visible"></ng-content>'
})
class MockDisallowedAuthorizedComponent {
public visible = false;
@Input() anyOf: any;
@Input() allOf: any;
@Input() overrideVisible = false;
}
function createSampleNodes(): Node[] {
return [
{
id: '56343c09-e968-43b3-b896-edd7cca03fbd',
name: 'A-non-architecto',
fqdn: 'A-non-architecto.bergnaum.co',
checkin: null,
uptime_seconds: 17112079,
environment: 'test',
platform: 'solaris',
policy_group: '',
organization: '',
source_fqdn: '',
status: 'failure',
latestRunId: '22efcb97-ae0d-4ece-b284-51bc73b2c6cc',
hasRuns: true,
lastCcrReceived: new Date(),
deprecationsCount: 0,
chefVersion: '12.6.0'
},
{
id: '96989735-5a77-499d-a4c7-b3a1144efaaf',
name: 'Ad-fugiat-optio',
fqdn: 'Ad-fugiat-optio.bergnaum.co',
source_fqdn: '',
checkin: null,
uptime_seconds: 11377524,
organization: '',
environment: '',
platform: 'centos',
policy_group: 'dev',
status: 'success',
latestRunId: '',
hasRuns: false,
lastCcrReceived: new Date(),
deprecationsCount: 0,
chefVersion: '12.6.0'
},
{
id: '96989735-5a77-499d-a4c7-b3a1144efaaf',
name: 'Ad-fugiat-optio',
fqdn: 'Ad-fugiat-optio.bergnaum.co',
source_fqdn: '',
checkin: null,
uptime_seconds: 11377524,
organization: '',
environment: '',
platform: 'centos',
policy_group: 'dev',
status: 'missing',
latestRunId: '',
hasRuns: false,
lastCcrReceived: new Date(),
deprecationsCount: 0,
chefVersion: '12.6.0'
},
{
id: '96989735-5a77-499d-a4c7-b3a1144efaaf',
name: 'database',
fqdn: 'Ad-fugiat-optio.bergnaum.or',
source_fqdn: '',
checkin: null,
uptime_seconds: 113774,
organization: '',
environment: '',
platform: 'ubuntu',
policy_group: 'dev',
status: 'missing',
latestRunId: '',
hasRuns: false,
lastCcrReceived: new Date(),
deprecationsCount: 0,
chefVersion: '12.6.0'
}
];
}
describe('ClientRunsTable', () => {
let fixture, element;
let component: ClientRunsTableComponent;
describe('user does not have permissions to delete nodes', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
ChefPipesModule,
StoreModule.forRoot({
}, { runtimeChecks })
],
declarations: [
ClientRunsTableComponent,
DeletableNodeControlComponent,
MockDisallowedAuthorizedComponent,
MockComponent({ selector: 'chef-tooltip' }),
MockComponent({ selector: 'chef-dropdown' })
],
providers: [
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
});
fixture = TestBed.createComponent(ClientRunsTableComponent);
component = fixture.componentInstance;
element = fixture.debugElement;
component.defaultFieldDirection = {
name: 'ASC',
checkin: 'DESC',
uptime_seconds: 'DESC',
platform: 'ASC',
environment: 'ASC',
policy_group: 'ASC',
chef_version: 'ASC',
deprecations_count: 'ASC'
};
component.columns = {
check_in: true,
uptime: true,
platform: true,
environment: true,
policy_group: true,
chef_version: false,
deprecations_count: false
};
component.selectedSortField = 'name';
component.selectedFieldDirection = component.defaultFieldDirection['name'];
component.canDeleteNodes = false;
});
describe('DeletableNodeControl', () => {
it('there is no delete column header checkbox', () => {
const sampleNodes = createSampleNodes();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], sampleNodes, true)
};
component.ngOnChanges(changesObj);
expect(component.deletableNodes.length).toEqual(2);
expect(component.nodes.length).toEqual(4);
fixture.detectChanges();
const checkbox = element.query(By.css('.delete-checkbox.header'));
expect(checkbox).toBeNull();
});
it('there is no delete column row checkboxes', () => {
const sampleNodes = createSampleNodes();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], sampleNodes, true)
};
component.ngOnChanges(changesObj);
fixture.detectChanges();
const checkboxes: DebugElement[] =
element.queryAll(By.css('.delete-checkbox.row'));
expect(checkboxes).toEqual([]);
});
it('there is no delete button in the deletable node control', () => {
fixture.detectChanges();
const sampleNodes = createSampleNodes();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], sampleNodes, true)
};
component.ngOnChanges(changesObj);
fixture.detectChanges();
const deletableNodeControl: DebugElement =
element.query(By.css('app-deletable-node-control'));
const deleteButton = deletableNodeControl.query(By.css('.delete-button'));
expect(deleteButton).toBeNull();
});
});
});
describe('user has permissions to delete nodes', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
ChefPipesModule,
StoreModule.forRoot({
}, { runtimeChecks })
],
declarations: [
ClientRunsTableComponent,
DeletableNodeControlComponent,
MockAllowedAuthorizedComponent,
MockComponent({ selector: 'chef-tooltip' }),
MockComponent({ selector: 'chef-checkbox' }),
MockComponent({ selector: 'chef-dropdown' })
],
providers: [
],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
});
fixture = TestBed.createComponent(ClientRunsTableComponent);
component = fixture.componentInstance;
element = fixture.debugElement;
component.defaultFieldDirection = {
name: 'ASC',
checkin: 'DESC',
uptime_seconds: 'DESC',
platform: 'ASC',
environment: 'ASC',
policy_group: 'ASC',
chef_version: 'ASC',
deprecations_count: 'ASC'
};
component.columns = {
check_in: true,
uptime: true,
platform: true,
environment: true,
policy_group: true,
chef_version: false,
deprecations_count: false
};
component.selectedSortField = 'name';
component.selectedFieldDirection = component.defaultFieldDirection['name'];
component.canDeleteNodes = true;
});
describe('DeletableNodeControl', () => {
it('there is a delete button in the deletable node control', () => {
fixture.detectChanges();
const sampleNodes = createSampleNodes();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], sampleNodes, true)
};
component.ngOnChanges(changesObj);
fixture.detectChanges();
const deletableNodeControl: DebugElement =
element.query(By.css('app-deletable-node-control'));
const deleteButton = deletableNodeControl.query(By.css('.delete-button'));
expect(deleteButton).not.toBeNull();
});
it('column header checkbox is indeterminate when' +
' one node is selected and one is not selected', () => {
const sampleNodes = createSampleNodes();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], sampleNodes, true)
};
component.ngOnChanges(changesObj);
expect(component.deletableNodes.length).toEqual(2);
expect(component.nodes.length).toEqual(4);
fixture.detectChanges();
const checkbox = element.query(By.css('.delete-checkbox.row'));
expect(checkbox).not.toBeNull();
checkbox.triggerEventHandler('change', { detail: true });
fixture.detectChanges();
expect(checkbox.nativeElement.checked).toEqual(true);
const headerCheckbox = element.query(By.css('.delete-checkbox.header'));
expect(headerCheckbox).not.toBeNull();
expect(headerCheckbox.nativeElement.indeterminate).toEqual(true);
});
it('column header checkbox is checked when all nodes are selected', () => {
const sampleNodes = createSampleNodes();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], sampleNodes, true)
};
component.ngOnChanges(changesObj);
fixture.detectChanges();
const checkboxes: DebugElement[] =
element.queryAll(By.css('.delete-checkbox.row'));
expect(checkboxes).not.toBeNull();
checkboxes.forEach((checkbox) => checkbox.triggerEventHandler('change', { detail: true }));
fixture.detectChanges();
const headerCheckbox = element.query(By.css('.delete-checkbox.header'));
expect(headerCheckbox).not.toBeNull();
fixture.detectChanges();
expect(headerCheckbox.nativeElement.checked).toEqual(true);
expect(headerCheckbox.nativeElement.indeterminate).toEqual(false);
});
it('column header checkbox is unchecked when no nodes are checked', () => {
fixture.detectChanges();
const sampleNodes = createSampleNodes();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], sampleNodes, true)
};
component.ngOnChanges(changesObj);
fixture.detectChanges();
const headerCheckbox = element.query(By.css('.delete-checkbox.header'));
expect(headerCheckbox).not.toBeNull();
fixture.detectChanges();
expect(headerCheckbox.nativeElement.checked).toEqual(false);
expect(headerCheckbox.nativeElement.indeterminate).toEqual(false);
});
it('column header checkbox is disabled when there are no deletable nodes', () => {
fixture.detectChanges();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], [], true)
};
component.ngOnChanges(changesObj);
fixture.detectChanges();
const headerCheckbox = element.query(By.css('.delete-checkbox.header'));
expect(headerCheckbox).not.toBeNull();
fixture.detectChanges();
expect(headerCheckbox.nativeElement.disabled).toEqual(true);
expect(headerCheckbox.nativeElement.indeterminate).toEqual(false);
});
it('when the column header checkbox is checked all nodes are selected', () => {
const sampleNodes = createSampleNodes();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], sampleNodes, true)
};
component.ngOnChanges(changesObj);
fixture.detectChanges();
const headerCheckbox = element.query(By.css('.delete-checkbox.header'));
expect(headerCheckbox).not.toBeNull();
headerCheckbox.triggerEventHandler('change', { detail: true });
fixture.detectChanges();
expect(headerCheckbox.nativeElement.disabled).toEqual(false);
expect(headerCheckbox.nativeElement.indeterminate).toEqual(false);
expect(headerCheckbox.nativeElement.checked).toEqual(true);
const checkboxes: DebugElement[] =
element.queryAll(By.css('.delete-checkbox.row'));
expect(checkboxes).not.toBeNull();
expect(checkboxes.length).toEqual(2);
checkboxes.forEach((checkbox) => {
expect(checkbox.nativeElement.checked).toEqual(true);
});
// when the column header checkbox is unchecked when all nodes are selected
// then all nodes will be unselected
headerCheckbox.triggerEventHandler('change', { detail: false });
fixture.detectChanges();
checkboxes.forEach((checkbox) => {
expect(checkbox.nativeElement.checked).toEqual(false);
});
});
});
describe('dynamic table columns', () => {
// it('display policy column when all nodes are policy nodes', () => {
// spyOn(MockNodesService.prototype, 'policyNodeCount').and.returnValue(observableOf(20));
// spyOn(MockNodesService.prototype, 'totalNodeCount').and.returnValue(observableOf(20));
// fixture.detectChanges();
// expect(component.displayPolicyNodes).toBe(true);
// });
//
// it('do not display environment column when all nodes are policy nodes', () => {
// spyOn(MockNodeListService.prototype, 'policyNodeCount')
// .and.returnValue(observableOf(20));
// spyOn(MockNodeListService.prototype, 'totalNodeCount').and.returnValue(observableOf(20));
// fixture.detectChanges();
// expect(component.displayEnvironmentNodes).toBe(false);
// });
//
// it('display environment column when all nodes are Environment/Roles nodes', () => {
// spyOn(MockNodeListService.prototype, 'policyNodeCount').and.returnValue(observableOf(0));
// spyOn(MockNodeListService.prototype, 'totalNodeCount').and.returnValue(observableOf(20));
// fixture.detectChanges();
// expect(component.displayEnvironmentNodes).toBe(true);
// });
//
// it('do not display policy column when all nodes are Environment/Roles nodes', () => {
// spyOn(MockNodeListService.prototype, 'policyNodeCount').and.returnValue(observableOf(0));
// spyOn(MockNodeListService.prototype, 'totalNodeCount').and.returnValue(observableOf(20));
// fixture.detectChanges();
// expect(component.displayPolicyNodes).toBe(false);
// });
// tslint:disable-next-line:max-line-length
it('display both policy and environment columns when both Policy File and Environment/Roles nodes are present', () => {
// spyOn(MockNodeListService.prototype, 'policyNodeCount')
// .and.returnValue(observableOf(10));
// spyOn(MockNodeListService.prototype, 'totalNodeCount').and.returnValue(observableOf(20));
fixture.detectChanges();
expect(component.displayPolicyNodes).toBe(true);
expect(component.displayEnvironmentNodes).toBe(true);
});
});
describe('initialization', () => {
it('should render a table', () => {
fixture.detectChanges();
expect(
element.nativeElement.querySelector('chef-table > chef-thead')).not.toBe(null);
expect(
element.nativeElement.querySelector('chef-table > chef-tbody')).not.toBe(null);
});
});
describe('when the node-list service returns', () => {
it('should render a row for each node', () => {
const sampleNodes = createSampleNodes();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], sampleNodes, true)
};
component.ngOnChanges(changesObj);
fixture.detectChanges();
expect(element.nativeElement
.querySelectorAll('chef-table > chef-tbody > chef-tr').length).toBe(4);
});
});
describe('clicking the Node Name heading', () => {
it('should toggle the list sort', () => {
const th = element.nativeElement.querySelector('chef-th:nth-child(1)');
fixture.detectChanges();
expect(component.defaultFieldDirection['name']).toBe('ASC');
expect(component.sortIcon('name')).toBe('sort-asc');
expect(component.sortIcon('environment')).toBe('sort');
spyOn(component.updateSort, 'emit');
fixture.detectChanges();
th.click();
expect(component.updateSort.emit).toHaveBeenCalledWith(
{field: 'name', fieldDirection: 'DESC'});
});
});
describe('clicking the Check-in heading', () => {
it('should emit the list sort for Check-in in descending order', () => {
const th = element.nativeElement.querySelector('chef-th:nth-child(2)');
fixture.detectChanges();
expect(component.defaultFieldDirection['name']).toBe('ASC');
expect(component.defaultFieldDirection['checkin']).toBe('DESC');
expect(component.selectedSortField).toBe('name');
spyOn(component.updateSort, 'emit');
fixture.detectChanges();
th.click();
expect(component.updateSort.emit).toHaveBeenCalledWith(
{field: 'checkin', fieldDirection: 'DESC'});
});
});
describe('nodes with no data', () => {
it('should not have links', () => {
const sampleNodes = createSampleNodes();
const changesObj: SimpleChanges = {
nodes: new SimpleChange([], sampleNodes, true)
};
component.ngOnChanges(changesObj);
fixture.detectChanges();
// There are four nodes 8 links per node. The example as on node that
// has data and the other that does not have data. Therefore there should only be 9 anchors
expect(element.nativeElement.querySelectorAll('chef-td > a').length).toBe(9);
});
});
});
}); | the_stack |
import { BasicClient, MarketMap, SendFn } from "../BasicClient";
import { Level2Point } from "../Level2Point";
import { Level2Snapshot } from "../Level2Snapshots";
import { Level2Update } from "../Level2Update";
import { Level3Point } from "../Level3Point";
import { Level3Snapshot } from "../Level3Snapshot";
import { Level3Update } from "../Level3Update";
import { Market } from "../Market";
import { NotImplementedAsyncFn, NotImplementedFn } from "../NotImplementedFn";
import { Ticker } from "../Ticker";
import { Trade } from "../Trade";
export enum BitfinexTradeMessageType {
/**
* Receive both execution events and updates
*/
All = "all",
/**
* Receive trade events immediately at the time of execution. Events
* do not include the database identifier, only the sequence identifier.
*/
Execution = "te",
/**
* Receive trade events that have been written to the database. These
* events include both the sequence identifier as well as the database
* identifier. These events are delayed by 1-2 seconds after the
* trade event.
*/
Update = "tu",
}
export type BitfinexClientOptions = {
wssPath?: string;
watcherMs?: number;
l2UpdateDepth?: number;
throttleL2Snapshot?: number;
/**
* (optional, default false). If true, emits empty events for all
* channels on heartbeat events which includes the sequenceId. This
* allows sequenceId validation by always receiving sequenceId from
* all heartbeat events on all channels while working w/the
* existing trade/ticker/orderbook event types
*/
enableEmptyHeartbeatEvents?: boolean;
/**
* (optional, defaults to "tu"). One of "tu", "te", or "all".
* Determines whether to use trade channel events of type "te" or
* "tu", or all trade events.
* See https://blog.bitfinex.com/api/websocket-api-update/.
*
* If you're using sequenceIds to validate websocket messages you
* will want to use "all" to receive every sequenceId.
*/
tradeMessageType?: BitfinexTradeMessageType;
};
export class BitfinexClient extends BasicClient {
public l2UpdateDepth: number;
public enableEmptyHeartbeatEvents: boolean;
public tradeMessageType: BitfinexTradeMessageType;
protected _channels: any;
protected _sendSubCandles = NotImplementedFn;
protected _sendSubLevel2Snapshots = NotImplementedFn;
protected _sendSubLevel3Snapshots = NotImplementedFn;
protected _sendUnsubCandles = NotImplementedAsyncFn;
protected _sendUnsubLevel2Snapshots = NotImplementedAsyncFn;
protected _sendUnsubLevel3Snapshots = NotImplementedAsyncFn;
constructor({
wssPath = "wss://api.bitfinex.com/ws/2",
watcherMs,
l2UpdateDepth = 250,
enableEmptyHeartbeatEvents = false,
tradeMessageType = BitfinexTradeMessageType.Update,
}: BitfinexClientOptions = {}) {
super(wssPath, "Bitfinex", undefined, watcherMs);
this._channels = {};
this.hasTickers = true;
this.hasTrades = true;
this.hasLevel2Updates = true;
this.hasLevel3Updates = true;
this.l2UpdateDepth = l2UpdateDepth;
this.enableEmptyHeartbeatEvents = enableEmptyHeartbeatEvents;
this.tradeMessageType = tradeMessageType;
}
protected _onConnected() {
// immediately send the config event to include sequence IDs in every message
this._sendConfiguration();
super._onConnected();
}
/**
* Override the default BasicClient _unsubscribe by deferring removal
* of from the appropriate map until the unsubscribe event has been
* received.
*
* If enableEmptyHeartbeatEvents (validating sequenceIds) we need to
* keep receiving events from a channel after we sent the unsub event
* until unsubscribe is confirmed. This is because every message's
* sequenceId must be validated, and some may arrive between sending
* unsub and it being confirmed. So we dont remove from the map and
* will continue emitting events for this channel until they stop
* arriving.
*/
protected _unsubscribe(market: Market, map: MarketMap, sendFn: SendFn) {
const remote_id = market.id;
if (map.has(remote_id)) {
if (this._wss.isConnected) {
sendFn(remote_id, market);
}
}
}
protected _sendConfiguration() {
// see docs for "conf" flags. https://docs.bitfinex.com/docs/ws-general#configuration
// combine multiple flags by summing their values
// 65536 adds a sequence ID to each message
// 32768 adds a Timestamp in milliseconds to each received event
// 131072 Enable checksum for every book iteration. Checks the top 25 entries for each side of book. Checksum is a signed int. more info https://docs.bitfinex.com/docs/ws-websocket-checksum. it's sent in its own
// separate event so we've disabled it
this._wss.send(JSON.stringify({ event: "conf", flags: 65536 + 32768 }));
}
protected _sendSubTicker(remote_id: string) {
this._wss.send(
JSON.stringify({
event: "subscribe",
channel: "ticker",
pair: remote_id,
}),
);
}
protected _sendUnsubTicker(remote_id: string) {
this._sendUnsubscribe(remote_id);
}
protected _sendSubTrades(remote_id: string) {
this._wss.send(
JSON.stringify({
event: "subscribe",
channel: "trades",
pair: remote_id,
}),
);
}
protected _sendUnsubTrades(remote_id: string) {
const chanId = this._findChannel("trades", remote_id);
this._sendUnsubscribe(chanId);
}
protected _sendSubLevel2Updates(remote_id: string) {
this._wss.send(
JSON.stringify({
event: "subscribe",
channel: "book",
pair: remote_id,
len: String(this.l2UpdateDepth), // len must be of type string, even though it's a number
}),
);
}
protected _sendUnsubLevel2Updates(remote_id: string) {
const chanId = this._findChannel("level2updates", remote_id);
this._sendUnsubscribe(chanId);
}
protected _sendSubLevel3Updates(remote_id: string) {
this._wss.send(
JSON.stringify({
event: "subscribe",
channel: "book",
pair: remote_id,
prec: "R0",
length: "100",
}),
);
}
protected _sendUnsubLevel3Updates(remote_id: string) {
const chanId = this._findChannel("level3updates", remote_id);
this._sendUnsubscribe(chanId);
}
protected _sendUnsubscribe(chanId) {
if (chanId) {
this._wss.send(
JSON.stringify({
event: "unsubscribe",
chanId: chanId,
}),
);
}
}
protected _findChannel(type: string, remote_id: string): string {
for (const raw of Object.values(this._channels)) {
const chan = raw as any;
if (chan.pair === remote_id) {
if (type === "trades" && chan.channel === "trades") return chan.chanId;
if (type === "level2updates" && chan.channel === "book" && chan.prec !== "R0")
return chan.chanId;
if (type === "level3updates" && chan.channel === "book" && chan.prec === "R0")
return chan.chanId;
}
}
}
/**
* Handle heartbeat messages on each channel.
*/
protected _onHeartbeatMessage(msg: any, channel: any) {
if (channel.channel === "ticker") {
let market = this._tickerSubs.get(channel.pair);
if (!market) return;
this._onTickerHeartbeat(msg, market);
return;
}
// trades
if (channel.channel === "trades") {
let market = this._tradeSubs.get(channel.pair);
if (!market) return;
this._onTradeMessageHeartbeat(msg, market);
return;
}
// level3
if (channel.channel === "book" && channel.prec === "R0") {
let market = this._level3UpdateSubs.get(channel.pair);
if (!market) return;
this._onLevel3UpdateHeartbeat(msg, market);
return;
}
// level2
if (channel.channel === "book") {
let market = this._level2UpdateSubs.get(channel.pair);
if (!market) return;
this._onLevel2UpdateHeartbeat(msg, market);
return;
}
}
protected _onMessage(raw: string) {
const msg = JSON.parse(raw);
// capture channel metadata
if (msg.event === "subscribed") {
this._channels[msg.chanId] = msg;
return;
}
// process unsubscribe event
if (msg.event === "unsubscribed") {
this._onUnsubscribeMessage(msg);
return;
}
// lookup channel
const channel = this._channels[msg[0]];
if (!channel) return;
// handle heartbeats
if (msg[1] === "hb") {
this._onHeartbeatMessage(msg, channel);
return;
}
if (channel.channel === "ticker") {
const market = this._tickerSubs.get(channel.pair);
if (!market) return;
this._onTicker(msg, market);
return;
}
// trades
if (channel.channel === "trades") {
const market = this._tradeSubs.get(channel.pair);
if (!market) return;
// handle tradeMessageType (constructor param) filtering
// example trade update msg: [ 359491, 'tu' or 'te', [ 560287312, 1609712228656, 0.005, 33432 ], 6 ]
// note: "tu" means it's got the tradeId, this is delayed by 1-2 seconds and includes tradeId.
// "te" is the same but available immediately and without the tradeId
const tradeEventType = msg[1];
if (
this.tradeMessageType === BitfinexTradeMessageType.All ||
tradeEventType === this.tradeMessageType
) {
this._onTradeMessage(msg, market);
}
return;
}
// level3
if (channel.channel === "book" && channel.prec === "R0") {
const market = this._level3UpdateSubs.get(channel.pair);
if (!market) return;
if (Array.isArray(msg[1][0])) this._onLevel3Snapshot(msg, market);
else this._onLevel3Update(msg, market);
return;
}
// level2
if (channel.channel === "book") {
const market = this._level2UpdateSubs.get(channel.pair);
if (!market) return;
if (Array.isArray(msg[1][0])) this._onLevel2Snapshot(msg, market);
else this._onLevel2Update(msg, market);
return;
}
}
protected _onUnsubscribeMessage(msg: any) {
const chanId = msg.chanId;
const channel = this._channels[chanId];
if (!channel) return;
const marketId = channel.pair;
// remove channel metadata
delete this._channels[chanId];
// remove from appropriate subscription map
if (channel.channel === "ticker") {
this._tickerSubs.delete(marketId);
} else if (channel.channel === "trades") {
this._tradeSubs.delete(marketId);
} else if (channel.channel === "book" && channel.prec === "R0") {
this._level3UpdateSubs.delete(marketId);
} else if (channel.channel === "book") {
this._level2UpdateSubs.delete(marketId);
}
}
/**
* Handle heartbeat events in the ticker channel.
*/
protected _onTickerHeartbeat(msg: any, market: Market) {
const sequenceId = Number(msg[2]);
const timestampMs = msg[3];
if (this.enableEmptyHeartbeatEvents === false) return;
// handle heartbeat by emitting empty update w/sequenceId.
// heartbeat msg: [ 198655, 'hb', 3, 1610920929093 ]
let ticker = new Ticker({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
timestamp: timestampMs,
sequenceId,
});
this.emit("ticker", ticker, market);
return;
}
protected _onTicker(msg: any, market: Market) {
const msgBody = msg[1];
const sequenceId = Number(msg[2]);
const [bid, bidSize, ask, askSize, change, changePercent, last, volume, high, low] =
msgBody;
const open = last + change;
const ticker = new Ticker({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
timestamp: Date.now(),
sequenceId,
last: last.toFixed(8),
open: open.toFixed(8),
high: high.toFixed(8),
low: low.toFixed(8),
volume: volume.toFixed(8),
change: change.toFixed(8),
changePercent: changePercent.toFixed(2),
bid: bid.toFixed(8),
bidVolume: bidSize.toFixed(8),
ask: ask.toFixed(8),
askVolume: askSize.toFixed(8),
});
this.emit("ticker", ticker, market);
}
/**
* Handle heartbeat events in the trades channel.
*/
protected _onTradeMessageHeartbeat(msg: any, market: Market) {
const timestampMs = msg[3];
const sequenceId = Number(msg[2]);
if (this.enableEmptyHeartbeatEvents === false) return;
// handle heartbeat by emitting empty update w/sequenceId.
// example trade heartbeat msg: [ 198655, 'hb', 3, 1610920929093 ]
let trade = new Trade({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
timestamp: timestampMs,
sequenceId,
});
this.emit("trade", trade, market);
return;
}
/**
* Handle the trade history payload received when initially subscribing, which includes recent trades history.
* Each trade in history is emitted as its own trade event.
*/
protected _onTradeHistoryMessage(msg: any, market: Market) {
// handle the initial trades snapshot
// trade snapshot example msg:
/*
[
CHANNEL_ID,
[
[
ID,
MTS,
AMOUNT,
PRICE
],
...
],
sequenceId,
timestampMs
]
*/
const sequenceId = Number(msg[2]);
for (const thisTrade of msg[1]) {
let [id, unix, amount, price] = thisTrade;
let side = amount > 0 ? "buy" : "sell";
price = price.toFixed(8);
amount = Math.abs(amount).toFixed(8);
let trade = new Trade({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
tradeId: id.toFixed(),
sequenceId,
unix: unix,
side,
price,
amount,
});
this.emit("trade", trade, market);
}
}
protected _onTradeMessage(msg: any, market: Market) {
const isTradeHistory = Array.isArray(msg[1]);
if (isTradeHistory) {
this._onTradeHistoryMessage(msg, market);
return;
}
// example msg: [ 359491, 'tu', [ 560287312, 1609712228656, 0.005, 33432 ], 6 ]
let [id, unix, amount, price] = msg[2];
const sequenceId = Number(msg[3]);
const side = amount > 0 ? "buy" : "sell";
price = price.toFixed(8);
amount = Math.abs(amount).toFixed(8);
const trade = new Trade({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
tradeId: id.toFixed(),
sequenceId,
unix: unix,
side,
price,
amount,
});
this.emit("trade", trade, market);
}
protected _onLevel2Snapshot(msg: any, market: Market) {
/*
example msg:
[
646750,
[
[ 31115, 1, 1 ],
[ 31114, 1, 0.31589592 ],
...
],
1,
1609794291015
]
*/
const bids = [];
const asks = [];
const sequenceId = Number(msg[2]);
const timestampMs = msg[3];
for (const [price, count, size] of msg[1]) {
const isBid = size > 0;
const result = new Level2Point(
price.toFixed(8),
Math.abs(size).toFixed(8),
count.toFixed(0),
);
if (isBid) bids.push(result);
else asks.push(result);
}
const result = new Level2Snapshot({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
sequenceId,
timestampMs,
bids,
asks,
});
this.emit("l2snapshot", result, market);
}
/**
* Handle heartbeat events in the l2updatae channel
*/
protected _onLevel2UpdateHeartbeat(msg: any, market: Market) {
const sequenceId = Number(msg[2]);
const timestampMs = msg[3];
if (this.enableEmptyHeartbeatEvents === false) return;
// handle heartbeat by emitting empty update w/sequenceId.
// heartbeat msg: [ 169546, 'hb', 17, 1610921150321 ]
let update = new Level2Update({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
sequenceId,
timestampMs,
asks: [],
bids: [],
});
this.emit("l2update", update, market);
return;
}
protected _onLevel2Update(msg, market) {
// example msg: [ 646750, [ 30927, 5, 0.0908 ], 19, 1609794565952 ]
const [price, count, size] = msg[1];
const sequenceId = Number(msg[2]);
const timestampMs = msg[3];
if (!price.toFixed) return;
const point = new Level2Point(
price.toFixed(8),
Math.abs(size).toFixed(8),
count.toFixed(0),
);
const asks = [];
const bids = [];
const isBid = size > 0;
if (isBid) bids.push(point);
else asks.push(point);
const isDelete = count === 0;
if (isDelete) (point as any).size = (0).toFixed(8); // reset the size to 0, comes in as 1 or -1 to indicate bid/ask
const update = new Level2Update({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
sequenceId,
timestampMs,
asks,
bids,
});
this.emit("l2update", update, market);
}
protected _onLevel3Snapshot(msg, market) {
/*
example msg:
[
648087,
[
[ 55888179267, 31111, 0.05 ],
[ 55895806791, 31111, 0.989 ],
...
],
1,
1609794565952
]
*/
const bids = [];
const asks = [];
const orders = msg[1];
const sequenceId = Number(msg[2]);
const timestampMs = msg[3];
for (const [orderId, price, size] of orders) {
const point = new Level3Point(
orderId.toFixed(),
price.toFixed(8),
Math.abs(size).toFixed(8),
);
if (size > 0) bids.push(point);
else asks.push(point);
}
const result = new Level3Snapshot({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
sequenceId,
timestampMs,
asks,
bids,
});
this.emit("l3snapshot", result, market);
}
/**
* Handle heartbeat events in the l3updatae channel
*/
protected _onLevel3UpdateHeartbeat(msg: any, market: Market) {
const sequenceId = Number(msg[2]);
const timestampMs = msg[3];
if (this.enableEmptyHeartbeatEvents === false) return;
// handle heartbeat by emitting empty update w/sequenceId.
// heartbeat msg: [ 169546, 'hb', 17, 1610921150321 ]
let result = new Level3Update({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
sequenceId,
timestampMs,
asks: [],
bids: [],
});
this.emit("l3update", result, market);
}
protected _onLevel3Update(msg, market) {
// example msg: [ 648087, [ 55895794256, 31107, 0.07799627 ], 4, 1609794565952 ]
const bids = [];
const asks = [];
const [orderId, price, size] = msg[1];
const sequenceId = Number(msg[2]);
const timestampMs = msg[3];
const point = new Level3Point(
orderId.toFixed(),
price.toFixed(8),
Math.abs(size).toFixed(8),
);
if (size > 0) bids.push(point);
else asks.push(point);
const result = new Level3Update({
exchange: "Bitfinex",
base: market.base,
quote: market.quote,
sequenceId,
timestampMs,
asks,
bids,
});
this.emit("l3update", result, market);
}
} | the_stack |
import { AspidaClient, BasicHeaders, dataToURLString } from 'aspida'
// prettier-ignore
import { Methods as Methods0 } from './auth/_provider@string/callback'
// prettier-ignore
import { Methods as Methods1 } from './auth/email-confirmation'
// prettier-ignore
import { Methods as Methods2 } from './auth/forgot-password'
// prettier-ignore
import { Methods as Methods3 } from './auth/local'
// prettier-ignore
import { Methods as Methods4 } from './auth/local/register'
// prettier-ignore
import { Methods as Methods5 } from './auth/reset-password'
// prettier-ignore
import { Methods as Methods6 } from './auth/send-email-confirmation'
// prettier-ignore
import { Methods as Methods7 } from './connect/_any'
// prettier-ignore
import { Methods as Methods8 } from './email'
// prettier-ignore
import { Methods as Methods9 } from './upload'
// prettier-ignore
import { Methods as Methods10 } from './upload/files'
// prettier-ignore
import { Methods as Methods11 } from './upload/files/_id@string'
// prettier-ignore
import { Methods as Methods12 } from './upload/files/count'
// prettier-ignore
import { Methods as Methods13 } from './upload/search/_id@string'
// prettier-ignore
import { Methods as Methods14 } from './users'
// prettier-ignore
import { Methods as Methods15 } from './users/_id@string'
// prettier-ignore
import { Methods as Methods16 } from './users/me'
// prettier-ignore
import { Methods as Methods17 } from './users-permissions/init'
// prettier-ignore
import { Methods as Methods18 } from './users-permissions/roles'
// prettier-ignore
import { Methods as Methods19 } from './users-permissions/roles/_id@string'
// prettier-ignore
import { Methods as Methods20 } from './users-permissions/roles/_role@string'
// prettier-ignore
import { Methods as Methods21 } from './users-permissions/search/_id@string'
// prettier-ignore
const api = <T>({ baseURL, fetch }: AspidaClient<T>) => {
const prefix = (baseURL === undefined ? 'http://localhost:1337' : baseURL).replace(/\/$/, '')
const PATH0 = '/auth'
const PATH1 = '/callback'
const PATH2 = '/auth/email-confirmation'
const PATH3 = '/auth/forgot-password'
const PATH4 = '/auth/local'
const PATH5 = '/auth/local/register'
const PATH6 = '/auth/reset-password'
const PATH7 = '/auth/send-email-confirmation'
const PATH8 = '/connect'
const PATH9 = '/email'
const PATH10 = '/upload'
const PATH11 = '/upload/files'
const PATH12 = '/upload/files/count'
const PATH13 = '/upload/search'
const PATH14 = '/users'
const PATH15 = '/users/me'
const PATH16 = '/users-permissions/init'
const PATH17 = '/users-permissions/roles'
const PATH18 = '/users-permissions/search'
const GET = 'GET'
const POST = 'POST'
const PUT = 'PUT'
const DELETE = 'DELETE'
return {
auth: {
_provider: (val1: string) => {
const prefix1 = `${PATH0}/${val1}`
return {
callback: {
/**
* Successfull redirection after approving a provider
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods0['get']['resBody'], BasicHeaders, Methods0['get']['status']>(prefix, `${prefix1}${PATH1}`, GET, option).json(),
/**
* Successfull redirection after approving a provider
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods0['get']['resBody'], BasicHeaders, Methods0['get']['status']>(prefix, `${prefix1}${PATH1}`, GET, option).json().then(r => r.body),
$path: () => `${prefix}${prefix1}${PATH1}`
}
}
},
email_confirmation: {
/**
* Validate a user account
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods1['get']['resBody'], BasicHeaders, Methods1['get']['status']>(prefix, PATH2, GET, option).json(),
/**
* Validate a user account
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods1['get']['resBody'], BasicHeaders, Methods1['get']['status']>(prefix, PATH2, GET, option).json().then(r => r.body),
$path: () => `${prefix}${PATH2}`
},
forgot_password: {
/**
* Send the reset password email link
* @returns response
*/
post: (option: { body: Methods2['post']['reqBody'], config?: T }) =>
fetch<Methods2['post']['resBody'], BasicHeaders, Methods2['post']['status']>(prefix, PATH3, POST, option).json(),
/**
* Send the reset password email link
* @returns response
*/
$post: (option: { body: Methods2['post']['reqBody'], config?: T }) =>
fetch<Methods2['post']['resBody'], BasicHeaders, Methods2['post']['status']>(prefix, PATH3, POST, option).json().then(r => r.body),
$path: () => `${prefix}${PATH3}`
},
local: {
register: {
/**
* Register a new user with the default role
* @returns response
*/
post: (option: { body: Methods4['post']['reqBody'], config?: T }) =>
fetch<Methods4['post']['resBody'], BasicHeaders, Methods4['post']['status']>(prefix, PATH5, POST, option).json(),
/**
* Register a new user with the default role
* @returns response
*/
$post: (option: { body: Methods4['post']['reqBody'], config?: T }) =>
fetch<Methods4['post']['resBody'], BasicHeaders, Methods4['post']['status']>(prefix, PATH5, POST, option).json().then(r => r.body),
$path: () => `${prefix}${PATH5}`
},
/**
* Login a user using the identifiers email and password
* @returns response
*/
post: (option: { body: Methods3['post']['reqBody'], config?: T }) =>
fetch<Methods3['post']['resBody'], BasicHeaders, Methods3['post']['status']>(prefix, PATH4, POST, option).json(),
/**
* Login a user using the identifiers email and password
* @returns response
*/
$post: (option: { body: Methods3['post']['reqBody'], config?: T }) =>
fetch<Methods3['post']['resBody'], BasicHeaders, Methods3['post']['status']>(prefix, PATH4, POST, option).json().then(r => r.body),
$path: () => `${prefix}${PATH4}`
},
reset_password: {
/**
* Change a user's password
* @returns response
*/
post: (option: { body: Methods5['post']['reqBody'], config?: T }) =>
fetch<Methods5['post']['resBody'], BasicHeaders, Methods5['post']['status']>(prefix, PATH6, POST, option).json(),
/**
* Change a user's password
* @returns response
*/
$post: (option: { body: Methods5['post']['reqBody'], config?: T }) =>
fetch<Methods5['post']['resBody'], BasicHeaders, Methods5['post']['status']>(prefix, PATH6, POST, option).json().then(r => r.body),
$path: () => `${prefix}${PATH6}`
},
send_email_confirmation: {
/**
* Send a confirmation email to user
* @returns response
*/
post: (option: { body: Methods6['post']['reqBody'], config?: T }) =>
fetch<Methods6['post']['resBody'], BasicHeaders, Methods6['post']['status']>(prefix, PATH7, POST, option).json(),
/**
* Send a confirmation email to user
* @returns response
*/
$post: (option: { body: Methods6['post']['reqBody'], config?: T }) =>
fetch<Methods6['post']['resBody'], BasicHeaders, Methods6['post']['status']>(prefix, PATH7, POST, option).json().then(r => r.body),
$path: () => `${prefix}${PATH7}`
}
},
connect: {
_any: (val1: number | string) => {
const prefix1 = `${PATH8}/${val1}`
return {
/**
* Connect a provider
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods7['get']['resBody'], BasicHeaders, Methods7['get']['status']>(prefix, prefix1, GET, option).json(),
/**
* Connect a provider
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods7['get']['resBody'], BasicHeaders, Methods7['get']['status']>(prefix, prefix1, GET, option).json().then(r => r.body),
$path: () => `${prefix}${prefix1}`
}
}
},
email: {
/**
* Send an email
* @returns response
*/
post: (option: { body: Methods8['post']['reqBody'], config?: T }) =>
fetch<Methods8['post']['resBody'], BasicHeaders, Methods8['post']['status']>(prefix, PATH9, POST, option).json(),
/**
* Send an email
* @returns response
*/
$post: (option: { body: Methods8['post']['reqBody'], config?: T }) =>
fetch<Methods8['post']['resBody'], BasicHeaders, Methods8['post']['status']>(prefix, PATH9, POST, option).json().then(r => r.body),
$path: () => `${prefix}${PATH9}`
},
upload: {
files: {
_id: (val2: string) => {
const prefix2 = `${PATH11}/${val2}`
return {
/**
* Retrieve a single file depending on its id
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods11['get']['resBody'], BasicHeaders, Methods11['get']['status']>(prefix, prefix2, GET, option).json(),
/**
* Retrieve a single file depending on its id
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods11['get']['resBody'], BasicHeaders, Methods11['get']['status']>(prefix, prefix2, GET, option).json().then(r => r.body),
/**
* Delete an uploaded file
* @returns response
*/
delete: (option?: { config?: T }) =>
fetch<Methods11['delete']['resBody'], BasicHeaders, Methods11['delete']['status']>(prefix, prefix2, DELETE, option).json(),
/**
* Delete an uploaded file
* @returns response
*/
$delete: (option?: { config?: T }) =>
fetch<Methods11['delete']['resBody'], BasicHeaders, Methods11['delete']['status']>(prefix, prefix2, DELETE, option).json().then(r => r.body),
$path: () => `${prefix}${prefix2}`
}
},
count: {
/**
* Retrieve the total number of uploaded files
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods12['get']['resBody'], BasicHeaders, Methods12['get']['status']>(prefix, PATH12, GET, option).json(),
/**
* Retrieve the total number of uploaded files
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods12['get']['resBody'], BasicHeaders, Methods12['get']['status']>(prefix, PATH12, GET, option).json().then(r => r.body),
$path: () => `${prefix}${PATH12}`
},
/**
* Retrieve all file documents
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods10['get']['resBody'], BasicHeaders, Methods10['get']['status']>(prefix, PATH11, GET, option).json(),
/**
* Retrieve all file documents
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods10['get']['resBody'], BasicHeaders, Methods10['get']['status']>(prefix, PATH11, GET, option).json().then(r => r.body),
$path: () => `${prefix}${PATH11}`
},
search: {
_id: (val2: string) => {
const prefix2 = `${PATH13}/${val2}`
return {
/**
* Search for an uploaded file
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods13['get']['resBody'], BasicHeaders, Methods13['get']['status']>(prefix, prefix2, GET, option).json(),
/**
* Search for an uploaded file
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods13['get']['resBody'], BasicHeaders, Methods13['get']['status']>(prefix, prefix2, GET, option).json().then(r => r.body),
$path: () => `${prefix}${prefix2}`
}
}
},
/**
* Upload a file
* @returns response
*/
post: (option: { body: Methods9['post']['reqBody'], config?: T }) =>
fetch<Methods9['post']['resBody'], BasicHeaders, Methods9['post']['status']>(prefix, PATH10, POST, option).json(),
/**
* Upload a file
* @returns response
*/
$post: (option: { body: Methods9['post']['reqBody'], config?: T }) =>
fetch<Methods9['post']['resBody'], BasicHeaders, Methods9['post']['status']>(prefix, PATH10, POST, option).json().then(r => r.body),
$path: () => `${prefix}${PATH10}`
},
users: {
_id: (val1: string) => {
const prefix1 = `${PATH14}/${val1}`
return {
/**
* Retrieve a single user depending on his id
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods15['get']['resBody'], BasicHeaders, Methods15['get']['status']>(prefix, prefix1, GET, option).json(),
/**
* Retrieve a single user depending on his id
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods15['get']['resBody'], BasicHeaders, Methods15['get']['status']>(prefix, prefix1, GET, option).json().then(r => r.body),
/**
* Update an existing user
* @returns response
*/
put: (option: { body: Methods15['put']['reqBody'], config?: T }) =>
fetch<Methods15['put']['resBody'], BasicHeaders, Methods15['put']['status']>(prefix, prefix1, PUT, option).json(),
/**
* Update an existing user
* @returns response
*/
$put: (option: { body: Methods15['put']['reqBody'], config?: T }) =>
fetch<Methods15['put']['resBody'], BasicHeaders, Methods15['put']['status']>(prefix, prefix1, PUT, option).json().then(r => r.body),
/**
* Delete an existing user
* @returns response
*/
delete: (option?: { config?: T }) =>
fetch<Methods15['delete']['resBody'], BasicHeaders, Methods15['delete']['status']>(prefix, prefix1, DELETE, option).json(),
/**
* Delete an existing user
* @returns response
*/
$delete: (option?: { config?: T }) =>
fetch<Methods15['delete']['resBody'], BasicHeaders, Methods15['delete']['status']>(prefix, prefix1, DELETE, option).json().then(r => r.body),
$path: () => `${prefix}${prefix1}`
}
},
me: {
/**
* Retrieve the logged in user information
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods16['get']['resBody'], BasicHeaders, Methods16['get']['status']>(prefix, PATH15, GET, option).json(),
/**
* Retrieve the logged in user information
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods16['get']['resBody'], BasicHeaders, Methods16['get']['status']>(prefix, PATH15, GET, option).json().then(r => r.body),
$path: () => `${prefix}${PATH15}`
},
/**
* Retrieve all user documents
*/
get: (option?: { query?: Methods14['get']['query'], config?: T }) =>
fetch(prefix, PATH14, GET, option).send(),
/**
* Retrieve all user documents
*/
$get: (option?: { query?: Methods14['get']['query'], config?: T }) =>
fetch(prefix, PATH14, GET, option).send().then(r => r.body),
$path: (option?: { method?: 'get'; query: Methods14['get']['query'] }) =>
`${prefix}${PATH14}${option && option.query ? `?${dataToURLString(option.query)}` : ''}`
},
users_permissions: {
init: {
/**
* Check if the first admin user has already been registered
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods17['get']['resBody'], BasicHeaders, Methods17['get']['status']>(prefix, PATH16, GET, option).json(),
/**
* Check if the first admin user has already been registered
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods17['get']['resBody'], BasicHeaders, Methods17['get']['status']>(prefix, PATH16, GET, option).json().then(r => r.body),
$path: () => `${prefix}${PATH16}`
},
roles: {
_id: (val2: string) => {
const prefix2 = `${PATH17}/${val2}`
return {
/**
* Retrieve a role depending on its id
* @returns response
*/
get: (option?: { config?: T }) =>
fetch<Methods19['get']['resBody'], BasicHeaders, Methods19['get']['status']>(prefix, prefix2, GET, option).json(),
/**
* Retrieve a role depending on its id
* @returns response
*/
$get: (option?: { config?: T }) =>
fetch<Methods19['get']['resBody'], BasicHeaders, Methods19['get']['status']>(prefix, prefix2, GET, option).json().then(r => r.body),
$path: () => `${prefix}${prefix2}`
}
},
_role: (val2: string) => {
const prefix2 = `${PATH17}/${val2}`
return {
/**
* Update a role
* @returns response
*/
put: (option: { body: Methods20['put']['reqBody'], config?: T }) =>
fetch<Methods20['put']['resBody'], BasicHeaders, Methods20['put']['status']>(prefix, prefix2, PUT, option).json(),
/**
* Update a role
* @returns response
*/
$put: (option: { body: Methods20['put']['reqBody'], config?: T }) =>
fetch<Methods20['put']['resBody'], BasicHeaders, Methods20['put']['status']>(prefix, prefix2, PUT, option).json().then(r => r.body),
/**
* Delete a role
* @returns response
*/
delete: (option?: { config?: T }) =>
fetch<Methods20['delete']['resBody'], BasicHeaders, Methods20['delete']['status']>(prefix, prefix2, DELETE, option).json(),
/**
* Delete a role
* @returns response
*/
$delete: (option?: { config?: T }) =>
fetch<Methods20['delete']['resBody'], BasicHeaders, Methods20['delete']['status']>(prefix, prefix2, DELETE, option).json().then(r => r.body),
$path: () => `${prefix}${prefix2}`
}
},
/**
* Retrieve all role documents
*/
get: (option?: { query?: Methods18['get']['query'], config?: T }) =>
fetch(prefix, PATH17, GET, option).send(),
/**
* Retrieve all role documents
*/
$get: (option?: { query?: Methods18['get']['query'], config?: T }) =>
fetch(prefix, PATH17, GET, option).send().then(r => r.body),
$path: (option?: { method?: 'get'; query: Methods18['get']['query'] }) =>
`${prefix}${PATH17}${option && option.query ? `?${dataToURLString(option.query)}` : ''}`
},
search: {
_id: (val2: string) => {
const prefix2 = `${PATH18}/${val2}`
return {
/**
* Search for users
*/
get: (option?: { query?: Methods21['get']['query'], config?: T }) =>
fetch(prefix, prefix2, GET, option).send(),
/**
* Search for users
*/
$get: (option?: { query?: Methods21['get']['query'], config?: T }) =>
fetch(prefix, prefix2, GET, option).send().then(r => r.body),
$path: (option?: { method?: 'get'; query: Methods21['get']['query'] }) =>
`${prefix}${prefix2}${option && option.query ? `?${dataToURLString(option.query)}` : ''}`
}
}
}
}
}
}
// prettier-ignore
export type ApiInstance = ReturnType<typeof api>
// prettier-ignore
export default api | the_stack |
/// <reference path="exponentHelper.d.ts" />
import * as path from "path";
import * as semver from "semver";
import * as vscode from "vscode";
import * as XDL from "./xdlInterface";
import { Package, IPackageInformation } from "../../common/node/package";
import { ProjectVersionHelper } from "../../common/projectVersionHelper";
import { OutputChannelLogger } from "../log/OutputChannelLogger";
import stripJSONComments = require("strip-json-comments");
import * as nls from "vscode-nls";
import { ErrorHelper } from "../../common/error/errorHelper";
import { getNodeModulesGlobalPath } from "../../common/utils";
import { PackageLoader, PackageConfig } from "../../common/packageLoader";
import { InternalErrorCode } from "../../common/error/internalErrorCode";
import { FileSystem } from "../../common/node/fileSystem";
import { SettingsHelper } from "../settingsHelper";
nls.config({
messageFormat: nls.MessageFormat.bundle,
bundleFormat: nls.BundleFormat.standalone,
})();
const localize = nls.loadMessageBundle();
const APP_JSON = "app.json";
const EXP_JSON = "exp.json";
const EXPONENT_INDEX = "exponentIndex.js";
const DEFAULT_EXPONENT_INDEX = "index.js";
const DEFAULT_IOS_INDEX = "index.ios.js";
const DEFAULT_ANDROID_INDEX = "index.android.js";
const DBL_SLASHES = /\\/g;
const NGROK_PACKAGE = "@expo/ngrok";
export class ExponentHelper {
private workspaceRootPath: string;
private projectRootPath: string;
private fs: FileSystem;
private hasInitialized: boolean;
private nodeModulesGlobalPathAddedToEnv: boolean;
private logger: OutputChannelLogger = OutputChannelLogger.getMainChannel();
public constructor(
workspaceRootPath: string,
projectRootPath: string,
fs: FileSystem = new FileSystem(),
) {
this.workspaceRootPath = workspaceRootPath;
this.projectRootPath = projectRootPath;
this.fs = fs;
this.hasInitialized = false;
// Constructor is slim by design. This is to add as less computation as possible
// to the initialization of the extension. If a public method is added, make sure
// to call this.lazilyInitialize() at the begining of the code to be sure all variables
// are correctly initialized.
this.nodeModulesGlobalPathAddedToEnv = false;
}
public async preloadExponentDependency(): Promise<[typeof xdl, typeof metroConfig]> {
this.logger.info(
localize(
"MakingSureYourProjectUsesCorrectExponentDependencies",
"Making sure your project uses the correct dependencies for Expo. This may take a while...",
),
);
return Promise.all([XDL.getXDLPackage(), XDL.getMetroConfigPackage()]);
}
public async configureExponentEnvironment(): Promise<void> {
let isExpo: boolean;
await this.lazilyInitialize();
this.logger.logStream(
localize("CheckingIfThisIsExpoApp", "Checking if this is an Expo app."),
);
isExpo = await this.isExpoApp(true);
if (!isExpo) {
if (!(await this.appHasExpoInstalled())) {
// Expo requires expo package to be installed inside RN application in order to be able to run it
// https://github.com/expo/expo-cli/issues/255#issuecomment-453214632
this.logger.logStream("\n");
this.logger.logStream(
localize(
"ExpoPackageIsNotInstalled",
'[Warning] Please make sure that expo package is installed locally for your project, otherwise further errors may occur. Please, run "npm install expo --save-dev" inside your project to install it.',
),
);
this.logger.logStream("\n");
}
}
this.logger.logStream(".\n");
await this.patchAppJson(isExpo);
}
/**
* Returns the current user. If there is none, asks user for username and password and logins to exponent servers.
*/
public async loginToExponent(
promptForInformation: (message: string, password: boolean) => Promise<string>,
showMessage: (message: string) => Promise<string>,
): Promise<XDL.IUser> {
await this.lazilyInitialize();
let user = await XDL.currentUser();
if (!user) {
await showMessage(
localize(
"YouNeedToLoginToExpo",
"You need to login to Expo. Please provide your Expo account username and password in the input boxes after closing this window. If you don't have an account, please go to https://expo.io to create one.",
),
);
const username = await promptForInformation(
localize("ExpoUsername", "Expo username"),
false,
);
const password = await promptForInformation(
localize("ExpoPassword", "Expo password"),
true,
);
user = await XDL.login(username, password);
}
return user;
}
public async getExpPackagerOptions(projectRoot: string): Promise<ExpMetroConfig> {
await this.lazilyInitialize();
const options = await this.getFromExpConfig<any>("packagerOpts").then(opts => opts || {});
const metroConfig = await this.getArgumentsFromExpoMetroConfig(projectRoot);
return { ...options, ...metroConfig };
}
public async appHasExpoInstalled(): Promise<boolean> {
const packageJson = await this.getAppPackageInformation();
if (packageJson.dependencies && packageJson.dependencies.expo) {
this.logger.debug("'expo' package is found in 'dependencies' section of package.json");
return true;
} else if (packageJson.devDependencies && packageJson.devDependencies.expo) {
this.logger.debug(
"'expo' package is found in 'devDependencies' section of package.json",
);
return true;
}
return false;
}
public async appHasExpoRNSDKInstalled(): Promise<boolean> {
const packageJson = await this.getAppPackageInformation();
const reactNativeValue =
packageJson.dependencies && packageJson.dependencies["react-native"];
if (reactNativeValue) {
this.logger.debug(
`'react-native' package with value '${reactNativeValue}' is found in 'dependencies' section of package.json`,
);
if (reactNativeValue.startsWith("https://github.com/expo/react-native/archive/sdk")) {
return true;
}
}
return false;
}
public async isExpoApp(showProgress: boolean = false): Promise<boolean> {
if (showProgress) {
this.logger.logStream("...");
}
try {
const [expoInstalled, expoRNSDKInstalled] = await Promise.all([
this.appHasExpoInstalled(),
this.appHasExpoRNSDKInstalled(),
]);
if (showProgress) this.logger.logStream(".");
return expoInstalled && expoRNSDKInstalled;
} catch (e) {
this.logger.error(e.message, e, e.stack);
if (showProgress) {
this.logger.logStream(".");
}
// Not in a react-native project
return false;
}
}
public async findOrInstallNgrokGlobally(): Promise<void> {
let ngrokInstalled: boolean;
try {
await this.addNodeModulesPathToEnvIfNotPresent();
ngrokInstalled = await XDL.isNgrokInstalled(this.projectRootPath);
} catch (e) {
ngrokInstalled = false;
}
if (!ngrokInstalled) {
const ngrokVersion = SettingsHelper.getExpoDependencyVersion("@expo/ngrok");
const ngrokPackageConfig = new PackageConfig(NGROK_PACKAGE, ngrokVersion);
const outputMessage = localize(
"ExpoInstallNgrokGlobally",
'It seems that "{0}" package isn\'t installed globally. This package is required to use Expo tunnels, would you like to install it globally?',
ngrokPackageConfig.getStringForInstall(),
);
const installButton = localize("InstallNgrokGloballyButtonOK", "Install");
const cancelButton = localize("InstallNgrokGloballyButtonCancel", "Cancel");
const selectedItem = await vscode.window.showWarningMessage(
outputMessage,
installButton,
cancelButton,
);
if (selectedItem === installButton) {
await PackageLoader.getInstance().installGlobalPackage(
ngrokPackageConfig,
this.projectRootPath,
);
this.logger.info(
localize(
"NgrokInstalledGlobally",
'"{0}" package has been successfully installed globally.',
ngrokPackageConfig.getStringForInstall(),
),
);
} else {
throw ErrorHelper.getInternalError(
InternalErrorCode.NgrokIsNotInstalledGlobally,
ngrokPackageConfig.getVersion(true),
);
}
}
}
public removeNodeModulesPathFromEnvIfWasSet(): void {
if (this.nodeModulesGlobalPathAddedToEnv) {
delete process.env["NODE_MODULES"];
this.nodeModulesGlobalPathAddedToEnv = false;
}
}
public async addNodeModulesPathToEnvIfNotPresent(): Promise<void> {
if (!process.env["NODE_MODULES"]) {
process.env["NODE_MODULES"] = await getNodeModulesGlobalPath();
this.nodeModulesGlobalPathAddedToEnv = true;
}
}
private async getArgumentsFromExpoMetroConfig(projectRoot: string): Promise<ExpMetroConfig> {
const config = await XDL.getMetroConfig(projectRoot);
return { sourceExts: config.resolver.sourceExts };
}
/**
* Path to a given file inside the .vscode directory
*/
private dotvscodePath(filename: string, isAbsolute: boolean): string {
let paths = [".vscode", filename];
if (isAbsolute) {
paths = [this.workspaceRootPath].concat(...paths);
}
return path.join(...paths);
}
private async createExpoEntry(name: string): Promise<void> {
await this.lazilyInitialize();
const entryPoint = await this.detectEntry();
const content = this.generateFileContent(name, entryPoint);
return await this.fs.writeFile(this.dotvscodePath(EXPONENT_INDEX, true), content);
}
private async detectEntry(): Promise<string> {
await this.lazilyInitialize();
const [expo, ios] = await Promise.all([
this.fs.exists(this.pathToFileInWorkspace(DEFAULT_EXPONENT_INDEX)),
this.fs.exists(this.pathToFileInWorkspace(DEFAULT_IOS_INDEX)),
this.fs.exists(this.pathToFileInWorkspace(DEFAULT_ANDROID_INDEX)),
]);
return expo
? this.pathToFileInWorkspace(DEFAULT_EXPONENT_INDEX)
: ios
? this.pathToFileInWorkspace(DEFAULT_IOS_INDEX)
: this.pathToFileInWorkspace(DEFAULT_ANDROID_INDEX);
}
private generateFileContent(name: string, entryPoint: string): string {
return `// This file is automatically generated by VS Code
// Please do not modify it manually. All changes will be lost.
var React = require('${this.pathToFileInWorkspace("/node_modules/react")}');
var { Component } = React;
var ReactNative = require('${this.pathToFileInWorkspace("/node_modules/react-native")}');
var { AppRegistry } = ReactNative;
AppRegistry.registerRunnable('main', function(appParameters) {
AppRegistry.runApplication('${name}', appParameters);
});
var entryPoint = require('${entryPoint}');`;
}
private async patchAppJson(isExpo: boolean = true): Promise<void> {
let appJson: AppJson;
try {
appJson = await this.readAppJson();
} catch {
// if app.json doesn't exist but it's ok, we will create it
appJson = <AppJson>{};
}
const packageName = await this.getPackageName();
const expoConfig = <ExpConfig>(appJson.expo || {});
if (!expoConfig.name || !expoConfig.slug) {
expoConfig.slug = expoConfig.slug || appJson.name || packageName.replace(" ", "-");
expoConfig.name = expoConfig.name || appJson.name || packageName;
appJson.expo = expoConfig;
}
if (!appJson.name) {
appJson.name = packageName;
}
if (!appJson.expo.sdkVersion) {
const sdkVersion = await this.exponentSdk(true);
appJson.expo.sdkVersion = sdkVersion;
}
if (!isExpo) {
// entryPoint must be relative
// https://docs.expo.io/versions/latest/workflow/configuration/#entrypoint
appJson.expo.entryPoint = this.dotvscodePath(EXPONENT_INDEX, false);
}
appJson = appJson ? await this.writeAppJson(appJson) : appJson;
if (!isExpo) {
await this.createExpoEntry(appJson.expo.name);
}
}
/**
* Exponent sdk version that maps to the current react-native version
* If react native version is not supported it returns null.
*/
private async exponentSdk(showProgress: boolean = false): Promise<string> {
if (showProgress) {
this.logger.logStream("...");
}
const versions = await ProjectVersionHelper.getReactNativeVersions(this.projectRootPath);
if (showProgress) {
this.logger.logStream(".");
}
const sdkVersion = await this.mapFacebookReactNativeVersionToExpoVersion(
versions.reactNativeVersion,
);
if (!sdkVersion) {
const supportedVersions = await this.getFacebookReactNativeVersions();
throw ErrorHelper.getInternalError(
InternalErrorCode.RNVersionNotSupportedByExponent,
supportedVersions.join(", "),
);
}
return sdkVersion;
}
private async getFacebookReactNativeVersions(): Promise<string[]> {
const sdkVersions = await XDL.getExpoSdkVersions();
const facebookReactNativeVersions = new Set(
Object.values(sdkVersions)
.map(data => data.facebookReactNativeVersion)
.filter(version => version),
);
return Array.from(facebookReactNativeVersions);
}
private async mapFacebookReactNativeVersionToExpoVersion(
outerFacebookReactNativeVersion: string,
): Promise<string | null> {
if (!semver.valid(outerFacebookReactNativeVersion)) {
throw new Error(
`${outerFacebookReactNativeVersion} is not a valid version. It must be in the form of x.y.z`,
);
}
const sdkVersions = await XDL.getReleasedExpoSdkVersions();
let currentSdkVersion: string | null = null;
for (const [version, { facebookReactNativeVersion }] of Object.entries(sdkVersions)) {
if (
semver.major(outerFacebookReactNativeVersion) ===
semver.major(facebookReactNativeVersion) &&
semver.minor(outerFacebookReactNativeVersion) ===
semver.minor(facebookReactNativeVersion) &&
(!currentSdkVersion || semver.gt(version, currentSdkVersion))
) {
currentSdkVersion = version;
}
}
return currentSdkVersion;
}
/**
* Name specified on user's package.json
*/
private getPackageName(): Promise<string> {
return new Package(this.projectRootPath, { fileSystem: this.fs }).name();
}
private async getExpConfig(): Promise<ExpConfig> {
try {
return this.readExpJson();
} catch (err) {
if (err.code === "ENOENT") {
const appJson = await this.readAppJson();
return appJson.expo || {};
}
throw err;
}
}
private async getFromExpConfig<T>(key: string): Promise<T> {
const config = await this.getExpConfig();
return config[key];
}
/**
* Returns the specified setting from exp.json if it exists
*/
private async readExpJson(): Promise<ExpConfig> {
const expJsonPath = this.pathToFileInWorkspace(EXP_JSON);
const content = await this.fs.readFile(expJsonPath);
return JSON.parse(stripJSONComments(content.toString()));
}
private async readAppJson(): Promise<AppJson> {
const appJsonPath = this.pathToFileInWorkspace(APP_JSON);
const content = await this.fs.readFile(appJsonPath);
return JSON.parse(stripJSONComments(content.toString()));
}
private async writeAppJson(config: AppJson): Promise<AppJson> {
const appJsonPath = this.pathToFileInWorkspace(APP_JSON);
await this.fs.writeFile(appJsonPath, JSON.stringify(config, null, 2));
return config;
}
private getAppPackageInformation(): Promise<IPackageInformation> {
return new Package(this.projectRootPath, { fileSystem: this.fs }).parsePackageInformation();
}
/**
* Path to a given file from the workspace root
*/
private pathToFileInWorkspace(filename: string): string {
return path.join(this.projectRootPath, filename).replace(DBL_SLASHES, "/");
}
/**
* Works as a constructor but only initiliazes when it's actually needed.
*/
private async lazilyInitialize(): Promise<void> {
if (!this.hasInitialized) {
this.hasInitialized = true;
await this.preloadExponentDependency();
XDL.configReactNativeVersionWarnings();
XDL.attachLoggerStream(this.projectRootPath, {
stream: {
write: (chunk: any) => {
if (chunk.level <= 30) {
this.logger.logStream(chunk.msg);
} else if (chunk.level === 40) {
this.logger.warning(chunk.msg);
} else {
this.logger.error(chunk.msg);
}
},
},
type: "raw",
});
}
}
} | the_stack |
import type { BinaryWriteOptions } from "@protobuf-ts/runtime";
import type { IBinaryWriter } from "@protobuf-ts/runtime";
import { WireType } from "@protobuf-ts/runtime";
import type { BinaryReadOptions } from "@protobuf-ts/runtime";
import type { IBinaryReader } from "@protobuf-ts/runtime";
import { UnknownFieldHandler } from "@protobuf-ts/runtime";
import { MessageType } from "@protobuf-ts/runtime";
/**
* The protocol compiler can output a FileDescriptorSet containing the .proto
* files it parses.
*
* @generated from protobuf message google.protobuf.FileDescriptorSet
*/
export interface FileDescriptorSet {
/**
* @generated from protobuf field: repeated google.protobuf.FileDescriptorProto file = 1;
*/
file: FileDescriptorProto[];
}
/**
* Describes a complete .proto file.
*
* @generated from protobuf message google.protobuf.FileDescriptorProto
*/
export interface FileDescriptorProto {
/**
* @generated from protobuf field: optional string name = 1;
*/
name?: string; // file name, relative to root of source tree
/**
* @generated from protobuf field: optional string package = 2;
*/
package?: string; // e.g. "foo", "foo.bar", etc.
/**
* Names of files imported by this file.
*
* @generated from protobuf field: repeated string dependency = 3;
*/
dependency: string[];
/**
* Indexes of the public imported files in the dependency list above.
*
* @generated from protobuf field: repeated int32 public_dependency = 10;
*/
publicDependency: number[];
/**
* Indexes of the weak imported files in the dependency list.
* For Google-internal migration only. Do not use.
*
* @generated from protobuf field: repeated int32 weak_dependency = 11;
*/
weakDependency: number[];
/**
* All top-level definitions in this file.
*
* @generated from protobuf field: repeated google.protobuf.DescriptorProto message_type = 4;
*/
messageType: DescriptorProto[];
/**
* @generated from protobuf field: repeated google.protobuf.EnumDescriptorProto enum_type = 5;
*/
enumType: EnumDescriptorProto[];
/**
* @generated from protobuf field: repeated google.protobuf.ServiceDescriptorProto service = 6;
*/
service: ServiceDescriptorProto[];
/**
* @generated from protobuf field: repeated google.protobuf.FieldDescriptorProto extension = 7;
*/
extension: FieldDescriptorProto[];
/**
* @generated from protobuf field: optional google.protobuf.FileOptions options = 8;
*/
options?: FileOptions;
/**
* This field contains optional information about the original source code.
* You may safely remove this entire field without harming runtime
* functionality of the descriptors -- the information is needed only by
* development tools.
*
* @generated from protobuf field: optional google.protobuf.SourceCodeInfo source_code_info = 9;
*/
sourceCodeInfo?: SourceCodeInfo;
/**
* The syntax of the proto file.
* The supported values are "proto2" and "proto3".
*
* @generated from protobuf field: optional string syntax = 12;
*/
syntax?: string;
}
/**
* Describes a message type.
*
* @generated from protobuf message google.protobuf.DescriptorProto
*/
export interface DescriptorProto {
/**
* @generated from protobuf field: optional string name = 1;
*/
name?: string;
/**
* @generated from protobuf field: repeated google.protobuf.FieldDescriptorProto field = 2;
*/
field: FieldDescriptorProto[];
/**
* @generated from protobuf field: repeated google.protobuf.FieldDescriptorProto extension = 6;
*/
extension: FieldDescriptorProto[];
/**
* @generated from protobuf field: repeated google.protobuf.DescriptorProto nested_type = 3;
*/
nestedType: DescriptorProto[];
/**
* @generated from protobuf field: repeated google.protobuf.EnumDescriptorProto enum_type = 4;
*/
enumType: EnumDescriptorProto[];
/**
* @generated from protobuf field: repeated google.protobuf.DescriptorProto.ExtensionRange extension_range = 5;
*/
extensionRange: DescriptorProto_ExtensionRange[];
/**
* @generated from protobuf field: repeated google.protobuf.OneofDescriptorProto oneof_decl = 8;
*/
oneofDecl: OneofDescriptorProto[];
/**
* @generated from protobuf field: optional google.protobuf.MessageOptions options = 7;
*/
options?: MessageOptions;
/**
* @generated from protobuf field: repeated google.protobuf.DescriptorProto.ReservedRange reserved_range = 9;
*/
reservedRange: DescriptorProto_ReservedRange[];
/**
* Reserved field names, which may not be used by fields in the same message.
* A given name may only be reserved once.
*
* @generated from protobuf field: repeated string reserved_name = 10;
*/
reservedName: string[];
}
/**
* @generated from protobuf message google.protobuf.DescriptorProto.ExtensionRange
*/
export interface DescriptorProto_ExtensionRange {
/**
* @generated from protobuf field: optional int32 start = 1;
*/
start?: number; // Inclusive.
/**
* @generated from protobuf field: optional int32 end = 2;
*/
end?: number; // Exclusive.
/**
* @generated from protobuf field: optional google.protobuf.ExtensionRangeOptions options = 3;
*/
options?: ExtensionRangeOptions;
}
/**
* Range of reserved tag numbers. Reserved tag numbers may not be used by
* fields or extension ranges in the same message. Reserved ranges may
* not overlap.
*
* @generated from protobuf message google.protobuf.DescriptorProto.ReservedRange
*/
export interface DescriptorProto_ReservedRange {
/**
* @generated from protobuf field: optional int32 start = 1;
*/
start?: number; // Inclusive.
/**
* @generated from protobuf field: optional int32 end = 2;
*/
end?: number; // Exclusive.
}
/**
* @generated from protobuf message google.protobuf.ExtensionRangeOptions
*/
export interface ExtensionRangeOptions {
/**
* The parser stores options it doesn't recognize here. See above.
*
* @generated from protobuf field: repeated google.protobuf.UninterpretedOption uninterpreted_option = 999;
*/
uninterpretedOption: UninterpretedOption[];
}
/**
* Describes a field within a message.
*
* @generated from protobuf message google.protobuf.FieldDescriptorProto
*/
export interface FieldDescriptorProto {
/**
* @generated from protobuf field: optional string name = 1;
*/
name?: string;
/**
* @generated from protobuf field: optional int32 number = 3;
*/
number?: number;
/**
* @generated from protobuf field: optional google.protobuf.FieldDescriptorProto.Label label = 4;
*/
label?: FieldDescriptorProto_Label;
/**
* If type_name is set, this need not be set. If both this and type_name
* are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
*
* @generated from protobuf field: optional google.protobuf.FieldDescriptorProto.Type type = 5;
*/
type?: FieldDescriptorProto_Type;
/**
* For message and enum types, this is the name of the type. If the name
* starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
* rules are used to find the type (i.e. first the nested types within this
* message are searched, then within the parent, on up to the root
* namespace).
*
* @generated from protobuf field: optional string type_name = 6;
*/
typeName?: string;
/**
* For extensions, this is the name of the type being extended. It is
* resolved in the same manner as type_name.
*
* @generated from protobuf field: optional string extendee = 2;
*/
extendee?: string;
/**
* For numeric types, contains the original text representation of the value.
* For booleans, "true" or "false".
* For strings, contains the default text contents (not escaped in any way).
* For bytes, contains the C escaped value. All bytes >= 128 are escaped.
* TODO(kenton): Base-64 encode?
*
* @generated from protobuf field: optional string default_value = 7;
*/
defaultValue?: string;
/**
* If set, gives the index of a oneof in the containing type's oneof_decl
* list. This field is a member of that oneof.
*
* @generated from protobuf field: optional int32 oneof_index = 9;
*/
oneofIndex?: number;
/**
* JSON name of this field. The value is set by protocol compiler. If the
* user has set a "json_name" option on this field, that option's value
* will be used. Otherwise, it's deduced from the field's name by converting
* it to camelCase.
*
* @generated from protobuf field: optional string json_name = 10;
*/
jsonName?: string;
/**
* @generated from protobuf field: optional google.protobuf.FieldOptions options = 8;
*/
options?: FieldOptions;
/**
* If true, this is a proto3 "optional". When a proto3 field is optional, it
* tracks presence regardless of field type.
*
* When proto3_optional is true, this field must be belong to a oneof to
* signal to old proto3 clients that presence is tracked for this field. This
* oneof is known as a "synthetic" oneof, and this field must be its sole
* member (each proto3 optional field gets its own synthetic oneof). Synthetic
* oneofs exist in the descriptor only, and do not generate any API. Synthetic
* oneofs must be ordered after all "real" oneofs.
*
* For message fields, proto3_optional doesn't create any semantic change,
* since non-repeated message fields always track presence. However it still
* indicates the semantic detail of whether the user wrote "optional" or not.
* This can be useful for round-tripping the .proto file. For consistency we
* give message fields a synthetic oneof also, even though it is not required
* to track presence. This is especially important because the parser can't
* tell if a field is a message or an enum, so it must always create a
* synthetic oneof.
*
* Proto2 optional fields do not set this flag, because they already indicate
* optional with `LABEL_OPTIONAL`.
*
* @generated from protobuf field: optional bool proto3_optional = 17;
*/
proto3Optional?: boolean;
}
/**
* @generated from protobuf enum google.protobuf.FieldDescriptorProto.Type
*/
export enum FieldDescriptorProto_Type {
/**
* @generated synthetic value - protobuf-ts requires all enums to have a 0 value
*/
UNSPECIFIED$ = 0,
/**
* 0 is reserved for errors.
* Order is weird for historical reasons.
*
* @generated from protobuf enum value: TYPE_DOUBLE = 1;
*/
DOUBLE = 1,
/**
* @generated from protobuf enum value: TYPE_FLOAT = 2;
*/
FLOAT = 2,
/**
* Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
* negative values are likely.
*
* @generated from protobuf enum value: TYPE_INT64 = 3;
*/
INT64 = 3,
/**
* @generated from protobuf enum value: TYPE_UINT64 = 4;
*/
UINT64 = 4,
/**
* Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
* negative values are likely.
*
* @generated from protobuf enum value: TYPE_INT32 = 5;
*/
INT32 = 5,
/**
* @generated from protobuf enum value: TYPE_FIXED64 = 6;
*/
FIXED64 = 6,
/**
* @generated from protobuf enum value: TYPE_FIXED32 = 7;
*/
FIXED32 = 7,
/**
* @generated from protobuf enum value: TYPE_BOOL = 8;
*/
BOOL = 8,
/**
* @generated from protobuf enum value: TYPE_STRING = 9;
*/
STRING = 9,
/**
* Tag-delimited aggregate.
* Group type is deprecated and not supported in proto3. However, Proto3
* implementations should still be able to parse the group wire format and
* treat group fields as unknown fields.
*
* @generated from protobuf enum value: TYPE_GROUP = 10;
*/
GROUP = 10,
/**
* Length-delimited aggregate.
*
* @generated from protobuf enum value: TYPE_MESSAGE = 11;
*/
MESSAGE = 11,
/**
* New in version 2.
*
* @generated from protobuf enum value: TYPE_BYTES = 12;
*/
BYTES = 12,
/**
* @generated from protobuf enum value: TYPE_UINT32 = 13;
*/
UINT32 = 13,
/**
* @generated from protobuf enum value: TYPE_ENUM = 14;
*/
ENUM = 14,
/**
* @generated from protobuf enum value: TYPE_SFIXED32 = 15;
*/
SFIXED32 = 15,
/**
* @generated from protobuf enum value: TYPE_SFIXED64 = 16;
*/
SFIXED64 = 16,
/**
* Uses ZigZag encoding.
*
* @generated from protobuf enum value: TYPE_SINT32 = 17;
*/
SINT32 = 17,
/**
* Uses ZigZag encoding.
*
* @generated from protobuf enum value: TYPE_SINT64 = 18;
*/
SINT64 = 18
}
/**
* @generated from protobuf enum google.protobuf.FieldDescriptorProto.Label
*/
export enum FieldDescriptorProto_Label {
/**
* @generated synthetic value - protobuf-ts requires all enums to have a 0 value
*/
UNSPECIFIED$ = 0,
/**
* 0 is reserved for errors
*
* @generated from protobuf enum value: LABEL_OPTIONAL = 1;
*/
OPTIONAL = 1,
/**
* @generated from protobuf enum value: LABEL_REQUIRED = 2;
*/
REQUIRED = 2,
/**
* @generated from protobuf enum value: LABEL_REPEATED = 3;
*/
REPEATED = 3
}
/**
* Describes a oneof.
*
* @generated from protobuf message google.protobuf.OneofDescriptorProto
*/
export interface OneofDescriptorProto {
/**
* @generated from protobuf field: optional string name = 1;
*/
name?: string;
/**
* @generated from protobuf field: optional google.protobuf.OneofOptions options = 2;
*/
options?: OneofOptions;
}
/**
* Describes an enum type.
*
* @generated from protobuf message google.protobuf.EnumDescriptorProto
*/
export interface EnumDescriptorProto {
/**
* @generated from protobuf field: optional string name = 1;
*/
name?: string;
/**
* @generated from protobuf field: repeated google.protobuf.EnumValueDescriptorProto value = 2;
*/
value: EnumValueDescriptorProto[];
/**
* @generated from protobuf field: optional google.protobuf.EnumOptions options = 3;
*/
options?: EnumOptions;
/**
* Range of reserved numeric values. Reserved numeric values may not be used
* by enum values in the same enum declaration. Reserved ranges may not
* overlap.
*
* @generated from protobuf field: repeated google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4;
*/
reservedRange: EnumDescriptorProto_EnumReservedRange[];
/**
* Reserved enum value names, which may not be reused. A given name may only
* be reserved once.
*
* @generated from protobuf field: repeated string reserved_name = 5;
*/
reservedName: string[];
}
/**
* Range of reserved numeric values. Reserved values may not be used by
* entries in the same enum. Reserved ranges may not overlap.
*
* Note that this is distinct from DescriptorProto.ReservedRange in that it
* is inclusive such that it can appropriately represent the entire int32
* domain.
*
* @generated from protobuf message google.protobuf.EnumDescriptorProto.EnumReservedRange
*/
export interface EnumDescriptorProto_EnumReservedRange {
/**
* @generated from protobuf field: optional int32 start = 1;
*/
start?: number; // Inclusive.
/**
* @generated from protobuf field: optional int32 end = 2;
*/
end?: number; // Inclusive.
}
/**
* Describes a value within an enum.
*
* @generated from protobuf message google.protobuf.EnumValueDescriptorProto
*/
export interface EnumValueDescriptorProto {
/**
* @generated from protobuf field: optional string name = 1;
*/
name?: string;
/**
* @generated from protobuf field: optional int32 number = 2;
*/
number?: number;
/**
* @generated from protobuf field: optional google.protobuf.EnumValueOptions options = 3;
*/
options?: EnumValueOptions;
}
/**
* Describes a service.
*
* @generated from protobuf message google.protobuf.ServiceDescriptorProto
*/
export interface ServiceDescriptorProto {
/**
* @generated from protobuf field: optional string name = 1;
*/
name?: string;
/**
* @generated from protobuf field: repeated google.protobuf.MethodDescriptorProto method = 2;
*/
method: MethodDescriptorProto[];
/**
* @generated from protobuf field: optional google.protobuf.ServiceOptions options = 3;
*/
options?: ServiceOptions;
}
/**
* Describes a method of a service.
*
* @generated from protobuf message google.protobuf.MethodDescriptorProto
*/
export interface MethodDescriptorProto {
/**
* @generated from protobuf field: optional string name = 1;
*/
name?: string;
/**
* Input and output type names. These are resolved in the same way as
* FieldDescriptorProto.type_name, but must refer to a message type.
*
* @generated from protobuf field: optional string input_type = 2;
*/
inputType?: string;
/**
* @generated from protobuf field: optional string output_type = 3;
*/
outputType?: string;
/**
* @generated from protobuf field: optional google.protobuf.MethodOptions options = 4;
*/
options?: MethodOptions;
/**
* Identifies if client streams multiple client messages
*
* @generated from protobuf field: optional bool client_streaming = 5;
*/
clientStreaming?: boolean;
/**
* Identifies if server streams multiple server messages
*
* @generated from protobuf field: optional bool server_streaming = 6;
*/
serverStreaming?: boolean;
}
// ===================================================================
// Options
// Each of the definitions above may have "options" attached. These are
// just annotations which may cause code to be generated slightly differently
// or may contain hints for code that manipulates protocol messages.
//
// Clients may define custom options as extensions of the *Options messages.
// These extensions may not yet be known at parsing time, so the parser cannot
// store the values in them. Instead it stores them in a field in the *Options
// message called uninterpreted_option. This field must have the same name
// across all *Options messages. We then use this field to populate the
// extensions when we build a descriptor, at which point all protos have been
// parsed and so all extensions are known.
//
// Extension numbers for custom options may be chosen as follows:
// * For options which will only be used within a single application or
// organization, or for experimental options, use field numbers 50000
// through 99999. It is up to you to ensure that you do not use the
// same number for multiple options.
// * For options which will be published and used publicly by multiple
// independent entities, e-mail protobuf-global-extension-registry@google.com
// to reserve extension numbers. Simply provide your project name (e.g.
// Objective-C plugin) and your project website (if available) -- there's no
// need to explain how you intend to use them. Usually you only need one
// extension number. You can declare multiple options with only one extension
// number by putting them in a sub-message. See the Custom Options section of
// the docs for examples:
// https://developers.google.com/protocol-buffers/docs/proto#options
// If this turns out to be popular, a web service will be set up
// to automatically assign option numbers.
/**
* @generated from protobuf message google.protobuf.FileOptions
*/
export interface FileOptions {
/**
* Sets the Java package where classes generated from this .proto will be
* placed. By default, the proto package is used, but this is often
* inappropriate because proto packages do not normally start with backwards
* domain names.
*
* @generated from protobuf field: optional string java_package = 1;
*/
javaPackage?: string;
/**
* Controls the name of the wrapper Java class generated for the .proto file.
* That class will always contain the .proto file's getDescriptor() method as
* well as any top-level extensions defined in the .proto file.
* If java_multiple_files is disabled, then all the other classes from the
* .proto file will be nested inside the single wrapper outer class.
*
* @generated from protobuf field: optional string java_outer_classname = 8;
*/
javaOuterClassname?: string;
/**
* If enabled, then the Java code generator will generate a separate .java
* file for each top-level message, enum, and service defined in the .proto
* file. Thus, these types will *not* be nested inside the wrapper class
* named by java_outer_classname. However, the wrapper class will still be
* generated to contain the file's getDescriptor() method as well as any
* top-level extensions defined in the file.
*
* @generated from protobuf field: optional bool java_multiple_files = 10;
*/
javaMultipleFiles?: boolean;
/**
* This option does nothing.
*
* @deprecated
* @generated from protobuf field: optional bool java_generate_equals_and_hash = 20 [deprecated = true];
*/
javaGenerateEqualsAndHash?: boolean;
/**
* If set true, then the Java2 code generator will generate code that
* throws an exception whenever an attempt is made to assign a non-UTF-8
* byte sequence to a string field.
* Message reflection will do the same.
* However, an extension field still accepts non-UTF-8 byte sequences.
* This option has no effect on when used with the lite runtime.
*
* @generated from protobuf field: optional bool java_string_check_utf8 = 27;
*/
javaStringCheckUtf8?: boolean;
/**
* @generated from protobuf field: optional google.protobuf.FileOptions.OptimizeMode optimize_for = 9;
*/
optimizeFor?: FileOptions_OptimizeMode;
/**
* Sets the Go package where structs generated from this .proto will be
* placed. If omitted, the Go package will be derived from the following:
* - The basename of the package import path, if provided.
* - Otherwise, the package statement in the .proto file, if present.
* - Otherwise, the basename of the .proto file, without extension.
*
* @generated from protobuf field: optional string go_package = 11;
*/
goPackage?: string;
/**
* Should generic services be generated in each language? "Generic" services
* are not specific to any particular RPC system. They are generated by the
* main code generators in each language (without additional plugins).
* Generic services were the only kind of service generation supported by
* early versions of google.protobuf.
*
* Generic services are now considered deprecated in favor of using plugins
* that generate code specific to your particular RPC system. Therefore,
* these default to false. Old code which depends on generic services should
* explicitly set them to true.
*
* @generated from protobuf field: optional bool cc_generic_services = 16;
*/
ccGenericServices?: boolean;
/**
* @generated from protobuf field: optional bool java_generic_services = 17;
*/
javaGenericServices?: boolean;
/**
* @generated from protobuf field: optional bool py_generic_services = 18;
*/
pyGenericServices?: boolean;
/**
* @generated from protobuf field: optional bool php_generic_services = 42;
*/
phpGenericServices?: boolean;
/**
* Is this file deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for everything in the file, or it will be completely ignored; in the very
* least, this is a formalization for deprecating files.
*
* @generated from protobuf field: optional bool deprecated = 23;
*/
deprecated?: boolean;
/**
* Enables the use of arenas for the proto messages in this file. This applies
* only to generated classes for C++.
*
* @generated from protobuf field: optional bool cc_enable_arenas = 31;
*/
ccEnableArenas?: boolean;
/**
* Sets the objective c class prefix which is prepended to all objective c
* generated classes from this .proto. There is no default.
*
* @generated from protobuf field: optional string objc_class_prefix = 36;
*/
objcClassPrefix?: string;
/**
* Namespace for generated classes; defaults to the package.
*
* @generated from protobuf field: optional string csharp_namespace = 37;
*/
csharpNamespace?: string;
/**
* By default Swift generators will take the proto package and CamelCase it
* replacing '.' with underscore and use that to prefix the types/symbols
* defined. When this options is provided, they will use this value instead
* to prefix the types/symbols defined.
*
* @generated from protobuf field: optional string swift_prefix = 39;
*/
swiftPrefix?: string;
/**
* Sets the php class prefix which is prepended to all php generated classes
* from this .proto. Default is empty.
*
* @generated from protobuf field: optional string php_class_prefix = 40;
*/
phpClassPrefix?: string;
/**
* Use this option to change the namespace of php generated classes. Default
* is empty. When this option is empty, the package name will be used for
* determining the namespace.
*
* @generated from protobuf field: optional string php_namespace = 41;
*/
phpNamespace?: string;
/**
* Use this option to change the namespace of php generated metadata classes.
* Default is empty. When this option is empty, the proto file name will be
* used for determining the namespace.
*
* @generated from protobuf field: optional string php_metadata_namespace = 44;
*/
phpMetadataNamespace?: string;
/**
* Use this option to change the package of ruby generated classes. Default
* is empty. When this option is not set, the package name will be used for
* determining the ruby package.
*
* @generated from protobuf field: optional string ruby_package = 45;
*/
rubyPackage?: string;
/**
* The parser stores options it doesn't recognize here.
* See the documentation for the "Options" section above.
*
* @generated from protobuf field: repeated google.protobuf.UninterpretedOption uninterpreted_option = 999;
*/
uninterpretedOption: UninterpretedOption[];
}
/**
* Generated classes can be optimized for speed or code size.
*
* @generated from protobuf enum google.protobuf.FileOptions.OptimizeMode
*/
export enum FileOptions_OptimizeMode {
/**
* @generated synthetic value - protobuf-ts requires all enums to have a 0 value
*/
UNSPECIFIED$ = 0,
/**
* Generate complete code for parsing, serialization,
*
* @generated from protobuf enum value: SPEED = 1;
*/
SPEED = 1,
/**
* etc.
*
* Use ReflectionOps to implement these methods.
*
* @generated from protobuf enum value: CODE_SIZE = 2;
*/
CODE_SIZE = 2,
/**
* Generate code using MessageLite and the lite runtime.
*
* @generated from protobuf enum value: LITE_RUNTIME = 3;
*/
LITE_RUNTIME = 3
}
/**
* @generated from protobuf message google.protobuf.MessageOptions
*/
export interface MessageOptions {
/**
* Set true to use the old proto1 MessageSet wire format for extensions.
* This is provided for backwards-compatibility with the MessageSet wire
* format. You should not use this for any other reason: It's less
* efficient, has fewer features, and is more complicated.
*
* The message must be defined exactly as follows:
* message Foo {
* option message_set_wire_format = true;
* extensions 4 to max;
* }
* Note that the message cannot have any defined fields; MessageSets only
* have extensions.
*
* All extensions of your type must be singular messages; e.g. they cannot
* be int32s, enums, or repeated messages.
*
* Because this is an option, the above two restrictions are not enforced by
* the protocol compiler.
*
* @generated from protobuf field: optional bool message_set_wire_format = 1;
*/
messageSetWireFormat?: boolean;
/**
* Disables the generation of the standard "descriptor()" accessor, which can
* conflict with a field of the same name. This is meant to make migration
* from proto1 easier; new code should avoid fields named "descriptor".
*
* @generated from protobuf field: optional bool no_standard_descriptor_accessor = 2;
*/
noStandardDescriptorAccessor?: boolean;
/**
* Is this message deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the message, or it will be completely ignored; in the very least,
* this is a formalization for deprecating messages.
*
* @generated from protobuf field: optional bool deprecated = 3;
*/
deprecated?: boolean;
/**
* Whether the message is an automatically generated map entry type for the
* maps field.
*
* For maps fields:
* map<KeyType, ValueType> map_field = 1;
* The parsed descriptor looks like:
* message MapFieldEntry {
* option map_entry = true;
* optional KeyType key = 1;
* optional ValueType value = 2;
* }
* repeated MapFieldEntry map_field = 1;
*
* Implementations may choose not to generate the map_entry=true message, but
* use a native map in the target language to hold the keys and values.
* The reflection APIs in such implementations still need to work as
* if the field is a repeated message field.
*
* NOTE: Do not set the option in .proto files. Always use the maps syntax
* instead. The option should only be implicitly set by the proto compiler
* parser.
*
* @generated from protobuf field: optional bool map_entry = 7;
*/
mapEntry?: boolean;
/**
* The parser stores options it doesn't recognize here. See above.
*
* @generated from protobuf field: repeated google.protobuf.UninterpretedOption uninterpreted_option = 999;
*/
uninterpretedOption: UninterpretedOption[];
}
/**
* @generated from protobuf message google.protobuf.FieldOptions
*/
export interface FieldOptions {
/**
* The ctype option instructs the C++ code generator to use a different
* representation of the field than it normally would. See the specific
* options below. This option is not yet implemented in the open source
* release -- sorry, we'll try to include it in a future version!
*
* @generated from protobuf field: optional google.protobuf.FieldOptions.CType ctype = 1;
*/
ctype?: FieldOptions_CType;
/**
* The packed option can be enabled for repeated primitive fields to enable
* a more efficient representation on the wire. Rather than repeatedly
* writing the tag and type for each element, the entire array is encoded as
* a single length-delimited blob. In proto3, only explicit setting it to
* false will avoid using packed encoding.
*
* @generated from protobuf field: optional bool packed = 2;
*/
packed?: boolean;
/**
* The jstype option determines the JavaScript type used for values of the
* field. The option is permitted only for 64 bit integral and fixed types
* (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
* is represented as JavaScript string, which avoids loss of precision that
* can happen when a large value is converted to a floating point JavaScript.
* Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
* use the JavaScript "number" type. The behavior of the default option
* JS_NORMAL is implementation dependent.
*
* This option is an enum to permit additional types to be added, e.g.
* goog.math.Integer.
*
* @generated from protobuf field: optional google.protobuf.FieldOptions.JSType jstype = 6;
*/
jstype?: FieldOptions_JSType;
/**
* Should this field be parsed lazily? Lazy applies only to message-type
* fields. It means that when the outer message is initially parsed, the
* inner message's contents will not be parsed but instead stored in encoded
* form. The inner message will actually be parsed when it is first accessed.
*
* This is only a hint. Implementations are free to choose whether to use
* eager or lazy parsing regardless of the value of this option. However,
* setting this option true suggests that the protocol author believes that
* using lazy parsing on this field is worth the additional bookkeeping
* overhead typically needed to implement it.
*
* This option does not affect the public interface of any generated code;
* all method signatures remain the same. Furthermore, thread-safety of the
* interface is not affected by this option; const methods remain safe to
* call from multiple threads concurrently, while non-const methods continue
* to require exclusive access.
*
*
* Note that implementations may choose not to check required fields within
* a lazy sub-message. That is, calling IsInitialized() on the outer message
* may return true even if the inner message has missing required fields.
* This is necessary because otherwise the inner message would have to be
* parsed in order to perform the check, defeating the purpose of lazy
* parsing. An implementation which chooses not to check required fields
* must be consistent about it. That is, for any particular sub-message, the
* implementation must either *always* check its required fields, or *never*
* check its required fields, regardless of whether or not the message has
* been parsed.
*
* @generated from protobuf field: optional bool lazy = 5;
*/
lazy?: boolean;
/**
* Is this field deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for accessors, or it will be completely ignored; in the very least, this
* is a formalization for deprecating fields.
*
* @generated from protobuf field: optional bool deprecated = 3;
*/
deprecated?: boolean;
/**
* For Google-internal migration only. Do not use.
*
* @generated from protobuf field: optional bool weak = 10;
*/
weak?: boolean;
/**
* The parser stores options it doesn't recognize here. See above.
*
* @generated from protobuf field: repeated google.protobuf.UninterpretedOption uninterpreted_option = 999;
*/
uninterpretedOption: UninterpretedOption[];
}
/**
* @generated from protobuf enum google.protobuf.FieldOptions.CType
*/
export enum FieldOptions_CType {
/**
* Default mode.
*
* @generated from protobuf enum value: STRING = 0;
*/
STRING = 0,
/**
* @generated from protobuf enum value: CORD = 1;
*/
CORD = 1,
/**
* @generated from protobuf enum value: STRING_PIECE = 2;
*/
STRING_PIECE = 2
}
/**
* @generated from protobuf enum google.protobuf.FieldOptions.JSType
*/
export enum FieldOptions_JSType {
/**
* Use the default type.
*
* @generated from protobuf enum value: JS_NORMAL = 0;
*/
JS_NORMAL = 0,
/**
* Use JavaScript strings.
*
* @generated from protobuf enum value: JS_STRING = 1;
*/
JS_STRING = 1,
/**
* Use JavaScript numbers.
*
* @generated from protobuf enum value: JS_NUMBER = 2;
*/
JS_NUMBER = 2
}
/**
* @generated from protobuf message google.protobuf.OneofOptions
*/
export interface OneofOptions {
/**
* The parser stores options it doesn't recognize here. See above.
*
* @generated from protobuf field: repeated google.protobuf.UninterpretedOption uninterpreted_option = 999;
*/
uninterpretedOption: UninterpretedOption[];
}
/**
* @generated from protobuf message google.protobuf.EnumOptions
*/
export interface EnumOptions {
/**
* Set this option to true to allow mapping different tag names to the same
* value.
*
* @generated from protobuf field: optional bool allow_alias = 2;
*/
allowAlias?: boolean;
/**
* Is this enum deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the enum, or it will be completely ignored; in the very least, this
* is a formalization for deprecating enums.
*
* @generated from protobuf field: optional bool deprecated = 3;
*/
deprecated?: boolean;
/**
* The parser stores options it doesn't recognize here. See above.
*
* @generated from protobuf field: repeated google.protobuf.UninterpretedOption uninterpreted_option = 999;
*/
uninterpretedOption: UninterpretedOption[];
}
/**
* @generated from protobuf message google.protobuf.EnumValueOptions
*/
export interface EnumValueOptions {
/**
* Is this enum value deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the enum value, or it will be completely ignored; in the very least,
* this is a formalization for deprecating enum values.
*
* @generated from protobuf field: optional bool deprecated = 1;
*/
deprecated?: boolean;
/**
* The parser stores options it doesn't recognize here. See above.
*
* @generated from protobuf field: repeated google.protobuf.UninterpretedOption uninterpreted_option = 999;
*/
uninterpretedOption: UninterpretedOption[];
}
/**
* @generated from protobuf message google.protobuf.ServiceOptions
*/
export interface ServiceOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
/**
* Is this service deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the service, or it will be completely ignored; in the very least,
* this is a formalization for deprecating services.
*
* @generated from protobuf field: optional bool deprecated = 33;
*/
deprecated?: boolean;
/**
* The parser stores options it doesn't recognize here. See above.
*
* @generated from protobuf field: repeated google.protobuf.UninterpretedOption uninterpreted_option = 999;
*/
uninterpretedOption: UninterpretedOption[];
}
/**
* @generated from protobuf message google.protobuf.MethodOptions
*/
export interface MethodOptions {
// Note: Field numbers 1 through 32 are reserved for Google's internal RPC
// framework. We apologize for hoarding these numbers to ourselves, but
// we were already using them long before we decided to release Protocol
// Buffers.
/**
* Is this method deprecated?
* Depending on the target platform, this can emit Deprecated annotations
* for the method, or it will be completely ignored; in the very least,
* this is a formalization for deprecating methods.
*
* @generated from protobuf field: optional bool deprecated = 33;
*/
deprecated?: boolean;
/**
* @generated from protobuf field: optional google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34;
*/
idempotencyLevel?: MethodOptions_IdempotencyLevel;
/**
* The parser stores options it doesn't recognize here. See above.
*
* @generated from protobuf field: repeated google.protobuf.UninterpretedOption uninterpreted_option = 999;
*/
uninterpretedOption: UninterpretedOption[];
}
/**
* Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
* or neither? HTTP based RPC implementation may choose GET verb for safe
* methods, and PUT verb for idempotent methods instead of the default POST.
*
* @generated from protobuf enum google.protobuf.MethodOptions.IdempotencyLevel
*/
export enum MethodOptions_IdempotencyLevel {
/**
* @generated from protobuf enum value: IDEMPOTENCY_UNKNOWN = 0;
*/
IDEMPOTENCY_UNKNOWN = 0,
/**
* implies idempotent
*
* @generated from protobuf enum value: NO_SIDE_EFFECTS = 1;
*/
NO_SIDE_EFFECTS = 1,
/**
* idempotent, but may have side effects
*
* @generated from protobuf enum value: IDEMPOTENT = 2;
*/
IDEMPOTENT = 2
}
/**
* A message representing a option the parser does not recognize. This only
* appears in options protos created by the compiler::Parser class.
* DescriptorPool resolves these when building Descriptor objects. Therefore,
* options protos in descriptor objects (e.g. returned by Descriptor::options(),
* or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
* in them.
*
* @generated from protobuf message google.protobuf.UninterpretedOption
*/
export interface UninterpretedOption {
/**
* @generated from protobuf field: repeated google.protobuf.UninterpretedOption.NamePart name = 2;
*/
name: UninterpretedOption_NamePart[];
/**
* The value of the uninterpreted option, in whatever type the tokenizer
* identified it as during parsing. Exactly one of these should be set.
*
* @generated from protobuf field: optional string identifier_value = 3;
*/
identifierValue?: string;
/**
* @generated from protobuf field: optional uint64 positive_int_value = 4;
*/
positiveIntValue?: bigint;
/**
* @generated from protobuf field: optional int64 negative_int_value = 5;
*/
negativeIntValue?: bigint;
/**
* @generated from protobuf field: optional double double_value = 6;
*/
doubleValue?: number;
/**
* @generated from protobuf field: optional bytes string_value = 7;
*/
stringValue?: Uint8Array;
/**
* @generated from protobuf field: optional string aggregate_value = 8;
*/
aggregateValue?: string;
}
/**
* The name of the uninterpreted option. Each string represents a segment in
* a dot-separated name. is_extension is true iff a segment represents an
* extension (denoted with parentheses in options specs in .proto files).
* E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
* "foo.(bar.baz).qux".
*
* @generated from protobuf message google.protobuf.UninterpretedOption.NamePart
*/
export interface UninterpretedOption_NamePart {
/**
* @generated from protobuf field: string name_part = 1;
*/
namePart: string;
/**
* @generated from protobuf field: bool is_extension = 2;
*/
isExtension: boolean;
}
// ===================================================================
// Optional source code info
/**
* Encapsulates information about the original source file from which a
* FileDescriptorProto was generated.
*
* @generated from protobuf message google.protobuf.SourceCodeInfo
*/
export interface SourceCodeInfo {
/**
* A Location identifies a piece of source code in a .proto file which
* corresponds to a particular definition. This information is intended
* to be useful to IDEs, code indexers, documentation generators, and similar
* tools.
*
* For example, say we have a file like:
* message Foo {
* optional string foo = 1;
* }
* Let's look at just the field definition:
* optional string foo = 1;
* ^ ^^ ^^ ^ ^^^
* a bc de f ghi
* We have the following locations:
* span path represents
* [a,i) [ 4, 0, 2, 0 ] The whole field definition.
* [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
* [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
* [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
* [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
*
* Notes:
* - A location may refer to a repeated field itself (i.e. not to any
* particular index within it). This is used whenever a set of elements are
* logically enclosed in a single code segment. For example, an entire
* extend block (possibly containing multiple extension definitions) will
* have an outer location whose path refers to the "extensions" repeated
* field without an index.
* - Multiple locations may have the same path. This happens when a single
* logical declaration is spread out across multiple places. The most
* obvious example is the "extend" block again -- there may be multiple
* extend blocks in the same scope, each of which will have the same path.
* - A location's span is not always a subset of its parent's span. For
* example, the "extendee" of an extension declaration appears at the
* beginning of the "extend" block and is shared by all extensions within
* the block.
* - Just because a location's span is a subset of some other location's span
* does not mean that it is a descendant. For example, a "group" defines
* both a type and a field in a single declaration. Thus, the locations
* corresponding to the type and field and their components will overlap.
* - Code which tries to interpret locations should probably be designed to
* ignore those that it doesn't understand, as more types of locations could
* be recorded in the future.
*
* @generated from protobuf field: repeated google.protobuf.SourceCodeInfo.Location location = 1;
*/
location: SourceCodeInfo_Location[];
}
/**
* @generated from protobuf message google.protobuf.SourceCodeInfo.Location
*/
export interface SourceCodeInfo_Location {
/**
* Identifies which part of the FileDescriptorProto was defined at this
* location.
*
* Each element is a field number or an index. They form a path from
* the root FileDescriptorProto to the place where the definition. For
* example, this path:
* [ 4, 3, 2, 7, 1 ]
* refers to:
* file.message_type(3) // 4, 3
* .field(7) // 2, 7
* .name() // 1
* This is because FileDescriptorProto.message_type has field number 4:
* repeated DescriptorProto message_type = 4;
* and DescriptorProto.field has field number 2:
* repeated FieldDescriptorProto field = 2;
* and FieldDescriptorProto.name has field number 1:
* optional string name = 1;
*
* Thus, the above path gives the location of a field name. If we removed
* the last element:
* [ 4, 3, 2, 7 ]
* this path refers to the whole field declaration (from the beginning
* of the label to the terminating semicolon).
*
* @generated from protobuf field: repeated int32 path = 1 [packed = true];
*/
path: number[];
/**
* Always has exactly three or four elements: start line, start column,
* end line (optional, otherwise assumed same as start line), end column.
* These are packed into a single field for efficiency. Note that line
* and column numbers are zero-based -- typically you will want to add
* 1 to each before displaying to a user.
*
* @generated from protobuf field: repeated int32 span = 2 [packed = true];
*/
span: number[];
/**
* If this SourceCodeInfo represents a complete declaration, these are any
* comments appearing before and after the declaration which appear to be
* attached to the declaration.
*
* A series of line comments appearing on consecutive lines, with no other
* tokens appearing on those lines, will be treated as a single comment.
*
* leading_detached_comments will keep paragraphs of comments that appear
* before (but not connected to) the current element. Each paragraph,
* separated by empty lines, will be one comment element in the repeated
* field.
*
* Only the comment content is provided; comment markers (e.g. //) are
* stripped out. For block comments, leading whitespace and an asterisk
* will be stripped from the beginning of each line other than the first.
* Newlines are included in the output.
*
* Examples:
*
* optional int32 foo = 1; // Comment attached to foo.
* // Comment attached to bar.
* optional int32 bar = 2;
*
* optional string baz = 3;
* // Comment attached to baz.
* // Another line attached to baz.
*
* // Comment attached to qux.
* //
* // Another line attached to qux.
* optional double qux = 4;
*
* // Detached comment for corge. This is not leading or trailing comments
* // to qux or corge because there are blank lines separating it from
* // both.
*
* // Detached comment for corge paragraph 2.
*
* optional string corge = 5;
* /* Block comment attached
* * to corge. Leading asterisks
* * will be removed. *\/
* /* Block comment attached to
* * grault. *\/
* optional int32 grault = 6;
*
* // ignored detached comments.
*
* @generated from protobuf field: optional string leading_comments = 3;
*/
leadingComments?: string;
/**
* @generated from protobuf field: optional string trailing_comments = 4;
*/
trailingComments?: string;
/**
* @generated from protobuf field: repeated string leading_detached_comments = 6;
*/
leadingDetachedComments: string[];
}
/**
* Describes the relationship between generated code and its original source
* file. A GeneratedCodeInfo message is associated with only one generated
* source file, but may contain references to different source .proto files.
*
* @generated from protobuf message google.protobuf.GeneratedCodeInfo
*/
export interface GeneratedCodeInfo {
/**
* An Annotation connects some span of text in generated code to an element
* of its generating .proto file.
*
* @generated from protobuf field: repeated google.protobuf.GeneratedCodeInfo.Annotation annotation = 1;
*/
annotation: GeneratedCodeInfo_Annotation[];
}
/**
* @generated from protobuf message google.protobuf.GeneratedCodeInfo.Annotation
*/
export interface GeneratedCodeInfo_Annotation {
/**
* Identifies the element in the original source .proto file. This field
* is formatted the same as SourceCodeInfo.Location.path.
*
* @generated from protobuf field: repeated int32 path = 1 [packed = true];
*/
path: number[];
/**
* Identifies the filesystem path to the original source .proto.
*
* @generated from protobuf field: optional string source_file = 2;
*/
sourceFile?: string;
/**
* Identifies the starting offset in bytes in the generated code
* that relates to the identified object.
*
* @generated from protobuf field: optional int32 begin = 3;
*/
begin?: number;
/**
* Identifies the ending offset in bytes in the generated code that
* relates to the identified offset. The end offset should be one past
* the last relevant byte (so the length of the text = end - begin).
*
* @generated from protobuf field: optional int32 end = 4;
*/
end?: number;
}
// @generated message type with reflection information, may provide speed optimized methods
class FileDescriptorSet$Type extends MessageType<FileDescriptorSet> {
constructor() {
super("google.protobuf.FileDescriptorSet", [
{ no: 1, name: "file", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => FileDescriptorProto }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FileDescriptorSet): FileDescriptorSet {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* repeated google.protobuf.FileDescriptorProto file */ 1:
message.file.push(FileDescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: FileDescriptorSet, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* repeated google.protobuf.FileDescriptorProto file = 1; */
for (let i = 0; i < message.file.length; i++)
FileDescriptorProto.internalBinaryWrite(message.file[i], writer.tag(1, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.FileDescriptorSet
*/
export const FileDescriptorSet = new FileDescriptorSet$Type();
// @generated message type with reflection information, may provide speed optimized methods
class FileDescriptorProto$Type extends MessageType<FileDescriptorProto> {
constructor() {
super("google.protobuf.FileDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "package", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "dependency", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ },
{ no: 10, name: "public_dependency", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 5 /*ScalarType.INT32*/ },
{ no: 11, name: "weak_dependency", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 5 /*ScalarType.INT32*/ },
{ no: 4, name: "message_type", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => DescriptorProto },
{ no: 5, name: "enum_type", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => EnumDescriptorProto },
{ no: 6, name: "service", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => ServiceDescriptorProto },
{ no: 7, name: "extension", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => FieldDescriptorProto },
{ no: 8, name: "options", kind: "message", T: () => FileOptions },
{ no: 9, name: "source_code_info", kind: "message", T: () => SourceCodeInfo },
{ no: 12, name: "syntax", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FileDescriptorProto): FileDescriptorProto {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional string name */ 1:
message.name = reader.string();
break;
case /* optional string package */ 2:
message.package = reader.string();
break;
case /* repeated string dependency */ 3:
message.dependency.push(reader.string());
break;
case /* repeated int32 public_dependency */ 10:
if (wireType === WireType.LengthDelimited)
for (let e = reader.int32() + reader.pos; reader.pos < e;)
message.publicDependency.push(reader.int32());
else
message.publicDependency.push(reader.int32());
break;
case /* repeated int32 weak_dependency */ 11:
if (wireType === WireType.LengthDelimited)
for (let e = reader.int32() + reader.pos; reader.pos < e;)
message.weakDependency.push(reader.int32());
else
message.weakDependency.push(reader.int32());
break;
case /* repeated google.protobuf.DescriptorProto message_type */ 4:
message.messageType.push(DescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* repeated google.protobuf.EnumDescriptorProto enum_type */ 5:
message.enumType.push(EnumDescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* repeated google.protobuf.ServiceDescriptorProto service */ 6:
message.service.push(ServiceDescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* repeated google.protobuf.FieldDescriptorProto extension */ 7:
message.extension.push(FieldDescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* optional google.protobuf.FileOptions options */ 8:
message.options = FileOptions.internalBinaryRead(reader, reader.uint32(), options, message.options);
break;
case /* optional google.protobuf.SourceCodeInfo source_code_info */ 9:
message.sourceCodeInfo = SourceCodeInfo.internalBinaryRead(reader, reader.uint32(), options, message.sourceCodeInfo);
break;
case /* optional string syntax */ 12:
message.syntax = reader.string();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: FileDescriptorProto, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional string name = 1; */
if (message.name !== undefined)
writer.tag(1, WireType.LengthDelimited).string(message.name);
/* optional string package = 2; */
if (message.package !== undefined)
writer.tag(2, WireType.LengthDelimited).string(message.package);
/* repeated string dependency = 3; */
for (let i = 0; i < message.dependency.length; i++)
writer.tag(3, WireType.LengthDelimited).string(message.dependency[i]);
/* repeated int32 public_dependency = 10; */
for (let i = 0; i < message.publicDependency.length; i++)
writer.tag(10, WireType.Varint).int32(message.publicDependency[i]);
/* repeated int32 weak_dependency = 11; */
for (let i = 0; i < message.weakDependency.length; i++)
writer.tag(11, WireType.Varint).int32(message.weakDependency[i]);
/* repeated google.protobuf.DescriptorProto message_type = 4; */
for (let i = 0; i < message.messageType.length; i++)
DescriptorProto.internalBinaryWrite(message.messageType[i], writer.tag(4, WireType.LengthDelimited).fork(), options).join();
/* repeated google.protobuf.EnumDescriptorProto enum_type = 5; */
for (let i = 0; i < message.enumType.length; i++)
EnumDescriptorProto.internalBinaryWrite(message.enumType[i], writer.tag(5, WireType.LengthDelimited).fork(), options).join();
/* repeated google.protobuf.ServiceDescriptorProto service = 6; */
for (let i = 0; i < message.service.length; i++)
ServiceDescriptorProto.internalBinaryWrite(message.service[i], writer.tag(6, WireType.LengthDelimited).fork(), options).join();
/* repeated google.protobuf.FieldDescriptorProto extension = 7; */
for (let i = 0; i < message.extension.length; i++)
FieldDescriptorProto.internalBinaryWrite(message.extension[i], writer.tag(7, WireType.LengthDelimited).fork(), options).join();
/* optional google.protobuf.FileOptions options = 8; */
if (message.options)
FileOptions.internalBinaryWrite(message.options, writer.tag(8, WireType.LengthDelimited).fork(), options).join();
/* optional google.protobuf.SourceCodeInfo source_code_info = 9; */
if (message.sourceCodeInfo)
SourceCodeInfo.internalBinaryWrite(message.sourceCodeInfo, writer.tag(9, WireType.LengthDelimited).fork(), options).join();
/* optional string syntax = 12; */
if (message.syntax !== undefined)
writer.tag(12, WireType.LengthDelimited).string(message.syntax);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.FileDescriptorProto
*/
export const FileDescriptorProto = new FileDescriptorProto$Type();
// @generated message type with reflection information, may provide speed optimized methods
class DescriptorProto$Type extends MessageType<DescriptorProto> {
constructor() {
super("google.protobuf.DescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "field", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => FieldDescriptorProto },
{ no: 6, name: "extension", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => FieldDescriptorProto },
{ no: 3, name: "nested_type", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => DescriptorProto },
{ no: 4, name: "enum_type", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => EnumDescriptorProto },
{ no: 5, name: "extension_range", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => DescriptorProto_ExtensionRange },
{ no: 8, name: "oneof_decl", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => OneofDescriptorProto },
{ no: 7, name: "options", kind: "message", T: () => MessageOptions },
{ no: 9, name: "reserved_range", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => DescriptorProto_ReservedRange },
{ no: 10, name: "reserved_name", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: DescriptorProto): DescriptorProto {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional string name */ 1:
message.name = reader.string();
break;
case /* repeated google.protobuf.FieldDescriptorProto field */ 2:
message.field.push(FieldDescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* repeated google.protobuf.FieldDescriptorProto extension */ 6:
message.extension.push(FieldDescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* repeated google.protobuf.DescriptorProto nested_type */ 3:
message.nestedType.push(DescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* repeated google.protobuf.EnumDescriptorProto enum_type */ 4:
message.enumType.push(EnumDescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* repeated google.protobuf.DescriptorProto.ExtensionRange extension_range */ 5:
message.extensionRange.push(DescriptorProto_ExtensionRange.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* repeated google.protobuf.OneofDescriptorProto oneof_decl */ 8:
message.oneofDecl.push(OneofDescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* optional google.protobuf.MessageOptions options */ 7:
message.options = MessageOptions.internalBinaryRead(reader, reader.uint32(), options, message.options);
break;
case /* repeated google.protobuf.DescriptorProto.ReservedRange reserved_range */ 9:
message.reservedRange.push(DescriptorProto_ReservedRange.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* repeated string reserved_name */ 10:
message.reservedName.push(reader.string());
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: DescriptorProto, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional string name = 1; */
if (message.name !== undefined)
writer.tag(1, WireType.LengthDelimited).string(message.name);
/* repeated google.protobuf.FieldDescriptorProto field = 2; */
for (let i = 0; i < message.field.length; i++)
FieldDescriptorProto.internalBinaryWrite(message.field[i], writer.tag(2, WireType.LengthDelimited).fork(), options).join();
/* repeated google.protobuf.FieldDescriptorProto extension = 6; */
for (let i = 0; i < message.extension.length; i++)
FieldDescriptorProto.internalBinaryWrite(message.extension[i], writer.tag(6, WireType.LengthDelimited).fork(), options).join();
/* repeated google.protobuf.DescriptorProto nested_type = 3; */
for (let i = 0; i < message.nestedType.length; i++)
DescriptorProto.internalBinaryWrite(message.nestedType[i], writer.tag(3, WireType.LengthDelimited).fork(), options).join();
/* repeated google.protobuf.EnumDescriptorProto enum_type = 4; */
for (let i = 0; i < message.enumType.length; i++)
EnumDescriptorProto.internalBinaryWrite(message.enumType[i], writer.tag(4, WireType.LengthDelimited).fork(), options).join();
/* repeated google.protobuf.DescriptorProto.ExtensionRange extension_range = 5; */
for (let i = 0; i < message.extensionRange.length; i++)
DescriptorProto_ExtensionRange.internalBinaryWrite(message.extensionRange[i], writer.tag(5, WireType.LengthDelimited).fork(), options).join();
/* repeated google.protobuf.OneofDescriptorProto oneof_decl = 8; */
for (let i = 0; i < message.oneofDecl.length; i++)
OneofDescriptorProto.internalBinaryWrite(message.oneofDecl[i], writer.tag(8, WireType.LengthDelimited).fork(), options).join();
/* optional google.protobuf.MessageOptions options = 7; */
if (message.options)
MessageOptions.internalBinaryWrite(message.options, writer.tag(7, WireType.LengthDelimited).fork(), options).join();
/* repeated google.protobuf.DescriptorProto.ReservedRange reserved_range = 9; */
for (let i = 0; i < message.reservedRange.length; i++)
DescriptorProto_ReservedRange.internalBinaryWrite(message.reservedRange[i], writer.tag(9, WireType.LengthDelimited).fork(), options).join();
/* repeated string reserved_name = 10; */
for (let i = 0; i < message.reservedName.length; i++)
writer.tag(10, WireType.LengthDelimited).string(message.reservedName[i]);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.DescriptorProto
*/
export const DescriptorProto = new DescriptorProto$Type();
// @generated message type with reflection information, may provide speed optimized methods
class DescriptorProto_ExtensionRange$Type extends MessageType<DescriptorProto_ExtensionRange> {
constructor() {
super("google.protobuf.DescriptorProto.ExtensionRange", [
{ no: 1, name: "start", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ },
{ no: 2, name: "end", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ },
{ no: 3, name: "options", kind: "message", T: () => ExtensionRangeOptions }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: DescriptorProto_ExtensionRange): DescriptorProto_ExtensionRange {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional int32 start */ 1:
message.start = reader.int32();
break;
case /* optional int32 end */ 2:
message.end = reader.int32();
break;
case /* optional google.protobuf.ExtensionRangeOptions options */ 3:
message.options = ExtensionRangeOptions.internalBinaryRead(reader, reader.uint32(), options, message.options);
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: DescriptorProto_ExtensionRange, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional int32 start = 1; */
if (message.start !== undefined)
writer.tag(1, WireType.Varint).int32(message.start);
/* optional int32 end = 2; */
if (message.end !== undefined)
writer.tag(2, WireType.Varint).int32(message.end);
/* optional google.protobuf.ExtensionRangeOptions options = 3; */
if (message.options)
ExtensionRangeOptions.internalBinaryWrite(message.options, writer.tag(3, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.DescriptorProto.ExtensionRange
*/
export const DescriptorProto_ExtensionRange = new DescriptorProto_ExtensionRange$Type();
// @generated message type with reflection information, may provide speed optimized methods
class DescriptorProto_ReservedRange$Type extends MessageType<DescriptorProto_ReservedRange> {
constructor() {
super("google.protobuf.DescriptorProto.ReservedRange", [
{ no: 1, name: "start", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ },
{ no: 2, name: "end", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: DescriptorProto_ReservedRange): DescriptorProto_ReservedRange {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional int32 start */ 1:
message.start = reader.int32();
break;
case /* optional int32 end */ 2:
message.end = reader.int32();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: DescriptorProto_ReservedRange, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional int32 start = 1; */
if (message.start !== undefined)
writer.tag(1, WireType.Varint).int32(message.start);
/* optional int32 end = 2; */
if (message.end !== undefined)
writer.tag(2, WireType.Varint).int32(message.end);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.DescriptorProto.ReservedRange
*/
export const DescriptorProto_ReservedRange = new DescriptorProto_ReservedRange$Type();
// @generated message type with reflection information, may provide speed optimized methods
class ExtensionRangeOptions$Type extends MessageType<ExtensionRangeOptions> {
constructor() {
super("google.protobuf.ExtensionRangeOptions", [
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => UninterpretedOption }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ExtensionRangeOptions): ExtensionRangeOptions {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* repeated google.protobuf.UninterpretedOption uninterpreted_option */ 999:
message.uninterpretedOption.push(UninterpretedOption.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: ExtensionRangeOptions, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* repeated google.protobuf.UninterpretedOption uninterpreted_option = 999; */
for (let i = 0; i < message.uninterpretedOption.length; i++)
UninterpretedOption.internalBinaryWrite(message.uninterpretedOption[i], writer.tag(999, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.ExtensionRangeOptions
*/
export const ExtensionRangeOptions = new ExtensionRangeOptions$Type();
// @generated message type with reflection information, may provide speed optimized methods
class FieldDescriptorProto$Type extends MessageType<FieldDescriptorProto> {
constructor() {
super("google.protobuf.FieldDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "number", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ },
{ no: 4, name: "label", kind: "enum", opt: true, T: () => ["google.protobuf.FieldDescriptorProto.Label", FieldDescriptorProto_Label, "LABEL_"] },
{ no: 5, name: "type", kind: "enum", opt: true, T: () => ["google.protobuf.FieldDescriptorProto.Type", FieldDescriptorProto_Type, "TYPE_"] },
{ no: 6, name: "type_name", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "extendee", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 7, name: "default_value", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 9, name: "oneof_index", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ },
{ no: 10, name: "json_name", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 8, name: "options", kind: "message", T: () => FieldOptions },
{ no: 17, name: "proto3_optional", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FieldDescriptorProto): FieldDescriptorProto {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional string name */ 1:
message.name = reader.string();
break;
case /* optional int32 number */ 3:
message.number = reader.int32();
break;
case /* optional google.protobuf.FieldDescriptorProto.Label label */ 4:
message.label = reader.int32();
break;
case /* optional google.protobuf.FieldDescriptorProto.Type type */ 5:
message.type = reader.int32();
break;
case /* optional string type_name */ 6:
message.typeName = reader.string();
break;
case /* optional string extendee */ 2:
message.extendee = reader.string();
break;
case /* optional string default_value */ 7:
message.defaultValue = reader.string();
break;
case /* optional int32 oneof_index */ 9:
message.oneofIndex = reader.int32();
break;
case /* optional string json_name */ 10:
message.jsonName = reader.string();
break;
case /* optional google.protobuf.FieldOptions options */ 8:
message.options = FieldOptions.internalBinaryRead(reader, reader.uint32(), options, message.options);
break;
case /* optional bool proto3_optional */ 17:
message.proto3Optional = reader.bool();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: FieldDescriptorProto, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional string name = 1; */
if (message.name !== undefined)
writer.tag(1, WireType.LengthDelimited).string(message.name);
/* optional int32 number = 3; */
if (message.number !== undefined)
writer.tag(3, WireType.Varint).int32(message.number);
/* optional google.protobuf.FieldDescriptorProto.Label label = 4; */
if (message.label !== undefined)
writer.tag(4, WireType.Varint).int32(message.label);
/* optional google.protobuf.FieldDescriptorProto.Type type = 5; */
if (message.type !== undefined)
writer.tag(5, WireType.Varint).int32(message.type);
/* optional string type_name = 6; */
if (message.typeName !== undefined)
writer.tag(6, WireType.LengthDelimited).string(message.typeName);
/* optional string extendee = 2; */
if (message.extendee !== undefined)
writer.tag(2, WireType.LengthDelimited).string(message.extendee);
/* optional string default_value = 7; */
if (message.defaultValue !== undefined)
writer.tag(7, WireType.LengthDelimited).string(message.defaultValue);
/* optional int32 oneof_index = 9; */
if (message.oneofIndex !== undefined)
writer.tag(9, WireType.Varint).int32(message.oneofIndex);
/* optional string json_name = 10; */
if (message.jsonName !== undefined)
writer.tag(10, WireType.LengthDelimited).string(message.jsonName);
/* optional google.protobuf.FieldOptions options = 8; */
if (message.options)
FieldOptions.internalBinaryWrite(message.options, writer.tag(8, WireType.LengthDelimited).fork(), options).join();
/* optional bool proto3_optional = 17; */
if (message.proto3Optional !== undefined)
writer.tag(17, WireType.Varint).bool(message.proto3Optional);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.FieldDescriptorProto
*/
export const FieldDescriptorProto = new FieldDescriptorProto$Type();
// @generated message type with reflection information, may provide speed optimized methods
class OneofDescriptorProto$Type extends MessageType<OneofDescriptorProto> {
constructor() {
super("google.protobuf.OneofDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "options", kind: "message", T: () => OneofOptions }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: OneofDescriptorProto): OneofDescriptorProto {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional string name */ 1:
message.name = reader.string();
break;
case /* optional google.protobuf.OneofOptions options */ 2:
message.options = OneofOptions.internalBinaryRead(reader, reader.uint32(), options, message.options);
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: OneofDescriptorProto, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional string name = 1; */
if (message.name !== undefined)
writer.tag(1, WireType.LengthDelimited).string(message.name);
/* optional google.protobuf.OneofOptions options = 2; */
if (message.options)
OneofOptions.internalBinaryWrite(message.options, writer.tag(2, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.OneofDescriptorProto
*/
export const OneofDescriptorProto = new OneofDescriptorProto$Type();
// @generated message type with reflection information, may provide speed optimized methods
class EnumDescriptorProto$Type extends MessageType<EnumDescriptorProto> {
constructor() {
super("google.protobuf.EnumDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "value", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => EnumValueDescriptorProto },
{ no: 3, name: "options", kind: "message", T: () => EnumOptions },
{ no: 4, name: "reserved_range", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => EnumDescriptorProto_EnumReservedRange },
{ no: 5, name: "reserved_name", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: EnumDescriptorProto): EnumDescriptorProto {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional string name */ 1:
message.name = reader.string();
break;
case /* repeated google.protobuf.EnumValueDescriptorProto value */ 2:
message.value.push(EnumValueDescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* optional google.protobuf.EnumOptions options */ 3:
message.options = EnumOptions.internalBinaryRead(reader, reader.uint32(), options, message.options);
break;
case /* repeated google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range */ 4:
message.reservedRange.push(EnumDescriptorProto_EnumReservedRange.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* repeated string reserved_name */ 5:
message.reservedName.push(reader.string());
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: EnumDescriptorProto, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional string name = 1; */
if (message.name !== undefined)
writer.tag(1, WireType.LengthDelimited).string(message.name);
/* repeated google.protobuf.EnumValueDescriptorProto value = 2; */
for (let i = 0; i < message.value.length; i++)
EnumValueDescriptorProto.internalBinaryWrite(message.value[i], writer.tag(2, WireType.LengthDelimited).fork(), options).join();
/* optional google.protobuf.EnumOptions options = 3; */
if (message.options)
EnumOptions.internalBinaryWrite(message.options, writer.tag(3, WireType.LengthDelimited).fork(), options).join();
/* repeated google.protobuf.EnumDescriptorProto.EnumReservedRange reserved_range = 4; */
for (let i = 0; i < message.reservedRange.length; i++)
EnumDescriptorProto_EnumReservedRange.internalBinaryWrite(message.reservedRange[i], writer.tag(4, WireType.LengthDelimited).fork(), options).join();
/* repeated string reserved_name = 5; */
for (let i = 0; i < message.reservedName.length; i++)
writer.tag(5, WireType.LengthDelimited).string(message.reservedName[i]);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.EnumDescriptorProto
*/
export const EnumDescriptorProto = new EnumDescriptorProto$Type();
// @generated message type with reflection information, may provide speed optimized methods
class EnumDescriptorProto_EnumReservedRange$Type extends MessageType<EnumDescriptorProto_EnumReservedRange> {
constructor() {
super("google.protobuf.EnumDescriptorProto.EnumReservedRange", [
{ no: 1, name: "start", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ },
{ no: 2, name: "end", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: EnumDescriptorProto_EnumReservedRange): EnumDescriptorProto_EnumReservedRange {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional int32 start */ 1:
message.start = reader.int32();
break;
case /* optional int32 end */ 2:
message.end = reader.int32();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: EnumDescriptorProto_EnumReservedRange, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional int32 start = 1; */
if (message.start !== undefined)
writer.tag(1, WireType.Varint).int32(message.start);
/* optional int32 end = 2; */
if (message.end !== undefined)
writer.tag(2, WireType.Varint).int32(message.end);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.EnumDescriptorProto.EnumReservedRange
*/
export const EnumDescriptorProto_EnumReservedRange = new EnumDescriptorProto_EnumReservedRange$Type();
// @generated message type with reflection information, may provide speed optimized methods
class EnumValueDescriptorProto$Type extends MessageType<EnumValueDescriptorProto> {
constructor() {
super("google.protobuf.EnumValueDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "number", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ },
{ no: 3, name: "options", kind: "message", T: () => EnumValueOptions }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: EnumValueDescriptorProto): EnumValueDescriptorProto {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional string name */ 1:
message.name = reader.string();
break;
case /* optional int32 number */ 2:
message.number = reader.int32();
break;
case /* optional google.protobuf.EnumValueOptions options */ 3:
message.options = EnumValueOptions.internalBinaryRead(reader, reader.uint32(), options, message.options);
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: EnumValueDescriptorProto, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional string name = 1; */
if (message.name !== undefined)
writer.tag(1, WireType.LengthDelimited).string(message.name);
/* optional int32 number = 2; */
if (message.number !== undefined)
writer.tag(2, WireType.Varint).int32(message.number);
/* optional google.protobuf.EnumValueOptions options = 3; */
if (message.options)
EnumValueOptions.internalBinaryWrite(message.options, writer.tag(3, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.EnumValueDescriptorProto
*/
export const EnumValueDescriptorProto = new EnumValueDescriptorProto$Type();
// @generated message type with reflection information, may provide speed optimized methods
class ServiceDescriptorProto$Type extends MessageType<ServiceDescriptorProto> {
constructor() {
super("google.protobuf.ServiceDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "method", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => MethodDescriptorProto },
{ no: 3, name: "options", kind: "message", T: () => ServiceOptions }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ServiceDescriptorProto): ServiceDescriptorProto {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional string name */ 1:
message.name = reader.string();
break;
case /* repeated google.protobuf.MethodDescriptorProto method */ 2:
message.method.push(MethodDescriptorProto.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* optional google.protobuf.ServiceOptions options */ 3:
message.options = ServiceOptions.internalBinaryRead(reader, reader.uint32(), options, message.options);
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: ServiceDescriptorProto, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional string name = 1; */
if (message.name !== undefined)
writer.tag(1, WireType.LengthDelimited).string(message.name);
/* repeated google.protobuf.MethodDescriptorProto method = 2; */
for (let i = 0; i < message.method.length; i++)
MethodDescriptorProto.internalBinaryWrite(message.method[i], writer.tag(2, WireType.LengthDelimited).fork(), options).join();
/* optional google.protobuf.ServiceOptions options = 3; */
if (message.options)
ServiceOptions.internalBinaryWrite(message.options, writer.tag(3, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.ServiceDescriptorProto
*/
export const ServiceDescriptorProto = new ServiceDescriptorProto$Type();
// @generated message type with reflection information, may provide speed optimized methods
class MethodDescriptorProto$Type extends MessageType<MethodDescriptorProto> {
constructor() {
super("google.protobuf.MethodDescriptorProto", [
{ no: 1, name: "name", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "input_type", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "output_type", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 4, name: "options", kind: "message", T: () => MethodOptions },
{ no: 5, name: "client_streaming", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 6, name: "server_streaming", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: MethodDescriptorProto): MethodDescriptorProto {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional string name */ 1:
message.name = reader.string();
break;
case /* optional string input_type */ 2:
message.inputType = reader.string();
break;
case /* optional string output_type */ 3:
message.outputType = reader.string();
break;
case /* optional google.protobuf.MethodOptions options */ 4:
message.options = MethodOptions.internalBinaryRead(reader, reader.uint32(), options, message.options);
break;
case /* optional bool client_streaming */ 5:
message.clientStreaming = reader.bool();
break;
case /* optional bool server_streaming */ 6:
message.serverStreaming = reader.bool();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: MethodDescriptorProto, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional string name = 1; */
if (message.name !== undefined)
writer.tag(1, WireType.LengthDelimited).string(message.name);
/* optional string input_type = 2; */
if (message.inputType !== undefined)
writer.tag(2, WireType.LengthDelimited).string(message.inputType);
/* optional string output_type = 3; */
if (message.outputType !== undefined)
writer.tag(3, WireType.LengthDelimited).string(message.outputType);
/* optional google.protobuf.MethodOptions options = 4; */
if (message.options)
MethodOptions.internalBinaryWrite(message.options, writer.tag(4, WireType.LengthDelimited).fork(), options).join();
/* optional bool client_streaming = 5; */
if (message.clientStreaming !== undefined)
writer.tag(5, WireType.Varint).bool(message.clientStreaming);
/* optional bool server_streaming = 6; */
if (message.serverStreaming !== undefined)
writer.tag(6, WireType.Varint).bool(message.serverStreaming);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.MethodDescriptorProto
*/
export const MethodDescriptorProto = new MethodDescriptorProto$Type();
// @generated message type with reflection information, may provide speed optimized methods
class FileOptions$Type extends MessageType<FileOptions> {
constructor() {
super("google.protobuf.FileOptions", [
{ no: 1, name: "java_package", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 8, name: "java_outer_classname", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 10, name: "java_multiple_files", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 20, name: "java_generate_equals_and_hash", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 27, name: "java_string_check_utf8", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 9, name: "optimize_for", kind: "enum", opt: true, T: () => ["google.protobuf.FileOptions.OptimizeMode", FileOptions_OptimizeMode] },
{ no: 11, name: "go_package", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 16, name: "cc_generic_services", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 17, name: "java_generic_services", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 18, name: "py_generic_services", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 42, name: "php_generic_services", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 23, name: "deprecated", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 31, name: "cc_enable_arenas", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 36, name: "objc_class_prefix", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 37, name: "csharp_namespace", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 39, name: "swift_prefix", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 40, name: "php_class_prefix", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 41, name: "php_namespace", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 44, name: "php_metadata_namespace", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 45, name: "ruby_package", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => UninterpretedOption }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FileOptions): FileOptions {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional string java_package */ 1:
message.javaPackage = reader.string();
break;
case /* optional string java_outer_classname */ 8:
message.javaOuterClassname = reader.string();
break;
case /* optional bool java_multiple_files */ 10:
message.javaMultipleFiles = reader.bool();
break;
case /* optional bool java_generate_equals_and_hash = 20 [deprecated = true];*/ 20:
message.javaGenerateEqualsAndHash = reader.bool();
break;
case /* optional bool java_string_check_utf8 */ 27:
message.javaStringCheckUtf8 = reader.bool();
break;
case /* optional google.protobuf.FileOptions.OptimizeMode optimize_for */ 9:
message.optimizeFor = reader.int32();
break;
case /* optional string go_package */ 11:
message.goPackage = reader.string();
break;
case /* optional bool cc_generic_services */ 16:
message.ccGenericServices = reader.bool();
break;
case /* optional bool java_generic_services */ 17:
message.javaGenericServices = reader.bool();
break;
case /* optional bool py_generic_services */ 18:
message.pyGenericServices = reader.bool();
break;
case /* optional bool php_generic_services */ 42:
message.phpGenericServices = reader.bool();
break;
case /* optional bool deprecated */ 23:
message.deprecated = reader.bool();
break;
case /* optional bool cc_enable_arenas */ 31:
message.ccEnableArenas = reader.bool();
break;
case /* optional string objc_class_prefix */ 36:
message.objcClassPrefix = reader.string();
break;
case /* optional string csharp_namespace */ 37:
message.csharpNamespace = reader.string();
break;
case /* optional string swift_prefix */ 39:
message.swiftPrefix = reader.string();
break;
case /* optional string php_class_prefix */ 40:
message.phpClassPrefix = reader.string();
break;
case /* optional string php_namespace */ 41:
message.phpNamespace = reader.string();
break;
case /* optional string php_metadata_namespace */ 44:
message.phpMetadataNamespace = reader.string();
break;
case /* optional string ruby_package */ 45:
message.rubyPackage = reader.string();
break;
case /* repeated google.protobuf.UninterpretedOption uninterpreted_option */ 999:
message.uninterpretedOption.push(UninterpretedOption.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: FileOptions, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional string java_package = 1; */
if (message.javaPackage !== undefined)
writer.tag(1, WireType.LengthDelimited).string(message.javaPackage);
/* optional string java_outer_classname = 8; */
if (message.javaOuterClassname !== undefined)
writer.tag(8, WireType.LengthDelimited).string(message.javaOuterClassname);
/* optional bool java_multiple_files = 10; */
if (message.javaMultipleFiles !== undefined)
writer.tag(10, WireType.Varint).bool(message.javaMultipleFiles);
/* optional bool java_generate_equals_and_hash = 20 [deprecated = true]; */
if (message.javaGenerateEqualsAndHash !== undefined)
writer.tag(20, WireType.Varint).bool(message.javaGenerateEqualsAndHash);
/* optional bool java_string_check_utf8 = 27; */
if (message.javaStringCheckUtf8 !== undefined)
writer.tag(27, WireType.Varint).bool(message.javaStringCheckUtf8);
/* optional google.protobuf.FileOptions.OptimizeMode optimize_for = 9; */
if (message.optimizeFor !== undefined)
writer.tag(9, WireType.Varint).int32(message.optimizeFor);
/* optional string go_package = 11; */
if (message.goPackage !== undefined)
writer.tag(11, WireType.LengthDelimited).string(message.goPackage);
/* optional bool cc_generic_services = 16; */
if (message.ccGenericServices !== undefined)
writer.tag(16, WireType.Varint).bool(message.ccGenericServices);
/* optional bool java_generic_services = 17; */
if (message.javaGenericServices !== undefined)
writer.tag(17, WireType.Varint).bool(message.javaGenericServices);
/* optional bool py_generic_services = 18; */
if (message.pyGenericServices !== undefined)
writer.tag(18, WireType.Varint).bool(message.pyGenericServices);
/* optional bool php_generic_services = 42; */
if (message.phpGenericServices !== undefined)
writer.tag(42, WireType.Varint).bool(message.phpGenericServices);
/* optional bool deprecated = 23; */
if (message.deprecated !== undefined)
writer.tag(23, WireType.Varint).bool(message.deprecated);
/* optional bool cc_enable_arenas = 31; */
if (message.ccEnableArenas !== undefined)
writer.tag(31, WireType.Varint).bool(message.ccEnableArenas);
/* optional string objc_class_prefix = 36; */
if (message.objcClassPrefix !== undefined)
writer.tag(36, WireType.LengthDelimited).string(message.objcClassPrefix);
/* optional string csharp_namespace = 37; */
if (message.csharpNamespace !== undefined)
writer.tag(37, WireType.LengthDelimited).string(message.csharpNamespace);
/* optional string swift_prefix = 39; */
if (message.swiftPrefix !== undefined)
writer.tag(39, WireType.LengthDelimited).string(message.swiftPrefix);
/* optional string php_class_prefix = 40; */
if (message.phpClassPrefix !== undefined)
writer.tag(40, WireType.LengthDelimited).string(message.phpClassPrefix);
/* optional string php_namespace = 41; */
if (message.phpNamespace !== undefined)
writer.tag(41, WireType.LengthDelimited).string(message.phpNamespace);
/* optional string php_metadata_namespace = 44; */
if (message.phpMetadataNamespace !== undefined)
writer.tag(44, WireType.LengthDelimited).string(message.phpMetadataNamespace);
/* optional string ruby_package = 45; */
if (message.rubyPackage !== undefined)
writer.tag(45, WireType.LengthDelimited).string(message.rubyPackage);
/* repeated google.protobuf.UninterpretedOption uninterpreted_option = 999; */
for (let i = 0; i < message.uninterpretedOption.length; i++)
UninterpretedOption.internalBinaryWrite(message.uninterpretedOption[i], writer.tag(999, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.FileOptions
*/
export const FileOptions = new FileOptions$Type();
// @generated message type with reflection information, may provide speed optimized methods
class MessageOptions$Type extends MessageType<MessageOptions> {
constructor() {
super("google.protobuf.MessageOptions", [
{ no: 1, name: "message_set_wire_format", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 2, name: "no_standard_descriptor_accessor", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 3, name: "deprecated", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 7, name: "map_entry", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => UninterpretedOption }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: MessageOptions): MessageOptions {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional bool message_set_wire_format */ 1:
message.messageSetWireFormat = reader.bool();
break;
case /* optional bool no_standard_descriptor_accessor */ 2:
message.noStandardDescriptorAccessor = reader.bool();
break;
case /* optional bool deprecated */ 3:
message.deprecated = reader.bool();
break;
case /* optional bool map_entry */ 7:
message.mapEntry = reader.bool();
break;
case /* repeated google.protobuf.UninterpretedOption uninterpreted_option */ 999:
message.uninterpretedOption.push(UninterpretedOption.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: MessageOptions, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional bool message_set_wire_format = 1; */
if (message.messageSetWireFormat !== undefined)
writer.tag(1, WireType.Varint).bool(message.messageSetWireFormat);
/* optional bool no_standard_descriptor_accessor = 2; */
if (message.noStandardDescriptorAccessor !== undefined)
writer.tag(2, WireType.Varint).bool(message.noStandardDescriptorAccessor);
/* optional bool deprecated = 3; */
if (message.deprecated !== undefined)
writer.tag(3, WireType.Varint).bool(message.deprecated);
/* optional bool map_entry = 7; */
if (message.mapEntry !== undefined)
writer.tag(7, WireType.Varint).bool(message.mapEntry);
/* repeated google.protobuf.UninterpretedOption uninterpreted_option = 999; */
for (let i = 0; i < message.uninterpretedOption.length; i++)
UninterpretedOption.internalBinaryWrite(message.uninterpretedOption[i], writer.tag(999, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.MessageOptions
*/
export const MessageOptions = new MessageOptions$Type();
// @generated message type with reflection information, may provide speed optimized methods
class FieldOptions$Type extends MessageType<FieldOptions> {
constructor() {
super("google.protobuf.FieldOptions", [
{ no: 1, name: "ctype", kind: "enum", opt: true, T: () => ["google.protobuf.FieldOptions.CType", FieldOptions_CType] },
{ no: 2, name: "packed", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 6, name: "jstype", kind: "enum", opt: true, T: () => ["google.protobuf.FieldOptions.JSType", FieldOptions_JSType] },
{ no: 5, name: "lazy", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 3, name: "deprecated", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 10, name: "weak", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => UninterpretedOption }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: FieldOptions): FieldOptions {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional google.protobuf.FieldOptions.CType ctype */ 1:
message.ctype = reader.int32();
break;
case /* optional bool packed */ 2:
message.packed = reader.bool();
break;
case /* optional google.protobuf.FieldOptions.JSType jstype */ 6:
message.jstype = reader.int32();
break;
case /* optional bool lazy */ 5:
message.lazy = reader.bool();
break;
case /* optional bool deprecated */ 3:
message.deprecated = reader.bool();
break;
case /* optional bool weak */ 10:
message.weak = reader.bool();
break;
case /* repeated google.protobuf.UninterpretedOption uninterpreted_option */ 999:
message.uninterpretedOption.push(UninterpretedOption.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: FieldOptions, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional google.protobuf.FieldOptions.CType ctype = 1; */
if (message.ctype !== undefined)
writer.tag(1, WireType.Varint).int32(message.ctype);
/* optional bool packed = 2; */
if (message.packed !== undefined)
writer.tag(2, WireType.Varint).bool(message.packed);
/* optional google.protobuf.FieldOptions.JSType jstype = 6; */
if (message.jstype !== undefined)
writer.tag(6, WireType.Varint).int32(message.jstype);
/* optional bool lazy = 5; */
if (message.lazy !== undefined)
writer.tag(5, WireType.Varint).bool(message.lazy);
/* optional bool deprecated = 3; */
if (message.deprecated !== undefined)
writer.tag(3, WireType.Varint).bool(message.deprecated);
/* optional bool weak = 10; */
if (message.weak !== undefined)
writer.tag(10, WireType.Varint).bool(message.weak);
/* repeated google.protobuf.UninterpretedOption uninterpreted_option = 999; */
for (let i = 0; i < message.uninterpretedOption.length; i++)
UninterpretedOption.internalBinaryWrite(message.uninterpretedOption[i], writer.tag(999, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.FieldOptions
*/
export const FieldOptions = new FieldOptions$Type();
// @generated message type with reflection information, may provide speed optimized methods
class OneofOptions$Type extends MessageType<OneofOptions> {
constructor() {
super("google.protobuf.OneofOptions", [
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => UninterpretedOption }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: OneofOptions): OneofOptions {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* repeated google.protobuf.UninterpretedOption uninterpreted_option */ 999:
message.uninterpretedOption.push(UninterpretedOption.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: OneofOptions, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* repeated google.protobuf.UninterpretedOption uninterpreted_option = 999; */
for (let i = 0; i < message.uninterpretedOption.length; i++)
UninterpretedOption.internalBinaryWrite(message.uninterpretedOption[i], writer.tag(999, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.OneofOptions
*/
export const OneofOptions = new OneofOptions$Type();
// @generated message type with reflection information, may provide speed optimized methods
class EnumOptions$Type extends MessageType<EnumOptions> {
constructor() {
super("google.protobuf.EnumOptions", [
{ no: 2, name: "allow_alias", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 3, name: "deprecated", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => UninterpretedOption }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: EnumOptions): EnumOptions {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional bool allow_alias */ 2:
message.allowAlias = reader.bool();
break;
case /* optional bool deprecated */ 3:
message.deprecated = reader.bool();
break;
case /* repeated google.protobuf.UninterpretedOption uninterpreted_option */ 999:
message.uninterpretedOption.push(UninterpretedOption.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: EnumOptions, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional bool allow_alias = 2; */
if (message.allowAlias !== undefined)
writer.tag(2, WireType.Varint).bool(message.allowAlias);
/* optional bool deprecated = 3; */
if (message.deprecated !== undefined)
writer.tag(3, WireType.Varint).bool(message.deprecated);
/* repeated google.protobuf.UninterpretedOption uninterpreted_option = 999; */
for (let i = 0; i < message.uninterpretedOption.length; i++)
UninterpretedOption.internalBinaryWrite(message.uninterpretedOption[i], writer.tag(999, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.EnumOptions
*/
export const EnumOptions = new EnumOptions$Type();
// @generated message type with reflection information, may provide speed optimized methods
class EnumValueOptions$Type extends MessageType<EnumValueOptions> {
constructor() {
super("google.protobuf.EnumValueOptions", [
{ no: 1, name: "deprecated", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => UninterpretedOption }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: EnumValueOptions): EnumValueOptions {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional bool deprecated */ 1:
message.deprecated = reader.bool();
break;
case /* repeated google.protobuf.UninterpretedOption uninterpreted_option */ 999:
message.uninterpretedOption.push(UninterpretedOption.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: EnumValueOptions, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional bool deprecated = 1; */
if (message.deprecated !== undefined)
writer.tag(1, WireType.Varint).bool(message.deprecated);
/* repeated google.protobuf.UninterpretedOption uninterpreted_option = 999; */
for (let i = 0; i < message.uninterpretedOption.length; i++)
UninterpretedOption.internalBinaryWrite(message.uninterpretedOption[i], writer.tag(999, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.EnumValueOptions
*/
export const EnumValueOptions = new EnumValueOptions$Type();
// @generated message type with reflection information, may provide speed optimized methods
class ServiceOptions$Type extends MessageType<ServiceOptions> {
constructor() {
super("google.protobuf.ServiceOptions", [
{ no: 33, name: "deprecated", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => UninterpretedOption }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: ServiceOptions): ServiceOptions {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional bool deprecated */ 33:
message.deprecated = reader.bool();
break;
case /* repeated google.protobuf.UninterpretedOption uninterpreted_option */ 999:
message.uninterpretedOption.push(UninterpretedOption.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: ServiceOptions, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional bool deprecated = 33; */
if (message.deprecated !== undefined)
writer.tag(33, WireType.Varint).bool(message.deprecated);
/* repeated google.protobuf.UninterpretedOption uninterpreted_option = 999; */
for (let i = 0; i < message.uninterpretedOption.length; i++)
UninterpretedOption.internalBinaryWrite(message.uninterpretedOption[i], writer.tag(999, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.ServiceOptions
*/
export const ServiceOptions = new ServiceOptions$Type();
// @generated message type with reflection information, may provide speed optimized methods
class MethodOptions$Type extends MessageType<MethodOptions> {
constructor() {
super("google.protobuf.MethodOptions", [
{ no: 33, name: "deprecated", kind: "scalar", opt: true, T: 8 /*ScalarType.BOOL*/ },
{ no: 34, name: "idempotency_level", kind: "enum", opt: true, T: () => ["google.protobuf.MethodOptions.IdempotencyLevel", MethodOptions_IdempotencyLevel] },
{ no: 999, name: "uninterpreted_option", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => UninterpretedOption }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: MethodOptions): MethodOptions {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* optional bool deprecated */ 33:
message.deprecated = reader.bool();
break;
case /* optional google.protobuf.MethodOptions.IdempotencyLevel idempotency_level */ 34:
message.idempotencyLevel = reader.int32();
break;
case /* repeated google.protobuf.UninterpretedOption uninterpreted_option */ 999:
message.uninterpretedOption.push(UninterpretedOption.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: MethodOptions, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* optional bool deprecated = 33; */
if (message.deprecated !== undefined)
writer.tag(33, WireType.Varint).bool(message.deprecated);
/* optional google.protobuf.MethodOptions.IdempotencyLevel idempotency_level = 34; */
if (message.idempotencyLevel !== undefined)
writer.tag(34, WireType.Varint).int32(message.idempotencyLevel);
/* repeated google.protobuf.UninterpretedOption uninterpreted_option = 999; */
for (let i = 0; i < message.uninterpretedOption.length; i++)
UninterpretedOption.internalBinaryWrite(message.uninterpretedOption[i], writer.tag(999, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.MethodOptions
*/
export const MethodOptions = new MethodOptions$Type();
// @generated message type with reflection information, may provide speed optimized methods
class UninterpretedOption$Type extends MessageType<UninterpretedOption> {
constructor() {
super("google.protobuf.UninterpretedOption", [
{ no: 2, name: "name", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => UninterpretedOption_NamePart },
{ no: 3, name: "identifier_value", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 4, name: "positive_int_value", kind: "scalar", opt: true, T: 4 /*ScalarType.UINT64*/, L: 0 /*LongType.BIGINT*/ },
{ no: 5, name: "negative_int_value", kind: "scalar", opt: true, T: 3 /*ScalarType.INT64*/, L: 0 /*LongType.BIGINT*/ },
{ no: 6, name: "double_value", kind: "scalar", opt: true, T: 1 /*ScalarType.DOUBLE*/ },
{ no: 7, name: "string_value", kind: "scalar", opt: true, T: 12 /*ScalarType.BYTES*/ },
{ no: 8, name: "aggregate_value", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: UninterpretedOption): UninterpretedOption {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* repeated google.protobuf.UninterpretedOption.NamePart name */ 2:
message.name.push(UninterpretedOption_NamePart.internalBinaryRead(reader, reader.uint32(), options));
break;
case /* optional string identifier_value */ 3:
message.identifierValue = reader.string();
break;
case /* optional uint64 positive_int_value */ 4:
message.positiveIntValue = reader.uint64().toBigInt();
break;
case /* optional int64 negative_int_value */ 5:
message.negativeIntValue = reader.int64().toBigInt();
break;
case /* optional double double_value */ 6:
message.doubleValue = reader.double();
break;
case /* optional bytes string_value */ 7:
message.stringValue = reader.bytes();
break;
case /* optional string aggregate_value */ 8:
message.aggregateValue = reader.string();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: UninterpretedOption, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* repeated google.protobuf.UninterpretedOption.NamePart name = 2; */
for (let i = 0; i < message.name.length; i++)
UninterpretedOption_NamePart.internalBinaryWrite(message.name[i], writer.tag(2, WireType.LengthDelimited).fork(), options).join();
/* optional string identifier_value = 3; */
if (message.identifierValue !== undefined)
writer.tag(3, WireType.LengthDelimited).string(message.identifierValue);
/* optional uint64 positive_int_value = 4; */
if (message.positiveIntValue !== undefined)
writer.tag(4, WireType.Varint).uint64(message.positiveIntValue);
/* optional int64 negative_int_value = 5; */
if (message.negativeIntValue !== undefined)
writer.tag(5, WireType.Varint).int64(message.negativeIntValue);
/* optional double double_value = 6; */
if (message.doubleValue !== undefined)
writer.tag(6, WireType.Bit64).double(message.doubleValue);
/* optional bytes string_value = 7; */
if (message.stringValue !== undefined)
writer.tag(7, WireType.LengthDelimited).bytes(message.stringValue);
/* optional string aggregate_value = 8; */
if (message.aggregateValue !== undefined)
writer.tag(8, WireType.LengthDelimited).string(message.aggregateValue);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.UninterpretedOption
*/
export const UninterpretedOption = new UninterpretedOption$Type();
// @generated message type with reflection information, may provide speed optimized methods
class UninterpretedOption_NamePart$Type extends MessageType<UninterpretedOption_NamePart> {
constructor() {
super("google.protobuf.UninterpretedOption.NamePart", [
{ no: 1, name: "name_part", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
{ no: 2, name: "is_extension", kind: "scalar", T: 8 /*ScalarType.BOOL*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: UninterpretedOption_NamePart): UninterpretedOption_NamePart {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* string name_part */ 1:
message.namePart = reader.string();
break;
case /* bool is_extension */ 2:
message.isExtension = reader.bool();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: UninterpretedOption_NamePart, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* string name_part = 1; */
if (message.namePart !== "")
writer.tag(1, WireType.LengthDelimited).string(message.namePart);
/* bool is_extension = 2; */
if (message.isExtension !== false)
writer.tag(2, WireType.Varint).bool(message.isExtension);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.UninterpretedOption.NamePart
*/
export const UninterpretedOption_NamePart = new UninterpretedOption_NamePart$Type();
// @generated message type with reflection information, may provide speed optimized methods
class SourceCodeInfo$Type extends MessageType<SourceCodeInfo> {
constructor() {
super("google.protobuf.SourceCodeInfo", [
{ no: 1, name: "location", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => SourceCodeInfo_Location }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: SourceCodeInfo): SourceCodeInfo {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* repeated google.protobuf.SourceCodeInfo.Location location */ 1:
message.location.push(SourceCodeInfo_Location.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: SourceCodeInfo, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* repeated google.protobuf.SourceCodeInfo.Location location = 1; */
for (let i = 0; i < message.location.length; i++)
SourceCodeInfo_Location.internalBinaryWrite(message.location[i], writer.tag(1, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.SourceCodeInfo
*/
export const SourceCodeInfo = new SourceCodeInfo$Type();
// @generated message type with reflection information, may provide speed optimized methods
class SourceCodeInfo_Location$Type extends MessageType<SourceCodeInfo_Location> {
constructor() {
super("google.protobuf.SourceCodeInfo.Location", [
{ no: 1, name: "path", kind: "scalar", repeat: 1 /*RepeatType.PACKED*/, T: 5 /*ScalarType.INT32*/ },
{ no: 2, name: "span", kind: "scalar", repeat: 1 /*RepeatType.PACKED*/, T: 5 /*ScalarType.INT32*/ },
{ no: 3, name: "leading_comments", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 4, name: "trailing_comments", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 6, name: "leading_detached_comments", kind: "scalar", repeat: 2 /*RepeatType.UNPACKED*/, T: 9 /*ScalarType.STRING*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: SourceCodeInfo_Location): SourceCodeInfo_Location {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* repeated int32 path = 1 [packed = true];*/ 1:
if (wireType === WireType.LengthDelimited)
for (let e = reader.int32() + reader.pos; reader.pos < e;)
message.path.push(reader.int32());
else
message.path.push(reader.int32());
break;
case /* repeated int32 span = 2 [packed = true];*/ 2:
if (wireType === WireType.LengthDelimited)
for (let e = reader.int32() + reader.pos; reader.pos < e;)
message.span.push(reader.int32());
else
message.span.push(reader.int32());
break;
case /* optional string leading_comments */ 3:
message.leadingComments = reader.string();
break;
case /* optional string trailing_comments */ 4:
message.trailingComments = reader.string();
break;
case /* repeated string leading_detached_comments */ 6:
message.leadingDetachedComments.push(reader.string());
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: SourceCodeInfo_Location, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* repeated int32 path = 1 [packed = true]; */
if (message.path.length) {
writer.tag(1, WireType.LengthDelimited).fork();
for (let i = 0; i < message.path.length; i++)
writer.int32(message.path[i]);
writer.join();
}
/* repeated int32 span = 2 [packed = true]; */
if (message.span.length) {
writer.tag(2, WireType.LengthDelimited).fork();
for (let i = 0; i < message.span.length; i++)
writer.int32(message.span[i]);
writer.join();
}
/* optional string leading_comments = 3; */
if (message.leadingComments !== undefined)
writer.tag(3, WireType.LengthDelimited).string(message.leadingComments);
/* optional string trailing_comments = 4; */
if (message.trailingComments !== undefined)
writer.tag(4, WireType.LengthDelimited).string(message.trailingComments);
/* repeated string leading_detached_comments = 6; */
for (let i = 0; i < message.leadingDetachedComments.length; i++)
writer.tag(6, WireType.LengthDelimited).string(message.leadingDetachedComments[i]);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.SourceCodeInfo.Location
*/
export const SourceCodeInfo_Location = new SourceCodeInfo_Location$Type();
// @generated message type with reflection information, may provide speed optimized methods
class GeneratedCodeInfo$Type extends MessageType<GeneratedCodeInfo> {
constructor() {
super("google.protobuf.GeneratedCodeInfo", [
{ no: 1, name: "annotation", kind: "message", repeat: 2 /*RepeatType.UNPACKED*/, T: () => GeneratedCodeInfo_Annotation }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: GeneratedCodeInfo): GeneratedCodeInfo {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* repeated google.protobuf.GeneratedCodeInfo.Annotation annotation */ 1:
message.annotation.push(GeneratedCodeInfo_Annotation.internalBinaryRead(reader, reader.uint32(), options));
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: GeneratedCodeInfo, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* repeated google.protobuf.GeneratedCodeInfo.Annotation annotation = 1; */
for (let i = 0; i < message.annotation.length; i++)
GeneratedCodeInfo_Annotation.internalBinaryWrite(message.annotation[i], writer.tag(1, WireType.LengthDelimited).fork(), options).join();
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.GeneratedCodeInfo
*/
export const GeneratedCodeInfo = new GeneratedCodeInfo$Type();
// @generated message type with reflection information, may provide speed optimized methods
class GeneratedCodeInfo_Annotation$Type extends MessageType<GeneratedCodeInfo_Annotation> {
constructor() {
super("google.protobuf.GeneratedCodeInfo.Annotation", [
{ no: 1, name: "path", kind: "scalar", repeat: 1 /*RepeatType.PACKED*/, T: 5 /*ScalarType.INT32*/ },
{ no: 2, name: "source_file", kind: "scalar", opt: true, T: 9 /*ScalarType.STRING*/ },
{ no: 3, name: "begin", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ },
{ no: 4, name: "end", kind: "scalar", opt: true, T: 5 /*ScalarType.INT32*/ }
]);
}
internalBinaryRead(reader: IBinaryReader, length: number, options: BinaryReadOptions, target?: GeneratedCodeInfo_Annotation): GeneratedCodeInfo_Annotation {
let message = target ?? this.create(), end = reader.pos + length;
while (reader.pos < end) {
let [fieldNo, wireType] = reader.tag();
switch (fieldNo) {
case /* repeated int32 path = 1 [packed = true];*/ 1:
if (wireType === WireType.LengthDelimited)
for (let e = reader.int32() + reader.pos; reader.pos < e;)
message.path.push(reader.int32());
else
message.path.push(reader.int32());
break;
case /* optional string source_file */ 2:
message.sourceFile = reader.string();
break;
case /* optional int32 begin */ 3:
message.begin = reader.int32();
break;
case /* optional int32 end */ 4:
message.end = reader.int32();
break;
default:
let u = options.readUnknownField;
if (u === "throw")
throw new globalThis.Error(`Unknown field ${fieldNo} (wire type ${wireType}) for ${this.typeName}`);
let d = reader.skip(wireType);
if (u !== false)
(u === true ? UnknownFieldHandler.onRead : u)(this.typeName, message, fieldNo, wireType, d);
}
}
return message;
}
internalBinaryWrite(message: GeneratedCodeInfo_Annotation, writer: IBinaryWriter, options: BinaryWriteOptions): IBinaryWriter {
/* repeated int32 path = 1 [packed = true]; */
if (message.path.length) {
writer.tag(1, WireType.LengthDelimited).fork();
for (let i = 0; i < message.path.length; i++)
writer.int32(message.path[i]);
writer.join();
}
/* optional string source_file = 2; */
if (message.sourceFile !== undefined)
writer.tag(2, WireType.LengthDelimited).string(message.sourceFile);
/* optional int32 begin = 3; */
if (message.begin !== undefined)
writer.tag(3, WireType.Varint).int32(message.begin);
/* optional int32 end = 4; */
if (message.end !== undefined)
writer.tag(4, WireType.Varint).int32(message.end);
let u = options.writeUnknownFields;
if (u !== false)
(u == true ? UnknownFieldHandler.onWrite : u)(this.typeName, message, writer);
return writer;
}
}
/**
* @generated MessageType for protobuf message google.protobuf.GeneratedCodeInfo.Annotation
*/
export const GeneratedCodeInfo_Annotation = new GeneratedCodeInfo_Annotation$Type(); | the_stack |
import {
upperFirst,
lowerFirst,
// isObject,
omit,
fromPairs,
toPairs,
map,
isObject,
} from "lodash/fp";
// /////////////////////////////////////////////////////////////////////////////
// Import stuff we want to use from Openlayers
import * as olRaw from "ol";
import * as olLayerRaw from "ol/layer";
import * as olControlRaw from "ol/control";
import * as olInteractionRaw from "ol/interaction";
import * as olSourceRaw from "ol/source";
import * as olGeomRaw from "ol/geom";
import * as olStyleRaw from "ol/style";
// /////////////////////////////////////////////////////////////////////////////
// Here we define what we omit: abstract base classes, utility classes and other weird stuff
const olOmitKeys = [
"defaults",
"AssertionError",
"Disposable",
"Graticule",
"Image",
"ImageBase",
"ImageCanvas",
"ImageTile",
"Kinetic",
"MapBrowserEvent",
"MapBrowserEventHandler",
"MapEvent",
"Tile",
"TileQueue",
"TileRange",
"VectorRenderTile",
"VectorTile",
"getUid",
"VERSION",
] as const;
const olLayerOmitKeys = [] as const;
const olControlOmitKeys = ["defaults"] as const;
const olInteractionOmitKeys = ["defaults"] as const;
const olSourceOmitKeys = ["Image", "Source", "Tile"] as const;
const olGeomOmitKeys = ["Geometry", "SimpleGeometry"] as const;
const olStyleOmitKeys = ["Image", "IconImage"] as const;
// /////////////////////////////////////////////////////////////////////////////
// Here we do omit things listed above
const ol = omit(olOmitKeys, olRaw) as Omit<
typeof olRaw,
typeof olOmitKeys[number]
>;
const olLayer = omit(olLayerOmitKeys, olLayerRaw) as Omit<
typeof olLayerRaw,
typeof olLayerOmitKeys[number]
>;
const olControl = omit(olControlOmitKeys, olControlRaw) as Omit<
typeof olControlRaw,
typeof olControlOmitKeys[number]
>;
const olInteraction = omit(olInteractionOmitKeys, olInteractionRaw) as Omit<
typeof olInteractionRaw,
typeof olInteractionOmitKeys[number]
>;
const olSource = omit(olSourceOmitKeys, olSourceRaw) as Omit<
typeof olSourceRaw,
typeof olSourceOmitKeys[number]
>;
const olGeom = omit(olGeomOmitKeys, olGeomRaw) as Omit<
typeof olGeomRaw,
typeof olGeomOmitKeys[number]
>;
const olStyle = omit(olStyleOmitKeys, olStyleRaw) as Omit<
typeof olStyleRaw,
typeof olStyleOmitKeys[number]
>;
// /////////////////////////////////////////////////////////////////////////////
// type OlSourceRaw = typeof olSourceRaw;
// // type OlSourceRawKey = keyof OlSourceRaw;
// type OlSourceOmitKey = typeof olSourceOmitKeys[number];
// // type OlSourceKey = Exclude<OlSourceRawKey, OlSourceOmitKey>;
// // type OlSourceElement = OlSourceRaw[OlSourceKey];
// type OlSource = Omit<OlSourceRaw, OlSourceOmitKey>;
// const olSource = Object.fromEntries(
// Object.entries(olSourceRaw).filter(
// ([key]) => !olSourceOmitKeys.includes(key as OlSourceOmitKey)
// ) // as [OlSourceKey, OlSourceElement]
// ) as OlSource;
// /////////////////////////////////////////////////////////////////////////////
// Now we generate the types automatically (This parts needs typescript >=4.1)
type CatalogueOl = {
[K in keyof typeof ol as `ol${Capitalize<K>}`]: {
kind: K;
type: `ol${Capitalize<K>}`;
object: typeof ol[K];
};
};
type CatalogueOlLayer = {
[K in keyof typeof olLayer as `olLayer${Capitalize<K>}`]: {
kind: "Layer";
type: `olLayer${Capitalize<K>}`;
object: typeof olLayer[K];
};
};
type CatalogueOlControl = {
[K in keyof typeof olControl as `olControl${Capitalize<K>}`]: {
kind: "Control";
type: `olControl${Capitalize<K>}`;
object: typeof olControl[K];
};
};
type CatalogueOlInteraction = {
[K in keyof typeof olInteraction as `olInteraction${Capitalize<K>}`]: {
kind: "Interaction";
type: `olInteraction${Capitalize<K>}`;
object: typeof olInteraction[K];
};
};
type CatalogueOlSource = {
[K in keyof typeof olSource as `olSource${Capitalize<K>}`]: {
kind: "Source";
type: `olSource${Capitalize<K>}`;
object: typeof olSource[K];
};
};
type CatalogueOlGeom = {
[K in keyof typeof olGeom as `olGeom${Capitalize<K>}`]: {
kind: "Geom";
type: `olGeom${Capitalize<K>}`;
object: typeof olGeom[K];
};
};
type CatalogueOlStyle = {
[K in keyof typeof olStyle as `olStyle${Capitalize<K>}`]: {
kind: "Style";
type: `olStyle${Capitalize<K>}`;
object: typeof olStyle[K];
};
};
// /////////////////////////////////////////////////////////////////////////////
// With typescript <4.1 we have to do this:
// // /////////////////////////////////////////////////////////////////////////////
// // Catalogue Type
// export type Kind =
// // Elements of Ol that we picked manually
// | keyof typeof ol
// // Or the categories of Ol items explained in https://openlayers.org/en/latest/apidoc/
// | "Layer"
// | "Control"
// | "Interaction"
// | "Source"
// | "Geom"
// | "Style";
// export type NewCatalogueItem<K extends Kind, T extends string, O> = {
// kind: K;
// type: T;
// object: O;
// };
// type CatalogueOl = {
// olCollection: NewCatalogueItem<
// "Collection",
// "olCollection",
// typeof olRaw.Collection
// >;
// olFeature: NewCatalogueItem<"Feature", "olFeature", typeof olRaw.Feature>;
// olGeolocation: NewCatalogueItem<
// "Geolocation",
// "olGeolocation",
// typeof olRaw.Geolocation
// >;
// olMap: NewCatalogueItem<"Map", "olMap", typeof olRaw.Map>;
// olObject: NewCatalogueItem<"Object", "olObject", typeof olRaw.Object>;
// olObservable: NewCatalogueItem<
// "Observable",
// "olObservable",
// typeof olRaw.Observable
// >;
// olOverlay: NewCatalogueItem<"Overlay", "olOverlay", typeof olRaw.Overlay>;
// olPluggableMap: NewCatalogueItem<
// "PluggableMap",
// "olPluggableMap",
// typeof olRaw.PluggableMap
// >;
// olTileCache: NewCatalogueItem<
// "TileCache",
// "olTileCache",
// typeof olRaw.TileCache
// >;
// olView: NewCatalogueItem<"View", "olView", typeof olRaw.View>;
// };
// type CatalogueOlLayer = {
// olLayerGraticule: NewCatalogueItem<
// "Layer",
// "olLayerGraticule",
// typeof olLayerRaw.Graticule
// >;
// olLayerGroup: NewCatalogueItem<
// "Layer",
// "olLayerGroup",
// typeof olLayerRaw.Group
// >;
// olLayerHeatmap: NewCatalogueItem<
// "Layer",
// "olLayerHeatmap",
// typeof olLayerRaw.Heatmap
// >;
// olLayerImage: NewCatalogueItem<
// "Layer",
// "olLayerImage",
// typeof olLayerRaw.Image
// >;
// olLayerLayer: NewCatalogueItem<
// "Layer",
// "olLayerLayer",
// typeof olLayerRaw.Layer
// >;
// olLayerMapboxVector: NewCatalogueItem<
// "Layer",
// "olLayerMapboxVector",
// typeof olLayerRaw.MapboxVector
// >;
// olLayerTile: NewCatalogueItem<"Layer", "olLayerTile", typeof olLayerRaw.Tile>;
// olLayerVector: NewCatalogueItem<
// "Layer",
// "olLayerVector",
// typeof olLayerRaw.Vector
// >;
// olLayerVectorImage: NewCatalogueItem<
// "Layer",
// "olLayerVectorImage",
// typeof olLayerRaw.VectorImage
// >;
// olLayerVectorTile: NewCatalogueItem<
// "Layer",
// "olLayerVectorTile",
// typeof olLayerRaw.VectorTile
// >;
// olLayerWebGLPoints: NewCatalogueItem<
// "Layer",
// "olLayerWebGLPoints",
// typeof olLayerRaw.WebGLPoints
// >;
// };
// type CatalogueOlControl = {
// olControlAttribution: NewCatalogueItem<
// "Control",
// "olControlAttribution",
// typeof olControlRaw.Attribution
// >;
// olControlControl: NewCatalogueItem<
// "Control",
// "olControlControl",
// typeof olControlRaw.Control
// >;
// olControlFullScreen: NewCatalogueItem<
// "Control",
// "olControlFullScreen",
// typeof olControlRaw.FullScreen
// >;
// olControlMousePosition: NewCatalogueItem<
// "Control",
// "olControlMousePosition",
// typeof olControlRaw.MousePosition
// >;
// olControlOverviewMap: NewCatalogueItem<
// "Control",
// "olControlOverviewMap",
// typeof olControlRaw.OverviewMap
// >;
// olControlRotate: NewCatalogueItem<
// "Control",
// "olControlRotate",
// typeof olControlRaw.Rotate
// >;
// olControlScaleLine: NewCatalogueItem<
// "Control",
// "olControlScaleLine",
// typeof olControlRaw.ScaleLine
// >;
// olControlZoom: NewCatalogueItem<
// "Control",
// "olControlZoom",
// typeof olControlRaw.Zoom
// >;
// olControlZoomSlider: NewCatalogueItem<
// "Control",
// "olControlZoomSlider",
// typeof olControlRaw.ZoomSlider
// >;
// olControlZoomToExtent: NewCatalogueItem<
// "Control",
// "olControlZoomToExtent",
// typeof olControlRaw.ZoomToExtent
// >;
// };
// type CatalogueOlInteraction = {
// olInteractionDoubleClickZoom: NewCatalogueItem<
// "Interaction",
// "olInteractionDoubleClickZoom",
// typeof olInteractionRaw.DoubleClickZoom
// >;
// olInteractionDragAndDrop: NewCatalogueItem<
// "Interaction",
// "olInteractionDragAndDrop",
// typeof olInteractionRaw.DragAndDrop
// >;
// olInteractionDragBox: NewCatalogueItem<
// "Interaction",
// "olInteractionDragBox",
// typeof olInteractionRaw.DragBox
// >;
// olInteractionDragPan: NewCatalogueItem<
// "Interaction",
// "olInteractionDragPan",
// typeof olInteractionRaw.DragPan
// >;
// olInteractionDragRotate: NewCatalogueItem<
// "Interaction",
// "olInteractionDragRotate",
// typeof olInteractionRaw.DragRotate
// >;
// olInteractionDragRotateAndZoom: NewCatalogueItem<
// "Interaction",
// "olInteractionDragRotateAndZoom",
// typeof olInteractionRaw.DragRotateAndZoom
// >;
// olInteractionDragZoom: NewCatalogueItem<
// "Interaction",
// "olInteractionDragZoom",
// typeof olInteractionRaw.DragZoom
// >;
// olInteractionDraw: NewCatalogueItem<
// "Interaction",
// "olInteractionDraw",
// typeof olInteractionRaw.Draw
// >;
// olInteractionExtent: NewCatalogueItem<
// "Interaction",
// "olInteractionExtent",
// typeof olInteractionRaw.Extent
// >;
// olInteractionInteraction: NewCatalogueItem<
// "Interaction",
// "olInteractionInteraction",
// typeof olInteractionRaw.Interaction
// >;
// olInteractionKeyboardPan: NewCatalogueItem<
// "Interaction",
// "olInteractionKeyboardPan",
// typeof olInteractionRaw.KeyboardPan
// >;
// olInteractionKeyboardZoom: NewCatalogueItem<
// "Interaction",
// "olInteractionKeyboardZoom",
// typeof olInteractionRaw.KeyboardZoom
// >;
// olInteractionModify: NewCatalogueItem<
// "Interaction",
// "olInteractionModify",
// typeof olInteractionRaw.Modify
// >;
// olInteractionMouseWheelZoom: NewCatalogueItem<
// "Interaction",
// "olInteractionMouseWheelZoom",
// typeof olInteractionRaw.MouseWheelZoom
// >;
// olInteractionPinchRotate: NewCatalogueItem<
// "Interaction",
// "olInteractionPinchRotate",
// typeof olInteractionRaw.PinchRotate
// >;
// olInteractionPinchZoom: NewCatalogueItem<
// "Interaction",
// "olInteractionPinchZoom",
// typeof olInteractionRaw.PinchZoom
// >;
// olInteractionPointer: NewCatalogueItem<
// "Interaction",
// "olInteractionPointer",
// typeof olInteractionRaw.Pointer
// >;
// olInteractionSelect: NewCatalogueItem<
// "Interaction",
// "olInteractionSelect",
// typeof olInteractionRaw.Select
// >;
// olInteractionSnap: NewCatalogueItem<
// "Interaction",
// "olInteractionSnap",
// typeof olInteractionRaw.Snap
// >;
// olInteractionTranslate: NewCatalogueItem<
// "Interaction",
// "olInteractionTranslate",
// typeof olInteractionRaw.Translate
// >;
// };
// type CatalogueOlSource = {
// olSourceBingMaps: NewCatalogueItem<
// "Source",
// "olSourceBingMaps",
// typeof olSourceRaw.BingMaps
// >;
// olSourceCartoDB: NewCatalogueItem<
// "Source",
// "olSourceCartoDB",
// typeof olSourceRaw.CartoDB
// >;
// olSourceCluster: NewCatalogueItem<
// "Source",
// "olSourceCluster",
// typeof olSourceRaw.Cluster
// >;
// olSourceIIIF: NewCatalogueItem<
// "Source",
// "olSourceIIIF",
// typeof olSourceRaw.IIIF
// >;
// // olSourceImage: NewCatalogueItem<"Source","olSourceImage",typeof olSourceRaw.Image>;
// olSourceImageArcGISRest: NewCatalogueItem<
// "Source",
// "olSourceImageArcGISRest",
// typeof olSourceRaw.ImageArcGISRest
// >;
// olSourceImageCanvas: NewCatalogueItem<
// "Source",
// "olSourceImageCanvas",
// typeof olSourceRaw.ImageCanvas
// >;
// olSourceImageMapGuide: NewCatalogueItem<
// "Source",
// "olSourceImageMapGuide",
// typeof olSourceRaw.ImageMapGuide
// >;
// olSourceImageStatic: NewCatalogueItem<
// "Source",
// "olSourceImageStatic",
// typeof olSourceRaw.ImageStatic
// >;
// olSourceImageWMS: NewCatalogueItem<
// "Source",
// "olSourceImageWMS",
// typeof olSourceRaw.ImageWMS
// >;
// olSourceOSM: NewCatalogueItem<
// "Source",
// "olSourceOSM",
// typeof olSourceRaw.OSM
// >;
// olSourceRaster: NewCatalogueItem<
// "Source",
// "olSourceRaster",
// typeof olSourceRaw.Raster
// >;
// // olSourceSource: NewCatalogueItem<"Source","olSourceSource",typeof olSourceRaw.Source>;
// olSourceStamen: NewCatalogueItem<
// "Source",
// "olSourceStamen",
// typeof olSourceRaw.Stamen
// >;
// // olSourceTile: NewCatalogueItem<"Source","olSourceTile",typeof olSourceRaw.Tile>;
// olSourceTileArcGISRest: NewCatalogueItem<
// "Source",
// "olSourceTileArcGISRest",
// typeof olSourceRaw.TileArcGISRest
// >;
// olSourceTileDebug: NewCatalogueItem<
// "Source",
// "olSourceTileDebug",
// typeof olSourceRaw.TileDebug
// >;
// olSourceTileImage: NewCatalogueItem<
// "Source",
// "olSourceTileImage",
// typeof olSourceRaw.TileImage
// >;
// olSourceTileJSON: NewCatalogueItem<
// "Source",
// "olSourceTileJSON",
// typeof olSourceRaw.TileJSON
// >;
// olSourceTileWMS: NewCatalogueItem<
// "Source",
// "olSourceTileWMS",
// typeof olSourceRaw.TileWMS
// >;
// olSourceUrlTile: NewCatalogueItem<
// "Source",
// "olSourceUrlTile",
// typeof olSourceRaw.UrlTile
// >;
// olSourceUTFGrid: NewCatalogueItem<
// "Source",
// "olSourceUTFGrid",
// typeof olSourceRaw.UTFGrid
// >;
// olSourceVector: NewCatalogueItem<
// "Source",
// "olSourceVector",
// typeof olSourceRaw.Vector
// >;
// olSourceVectorTile: NewCatalogueItem<
// "Source",
// "olSourceVectorTile",
// typeof olSourceRaw.VectorTile
// >;
// olSourceWMTS: NewCatalogueItem<
// "Source",
// "olSourceWMTS",
// typeof olSourceRaw.WMTS
// >;
// olSourceXYZ: NewCatalogueItem<
// "Source",
// "olSourceXYZ",
// typeof olSourceRaw.XYZ
// >;
// olSourceZoomify: NewCatalogueItem<
// "Source",
// "olSourceZoomify",
// typeof olSourceRaw.Zoomify
// >;
// };
// type CatalogueOlGeom = {
// olGeomCircle: NewCatalogueItem<
// "Geom",
// "olGeomCircle",
// typeof olGeomRaw.Circle
// >;
// // olGeomGeometry: NewCatalogueItem<"Geom","olGeomGeometry",typeof olGeomRaw.Geometry>;
// olGeomGeometryCollection: NewCatalogueItem<
// "Geom",
// "olGeomGeometryCollection",
// typeof olGeomRaw.GeometryCollection
// >;
// olGeomLinearRing: NewCatalogueItem<
// "Geom",
// "olGeomLinearRing",
// typeof olGeomRaw.LinearRing
// >;
// olGeomLineString: NewCatalogueItem<
// "Geom",
// "olGeomLineString",
// typeof olGeomRaw.LineString
// >;
// olGeomMultiLineString: NewCatalogueItem<
// "Geom",
// "olGeomMultiLineString",
// typeof olGeomRaw.MultiLineString
// >;
// olGeomMultiPoint: NewCatalogueItem<
// "Geom",
// "olGeomMultiPoint",
// typeof olGeomRaw.MultiPoint
// >;
// olGeomMultiPolygon: NewCatalogueItem<
// "Geom",
// "olGeomMultiPolygon",
// typeof olGeomRaw.MultiPolygon
// >;
// olGeomPoint: NewCatalogueItem<"Geom", "olGeomPoint", typeof olGeomRaw.Point>;
// olGeomPolygon: NewCatalogueItem<
// "Geom",
// "olGeomPolygon",
// typeof olGeomRaw.Polygon
// >;
// // olGeomSimpleGeometry: NewCatalogueItem<"Geom","olGeomSimpleGeometry",typeof olGeomRaw.SimpleGeometry>;
// };
// type CatalogueOlStyle = {
// olStyleCircle: NewCatalogueItem<
// "Style",
// "olStyleCircle",
// typeof olStyleRaw.Circle
// >;
// olStyleFill: NewCatalogueItem<"Style", "olStyleFill", typeof olStyleRaw.Fill>;
// olStyleIcon: NewCatalogueItem<"Style", "olStyleIcon", typeof olStyleRaw.Icon>;
// // olStyleIconImage: NewCatalogueItem<"Style","olStyleIconImage",typeof olStyleRaw.IconImage>;
// // olStyleImage: NewCatalogueItem<"Style","olStyleImage",typeof olStyleRaw.Image>;
// olStyleRegularShape: NewCatalogueItem<
// "Style",
// "olStyleRegularShape",
// typeof olStyleRaw.RegularShape
// >;
// olStyleStroke: NewCatalogueItem<
// "Style",
// "olStyleStroke",
// typeof olStyleRaw.Stroke
// >;
// olStyleStyle: NewCatalogueItem<
// "Style",
// "olStyleStyle",
// typeof olStyleRaw.Style
// >;
// olStyleText: NewCatalogueItem<"Style", "olStyleText", typeof olStyleRaw.Text>;
// };
// /////////////////////////////////////////////////////////////////////////////
// Finished, now some additional stuff
export type Catalogue = CatalogueOl &
CatalogueOlLayer &
CatalogueOlControl &
CatalogueOlInteraction &
CatalogueOlSource &
CatalogueOlGeom &
CatalogueOlStyle;
export type CatalogueKey = keyof Catalogue;
export type CatalogueItem = Catalogue[CatalogueKey];
export type Kind = CatalogueItem["kind"];
export type ExtendedCatalogueItem<T> = {
object: T;
kind: Kind | null;
type: string;
};
// /////////////////////////////////////////////////////////////////////////////
// Catalogue Value
const catalogueOl = Object.fromEntries(
Object.entries(ol).map(([key, value]) => [
`ol${upperFirst(key)}`,
{
kind: key,
type: `ol${upperFirst(key)}`,
object: value,
},
])
) as CatalogueOl;
const catalogueOlLayer = Object.fromEntries(
Object.entries(olLayer).map(([key, value]) => [
`olLayer${upperFirst(key)}`,
{
kind: "Layer",
type: `olLayer${upperFirst(key)}`,
object: value,
},
])
) as CatalogueOlLayer;
const catalogueOlControl = Object.fromEntries(
Object.entries(olControl).map(([key, value]) => [
`olControl${upperFirst(key)}`,
{
kind: "Control",
type: `olControl${upperFirst(key)}`,
object: value,
},
])
) as CatalogueOlControl;
const catalogueOlInteraction = Object.fromEntries(
Object.entries(olInteraction).map(([key, value]) => [
`olInteraction${upperFirst(key)}`,
{
kind: "Interaction",
type: `olInteraction${upperFirst(key)}`,
object: value,
},
])
) as CatalogueOlInteraction;
const catalogueOlSource = Object.fromEntries(
Object.entries(olSource).map(([key, value]) => [
`olSource${upperFirst(key)}`,
{
kind: "Source",
type: `olSource${upperFirst(key)}`,
object: value,
},
])
) as CatalogueOlSource;
const catalogueOlGeom = Object.fromEntries(
Object.entries(olGeom).map(([key, value]) => [
`olGeom${upperFirst(key)}`,
{
kind: "Geom",
type: `olGeom${upperFirst(key)}`,
object: value,
},
])
) as CatalogueOlGeom;
const catalogueOlStyle = Object.fromEntries(
Object.entries(olStyle).map(([key, value]) => [
`olStyle${upperFirst(key)}`,
{
kind: "Style",
type: `olStyle${upperFirst(key)}`,
object: value,
},
])
) as CatalogueOlStyle;
// eslint-disable-next-line import/no-mutable-exports
export let catalogue: Catalogue = {
...catalogueOl,
...catalogueOlLayer,
...catalogueOlControl,
...catalogueOlInteraction,
...catalogueOlSource,
...catalogueOlGeom,
...catalogueOlStyle,
};
/// ////////////////////////////////////////////////////////////////////////
/// ////////////////////////////////////////////////////////////////////////////
// A way to extend the catalogue
export const extend = <T>(objects: { [key: string]: T }): void => {
// Cleanup the input
const cleanedUpObjects = fromPairs(
map(<U>([key, value]: [string, U | ExtendedCatalogueItem<U>]): [
string,
ExtendedCatalogueItem<U>
] => {
if (!isObject((value as ExtendedCatalogueItem<U>).object)) {
// If it's directly an object we put it nicely in a catalogue item
return [
lowerFirst(key),
{
type: lowerFirst(key),
kind: null,
object: value as U,
},
];
}
// If it's already a catalogue item it's good
return [
lowerFirst(key),
{
...(value as ExtendedCatalogueItem<U>),
type: lowerFirst(key),
},
];
}, toPairs(objects))
);
// Update the catalogue
catalogue = { ...catalogue, ...cleanedUpObjects };
}; | the_stack |
import test, { Test } from "tape-promise/tape";
import { v4 as uuidv4 } from "uuid";
import {
EthContractInvocationType,
Web3SigningCredentialType,
PluginLedgerConnectorXdai,
DefaultApi as XdaiApi,
ReceiptType,
DeployContractV1Request,
InvokeContractV1Request,
RunTransactionV1Request,
} from "../../../../main/typescript/public-api";
import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory";
import {
Containers,
K_DEV_WHALE_ACCOUNT_PRIVATE_KEY,
K_DEV_WHALE_ACCOUNT_PUBLIC_KEY,
OpenEthereumTestLedger,
pruneDockerAllIfGithubAction,
} from "@hyperledger/cactus-test-tooling";
import HelloWorldContractJson from "../../../solidity/hello-world-contract/HelloWorld.json";
import { PluginRegistry } from "@hyperledger/cactus-core";
import express from "express";
import bodyParser from "body-parser";
import http from "http";
import { AddressInfo } from "net";
import { Configuration } from "@hyperledger/cactus-core-api";
import {
LogLevelDesc,
IListenOptions,
Servers,
} from "@hyperledger/cactus-common";
import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core";
import OAS from "../../../../main/json/openapi.json";
const testCase = "xDai API";
const logLevel: LogLevelDesc = "TRACE";
test("BEFORE " + testCase, async (t: Test) => {
const pruning = pruneDockerAllIfGithubAction({ logLevel });
await t.doesNotReject(pruning, "Pruning did not throw OK");
t.end();
});
test(testCase, async (t: Test) => {
test.onFailure(async () => {
await Containers.logDiagnostics({ logLevel });
});
// create a test ledger
const xdaiTestLedger = new OpenEthereumTestLedger({ logLevel });
test.onFinish(async () => {
await xdaiTestLedger.stop();
await xdaiTestLedger.destroy();
});
await xdaiTestLedger.start();
// get host to which connector will attack
const rpcApiHttpHost = await xdaiTestLedger.getRpcApiHttpHost();
// obtain public and private keys from an account
const whalePubKey = K_DEV_WHALE_ACCOUNT_PUBLIC_KEY;
const whalePrivKey = K_DEV_WHALE_ACCOUNT_PRIVATE_KEY;
// create an ethereum account
const testEthAccount = await xdaiTestLedger.createEthTestAccount();
// create a keychain for this account
const keychainId = uuidv4();
const keychainEntryKey = uuidv4();
const keychainEntryValue = testEthAccount.privateKey;
const keychainPlugin = new PluginKeychainMemory({
instanceId: uuidv4(),
keychainId,
// pre-provision keychain with mock backend holding the private key of the
// test account that we'll reference while sending requests with the
// signing credential pointing to this keychain entry.
backend: new Map([[keychainEntryKey, keychainEntryValue]]),
logLevel,
});
keychainPlugin.set(
HelloWorldContractJson.contractName,
JSON.stringify(HelloWorldContractJson),
);
// add keychain plugin to plugin registry
const pluginRegistry = new PluginRegistry({ plugins: [keychainPlugin] });
// create the connector
const connector: PluginLedgerConnectorXdai = new PluginLedgerConnectorXdai({
instanceId: uuidv4(),
rpcApiHttpHost,
logLevel,
pluginRegistry,
});
const expressApp = express();
expressApp.use(bodyParser.json({ limit: "250mb" }));
const server = http.createServer(expressApp);
const listenOptions: IListenOptions = {
hostname: "localhost",
port: 0,
server,
};
const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo;
test.onFinish(async () => await Servers.shutdown(server));
const { address, port } = addressInfo;
const apiHost = `http://${address}:${port}`;
const config = new Configuration({ basePath: apiHost });
const apiClient = new XdaiApi(config);
await installOpenapiValidationMiddleware({
logLevel,
app: expressApp,
apiSpec: OAS,
});
await connector.getOrCreateWebServices();
await connector.registerWebServices(expressApp);
const fDeploy = "deployContractV1";
const fInvoke = "invokeContractV1";
const fRun = "runTransactionV1";
const cOk = "without bad request error";
const cWithoutParams = "not sending all required parameters";
const cInvalidParams = "sending invalid parameters";
test(`${testCase} - ${fDeploy} - ${cOk}`, async (t2: Test) => {
const parameters = {
keychainId: keychainPlugin.getKeychainId(),
contractName: HelloWorldContractJson.contractName,
constructorArgs: [],
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
gas: 1000000,
};
const res = await apiClient.deployContractV1(parameters);
t2.ok(res, "Contract deployed successfully");
t2.ok(res.data);
t2.equal(
res.status,
200,
`Endpoint ${fDeploy}: response.status === 200 OK`,
);
t2.end();
});
test(`${testCase} - ${fDeploy} - ${cWithoutParams}`, async (t2: Test) => {
try {
const parameters = {
contractName: HelloWorldContractJson.contractName,
constructorArgs: [],
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
gas: 1000000,
};
await apiClient.deployContractV1(
(parameters as unknown) as DeployContractV1Request,
);
} catch (e) {
t2.equal(
e.response.status,
400,
`Endpoint ${fDeploy} without required keychainId: response.status === 400 OK`,
);
const fields = e.response.data.map((param: { path: string }) =>
param.path.replace(".body.", ""),
);
t2.ok(
fields.includes("keychainId"),
"Rejected because keychainId is required",
);
}
t2.end();
});
test(`${testCase} - ${fDeploy} - ${cInvalidParams}`, async (t2: Test) => {
try {
const parameters = {
keychainId: keychainPlugin.getKeychainId(),
contractName: HelloWorldContractJson.contractName,
constructorArgs: [],
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
gas: 1000000,
fake: 4,
};
await apiClient.deployContractV1(parameters);
} catch (e) {
t2.equal(
e.response.status,
400,
`Endpoint ${fDeploy} with fake=4: response.status === 400 OK`,
);
const fields = e.response.data.map((param: { path: string }) =>
param.path.replace(".body.", ""),
);
t2.ok(
fields.includes("fake"),
"Rejected because fake is not a valid parameter",
);
}
t2.end();
});
test(`${testCase} - ${fInvoke} - ${cOk}`, async (t2: Test) => {
const parameters = {
contractName: HelloWorldContractJson.contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Call,
methodName: "sayHello",
params: [],
gas: 1000000,
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
};
const res = await apiClient.invokeContractV1(parameters);
t2.ok(res, "Contract invoked successfully");
t2.ok(res.data);
t2.equal(
res.status,
200,
`Endpoint ${fInvoke}: response.status === 200 OK`,
);
t2.end();
});
test(`${testCase} - ${fInvoke} - ${cWithoutParams}`, async (t2: Test) => {
try {
const parameters = {
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Call,
methodName: "sayHello",
params: [],
gas: 1000000,
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
};
await apiClient.invokeContractV1(
(parameters as unknown) as InvokeContractV1Request,
);
} catch (e) {
t2.equal(
e.response.status,
400,
`Endpoint ${fInvoke} without required contractName: response.status === 400 OK`,
);
const fields = e.response.data.map((param: { path: string }) =>
param.path.replace(".body.", ""),
);
t2.ok(
fields.includes("contractName"),
"Rejected because contractName is required",
);
}
t2.end();
});
test(`${testCase} - ${fInvoke} - ${cInvalidParams}`, async (t2: Test) => {
try {
const parameters = {
contractName: HelloWorldContractJson.contractName,
keychainId: keychainPlugin.getKeychainId(),
invocationType: EthContractInvocationType.Call,
methodName: "sayHello",
params: [],
gas: 1000000,
signingCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
fake: 4,
};
await apiClient.invokeContractV1(
(parameters as any) as InvokeContractV1Request,
);
} catch (e) {
t2.equal(
e.response.status,
400,
`Endpoint ${fInvoke} with fake=4: response.status === 400 OK`,
);
const fields = e.response.data.map((param: { path: string }) =>
param.path.replace(".body.", ""),
);
t2.ok(
fields.includes("fake"),
"Rejected because fake is not a valid parameter",
);
}
t2.end();
});
test(`${testCase} - ${fRun} - ${cOk}`, async (t2: Test) => {
const parameters = {
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
transactionConfig: {
from: whalePubKey,
to: testEthAccount.address,
value: 10e7,
gas: 1000000,
},
consistencyStrategy: {
blockConfirmations: 0,
receiptType: ReceiptType.NodeTxPoolAck,
timeoutMs: 60000,
},
};
const res = await apiClient.runTransactionV1(parameters);
t2.ok(res, "Transaction ran successfully");
t2.ok(res.data);
t2.equal(res.status, 200, `Endpoint ${fRun}: response.status === 200 OK`);
t2.end();
});
test(`${testCase} - ${fRun} - ${cWithoutParams}`, async (t2: Test) => {
try {
const parameters = {
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
transactionConfig: {
from: whalePubKey,
to: testEthAccount.address,
value: 10e7,
gas: 22000,
},
};
await apiClient.runTransactionV1(
(parameters as any) as RunTransactionV1Request,
);
} catch (e) {
t2.equal(
e.response.status,
400,
`Endpoint ${fRun} without required consistencyStrategy: response.status === 400 OK`,
);
const fields = e.response.data.map((param: { path: string }) =>
param.path.replace(".body.", ""),
);
t2.ok(
fields.includes("consistencyStrategy"),
"Rejected because consistencyStrategy is required",
);
}
t2.end();
});
test(`${testCase} - ${fRun} - ${cInvalidParams}`, async (t2: Test) => {
try {
const parameters = {
web3SigningCredential: {
ethAccount: whalePubKey,
secret: whalePrivKey,
type: Web3SigningCredentialType.PrivateKeyHex,
},
transactionConfig: {
from: whalePubKey,
to: testEthAccount.address,
value: 10e7,
gas: 22000,
},
consistencyStrategy: {
blockConfirmations: 0,
receiptType: ReceiptType.NodeTxPoolAck,
timeoutMs: 60000,
},
fake: 4,
};
await apiClient.runTransactionV1(
(parameters as any) as RunTransactionV1Request,
);
} catch (e) {
t2.equal(
e.response.status,
400,
`Endpoint ${fRun} with fake=4: response.status === 400 OK`,
);
const fields = e.response.data.map((param: { path: string }) =>
param.path.replace(".body.", ""),
);
t2.ok(
fields.includes("fake"),
"Rejected because fake is not a valid parameter",
);
}
t2.end();
});
t.end();
});
test("AFTER " + testCase, async (t: Test) => {
const pruning = pruneDockerAllIfGithubAction({ logLevel });
await t.doesNotReject(pruning, "Pruning did not throw OK");
t.end();
}); | the_stack |
import { KeyPair, PublicKey, PrivateKey } from "./secure_keygen";
import context from "./context";
import { ThemisError, ThemisErrorCode } from "./themis_error";
import {
coerceToBytes,
heapFree,
heapGetArray,
heapPutArray,
heapAlloc,
} from "./utils";
const cryptosystem_name = "SecureMessage";
export class SecureMessage {
private privateKey: PrivateKey;
private publicKey: PublicKey;
constructor(keyPair: KeyPair) {
if (arguments.length == 1) {
if (!(keyPair instanceof KeyPair)) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"invalid argument: must be KeyPair"
);
}
this.privateKey = keyPair.privateKey;
this.publicKey = keyPair.publicKey;
return;
}
if (arguments.length == 2) {
let arg0isPrivateKey = arguments[0] instanceof PrivateKey;
let arg0isPublicKey = arguments[0] instanceof PublicKey;
let arg1isPrivateKey = arguments[1] instanceof PrivateKey;
let arg1isPublicKey = arguments[1] instanceof PublicKey;
if (arg0isPublicKey && arg1isPrivateKey) {
this.publicKey = arguments[0];
this.privateKey = arguments[1];
return;
}
if (arg0isPrivateKey && arg1isPublicKey) {
this.privateKey = arguments[0];
this.publicKey = arguments[1];
return;
}
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"invalid arguments: expected PrivateKey and PublicKey"
);
}
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"invalid argument count: expected either one KeyPair, or PrivateKey and PublicKey"
);
}
encrypt(message: Uint8Array) {
message = coerceToBytes(message);
if (message.length == 0) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"message must be not empty"
);
}
let status;
/// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten
let result_length_ptr = context.libthemis!!.allocate(
new ArrayBuffer(4),
context.libthemis!!.ALLOC_STACK
);
let private_key_ptr, public_key_ptr, message_ptr, result_ptr, result_length;
try {
private_key_ptr = heapAlloc(this.privateKey.length);
public_key_ptr = heapAlloc(this.publicKey.length);
message_ptr = heapAlloc(message.length);
if (!private_key_ptr || !public_key_ptr || !message_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
heapPutArray(this.privateKey, private_key_ptr);
heapPutArray(this.publicKey, public_key_ptr);
heapPutArray(message, message_ptr);
status = context.libthemis!!._themis_secure_message_encrypt(
private_key_ptr,
this.privateKey.length,
public_key_ptr,
this.publicKey.length,
message_ptr,
message.length,
null,
result_length_ptr
);
if (status != ThemisErrorCode.BUFFER_TOO_SMALL) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = context.libthemis!!.getValue(result_length_ptr, "i32");
result_ptr = heapAlloc(result_length);
if (!result_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
status = context.libthemis!!._themis_secure_message_encrypt(
private_key_ptr,
this.privateKey.length,
public_key_ptr,
this.publicKey.length,
message_ptr,
message.length,
result_ptr,
result_length_ptr
);
if (status != ThemisErrorCode.SUCCESS) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = context.libthemis!!.getValue(result_length_ptr, "i32");
return heapGetArray(result_ptr, result_length);
} finally {
heapFree(private_key_ptr, this.privateKey.length);
heapFree(public_key_ptr, this.publicKey.length);
heapFree(message_ptr, message.length);
heapFree(result_ptr, result_length);
}
}
decrypt(message: Uint8Array) {
message = coerceToBytes(message);
if (message.length == 0) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"message must be not empty"
);
}
let status;
/// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten
let result_length_ptr = context.libthemis!!.allocate(
new ArrayBuffer(4),
context.libthemis!!.ALLOC_STACK
);
let private_key_ptr, public_key_ptr, message_ptr, result_ptr, result_length;
try {
private_key_ptr = heapAlloc(this.privateKey.length);
public_key_ptr = heapAlloc(this.publicKey.length);
message_ptr = heapAlloc(message.length);
if (!private_key_ptr || !public_key_ptr || !message_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
heapPutArray(this.privateKey, private_key_ptr);
heapPutArray(this.publicKey, public_key_ptr);
heapPutArray(message, message_ptr);
status = context.libthemis!!._themis_secure_message_decrypt(
private_key_ptr,
this.privateKey.length,
public_key_ptr,
this.publicKey.length,
message_ptr,
message.length,
null,
result_length_ptr
);
if (status != ThemisErrorCode.BUFFER_TOO_SMALL) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = context.libthemis!!.getValue(result_length_ptr, "i32");
result_ptr = heapAlloc(result_length);
if (!result_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
status = context.libthemis!!._themis_secure_message_decrypt(
private_key_ptr,
this.privateKey.length,
public_key_ptr,
this.publicKey.length,
message_ptr,
message.length,
result_ptr,
result_length_ptr
);
if (status != ThemisErrorCode.SUCCESS) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = context.libthemis!!.getValue(result_length_ptr, "i32");
return heapGetArray(result_ptr, result_length);
} finally {
heapFree(private_key_ptr, this.privateKey.length);
heapFree(public_key_ptr, this.publicKey.length);
heapFree(message_ptr, message.length);
heapFree(result_ptr, result_length);
}
}
}
export class SecureMessageSign {
private privateKey: PrivateKey;
constructor(privateKey: PrivateKey) {
if (!(privateKey instanceof PrivateKey)) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"invalid argument: expected PrivateKey"
);
}
this.privateKey = privateKey;
}
sign(message: Uint8Array) {
message = coerceToBytes(message);
if (message.length == 0) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"message must be not empty"
);
}
let status;
/// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten
let result_length_ptr = context.libthemis!!.allocate(
new ArrayBuffer(4),
context.libthemis!!.ALLOC_STACK
);
let private_key_ptr, message_ptr, result_ptr, result_length;
try {
private_key_ptr = heapAlloc(this.privateKey.length);
message_ptr = heapAlloc(message.length);
if (!private_key_ptr || !message_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
heapPutArray(this.privateKey, private_key_ptr);
heapPutArray(message, message_ptr);
status = context.libthemis!!._themis_secure_message_sign(
private_key_ptr,
this.privateKey.length,
message_ptr,
message.length,
null,
result_length_ptr
);
if (status != ThemisErrorCode.BUFFER_TOO_SMALL) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = context.libthemis!!.getValue(result_length_ptr, "i32");
result_ptr = heapAlloc(result_length);
if (!result_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
status = context.libthemis!!._themis_secure_message_sign(
private_key_ptr,
this.privateKey.length,
message_ptr,
message.length,
result_ptr,
result_length_ptr
);
if (status != ThemisErrorCode.SUCCESS) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = context.libthemis!!.getValue(result_length_ptr, "i32");
return heapGetArray(result_ptr, result_length);
} finally {
heapFree(private_key_ptr, this.privateKey.length);
heapFree(message_ptr, message.length);
heapFree(result_ptr, result_length);
}
}
}
export class SecureMessageVerify {
private publicKey: PublicKey;
constructor(publicKey: PublicKey) {
if (!(publicKey instanceof PublicKey)) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"invalid argument: expected PublicKey"
);
}
this.publicKey = publicKey;
}
verify(message: Uint8Array) {
message = coerceToBytes(message);
if (message.length == 0) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"message must be not empty"
);
}
let status;
/// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten
let result_length_ptr = context.libthemis!!.allocate(
new ArrayBuffer(4),
context.libthemis!!.ALLOC_STACK
);
let public_key_ptr, message_ptr, result_ptr, result_length;
try {
public_key_ptr = heapAlloc(this.publicKey.length);
message_ptr = heapAlloc(message.length);
if (!public_key_ptr || !message_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
heapPutArray(this.publicKey, public_key_ptr);
heapPutArray(message, message_ptr);
status = context.libthemis!!._themis_secure_message_verify(
public_key_ptr,
this.publicKey.length,
message_ptr,
message.length,
null,
result_length_ptr
);
if (status != ThemisErrorCode.BUFFER_TOO_SMALL) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = context.libthemis!!.getValue(result_length_ptr, "i32");
result_ptr = heapAlloc(result_length);
if (!result_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
status = context.libthemis!!._themis_secure_message_verify(
public_key_ptr,
this.publicKey.length,
message_ptr,
message.length,
result_ptr,
result_length_ptr
);
if (status != ThemisErrorCode.SUCCESS) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = context.libthemis!!.getValue(result_length_ptr, "i32");
return heapGetArray(result_ptr, result_length);
} finally {
heapFree(public_key_ptr, this.publicKey.length);
heapFree(message_ptr, message.length);
heapFree(result_ptr, result_length);
}
}
} | the_stack |
import { ChangeLogItem, ChangeLogKind, ContentProvider, Header, Image, Sponsor, IssueKind, SupportChannel, SocialMediaProvider } from "../../vscode-whats-new/src/ContentProvider";
export class NumberedBookmarksContentProvider implements ContentProvider {
public provideHeader(logoUrl: string): Header {
return <Header> {logo: <Image> {src: logoUrl, height: 50, width: 50},
message: `<b>Numbered Bookmarks</b> helps you to navigate in your code, <b>moving</b>
between important positions easily and quickly. No more need
to <i>search for code</i>. All of this in <b><i>Delphi style</i></b>`};
}
public provideChangeLog(): ChangeLogItem[] {
const changeLog: ChangeLogItem[] = [];
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "8.2.0", releaseDate: "September 2021" } });
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "New <b>Sticky Engine</b> with improved support to Formatters, Multi-cursor and Undo operations",
id: 115,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Bookmarks removes on Undo",
id: 47,
kind: IssueKind.Issue
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "8.1.0", releaseDate: "May 2021" } });
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support <b>Virtual Workspaces</b>",
id: 107,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support <b>Workspace Trust</b>",
id: 108,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support Translation",
id: 112,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Return to line/column when cancel List or List from All Files",
id: 96,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Security Alert: lodash",
id: 109,
kind: IssueKind.PR,
kudos: "dependabot"
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Security Alert: ssri",
id: 106,
kind: IssueKind.PR,
kudos: "dependabot"
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Security Alert: y18n",
id: 104,
kind: IssueKind.PR,
kudos: "dependabot"
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "8.0.3", releaseDate: "March 2021" } });
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Bookmarks on deleted/missing files breaks jumping",
id: 102,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Running the contributed command: <b>numberedBookmarks.toggleBookmark1</b> failed",
id: 100,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Toggling bookmarks on Untitled documents does not work bug",
id: 99,
kind: IssueKind.Issue
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "8.0.2", releaseDate: "February 2021" } });
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Command `Toggle` not found - loading empty workspace with random files",
id: 97,
kind: IssueKind.Issue
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "8.0.1", releaseDate: "February 2021" } });
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Extension does not activate on VS Code 1.50",
id: 98,
kind: IssueKind.Issue
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "8.0.0", releaseDate: "February 2021" } });
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Improvements on <b>multi-root</b> support",
id: 92,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Cross-platform support",
id: 94,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support <b>Remote Development</b>",
id: 63,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support column position",
id: 14,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Error using <b>Toggle Bookmark</b> command with <b>saveBookmarksInProject</b>",
id: 69,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Do not show welcome message if installed by Settings Sync",
id: 95,
kind: IssueKind.Issue
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "7.3.0", releaseDate: "January 2021" } });
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "Support <b>submenu</b> for editor commands",
id: 84,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.NEW,
detail: {
message: "New <b>setting</b> to decide if should show a warning when a bookmark is not defined",
id: 73,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.FIXED,
detail: {
message: "Typo in extension's configuration title",
id: 89,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Shrink installation size",
id: 53,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Update <b>what-new</b> submodule API",
id: 85,
kind: IssueKind.Issue
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "7.2.0", releaseDate: "September 2020" } });
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Use <b>vscode-ext-codicons</b> package",
id: 80,
kind: IssueKind.Issue
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Migrate from TSLint to ESLint",
id: 75,
kind: IssueKind.Issue
}
});
changeLog.push({ kind: ChangeLogKind.VERSION, detail: { releaseNumber: "7.1.3", releaseDate: "August 2020" } });
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Security Alert: elliptic",
id: 79,
kind: IssueKind.PR,
kudos: "dependabot"
}
});
changeLog.push({
kind: ChangeLogKind.INTERNAL,
detail: {
message: "Security Alert: lodash",
id: 77,
kind: IssueKind.PR,
kudos: "dependabot"
}
});
return changeLog;
}
public provideSupportChannels(): SupportChannel[] {
const supportChannels: SupportChannel[] = [];
supportChannels.push({
title: "Become a sponsor on Patreon",
link: "https://www.patreon.com/alefragnani",
message: "Become a Sponsor"
});
supportChannels.push({
title: "Donate via PayPal",
link: "https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=EP57F3B6FXKTU&lc=US&item_name=Alessandro%20Fragnani&item_number=vscode%20extensions¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted",
message: "Donate via PayPal"
});
return supportChannels;
}
}
export class NumberedBookmarksSocialMediaProvider implements SocialMediaProvider {
public provideSocialMedias() {
return [{
title: "Follow me on Twitter",
link: "https://www.twitter.com/alefragnani"
}];
}
} | the_stack |
import {Mutable, Cursor} from "@swim/util";
import type {FastenerOwner} from "@swim/component";
import {AnyValue, Value, Form} from "@swim/structure";
import {Uri} from "@swim/uri";
import type {ListDownlinkObserver, ListDownlink} from "../downlink/ListDownlink";
import type {WarpRef} from "../ref/WarpRef";
import {DownlinkFastenerInit, DownlinkFastenerClass, DownlinkFastener} from "./DownlinkFastener";
/** @internal */
export type ListDownlinkFastenerType<F extends ListDownlinkFastener<any, any>> =
F extends ListDownlinkFastener<any, infer V, any> ? V : never;
/** @internal */
export type ListDownlinkFastenerInitType<F extends ListDownlinkFastener<any, any>> =
F extends ListDownlinkFastener<any, infer V, infer VU> ? V | VU : never;
/** @beta */
export interface ListDownlinkFastenerInit<V = unknown, VU = V> extends DownlinkFastenerInit, ListDownlinkObserver<V, VU> {
extends?: {prototype: ListDownlinkFastener<any, any>} | string | boolean | null;
valueForm?: Form<V, VU>;
initDownlink?(downlink: ListDownlink<V, VU>): ListDownlink<V, VU>;
}
/** @beta */
export type ListDownlinkFastenerDescriptor<O = unknown, V = unknown, VU = V, I = {}> = ThisType<ListDownlinkFastener<O, V, VU> & I> & ListDownlinkFastenerInit<V, VU> & Partial<I>;
/** @beta */
export interface ListDownlinkFastenerClass<F extends ListDownlinkFastener<any, any> = ListDownlinkFastener<any, any>> extends DownlinkFastenerClass<F> {
}
/** @beta */
export interface ListDownlinkFastenerFactory<F extends ListDownlinkFastener<any, any> = ListDownlinkFastener<any, any>> extends ListDownlinkFastenerClass<F> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): ListDownlinkFastenerFactory<F> & I;
define<O, V extends Value = Value, VU extends AnyValue = AnyValue>(className: string, descriptor: ListDownlinkFastenerDescriptor<O, V, VU>): ListDownlinkFastenerFactory<ListDownlinkFastener<any, V, VU>>;
define<O, V, VU = V>(className: string, descriptor: {valueForm: Form<V, VU>} & ListDownlinkFastenerDescriptor<O, V, VU>): ListDownlinkFastenerFactory<ListDownlinkFastener<any, V, VU>>;
define<O, V extends Value, VU extends AnyValue = AnyValue, I = {}>(className: string, descriptor: {implements: unknown} & ListDownlinkFastenerDescriptor<O, V, VU, I>): ListDownlinkFastenerFactory<ListDownlinkFastener<any, V, VU> & I>;
define<O, V, VU = V, I = {}>(className: string, descriptor: {implements: unknown; valueForm: Form<V, VU>} & ListDownlinkFastenerDescriptor<O, V, VU, I>): ListDownlinkFastenerFactory<ListDownlinkFastener<any, V, VU> & I>;
<O, V extends Value = Value, VU extends AnyValue = AnyValue>(descriptor: ListDownlinkFastenerDescriptor<O, V, VU>): PropertyDecorator;
<O, V, VU = V>(descriptor: {valueForm: Form<V, VU>} & ListDownlinkFastenerDescriptor<O, V, VU>): PropertyDecorator;
<O, V extends Value, VU extends AnyValue = AnyValue, I = {}>(descriptor: {implements: unknown} & ListDownlinkFastenerDescriptor<O, V, VU, I>): PropertyDecorator;
<O, V, VU = V, I = {}>(descriptor: {implements: unknown; valueForm: Form<V, VU>} & ListDownlinkFastenerDescriptor<O, V, VU, I>): PropertyDecorator;
}
/** @beta */
export interface ListDownlinkFastener<O = unknown, V = unknown, VU = V> extends DownlinkFastener<O> {
(index: number): V | undefined;
(index: number, newObject: V | VU): O;
/** @internal */
readonly ownValueForm: Form<V, VU> | null;
get length(): number;
valueForm(): Form<V, VU> | null;
valueForm(valueForm: Form<V, VU> | null): this;
isEmpty(): boolean;
get(index: number, id?: Value): V | undefined;
getEntry(index: number, id?: Value): [V, Value] | undefined;
set(index: number, newObject: V | VU, id?: Value): this;
insert(index: number, newObject: V | VU, id?: Value): this;
remove(index: number, id?: Value): this;
push(...newObjects: (V | VU)[]): number;
pop(): V | undefined;
unshift(...newObjects: (V | VU)[]): number;
shift(): V | undefined;
move(fromIndex: number, toIndex: number, id?: Value): this;
splice(start: number, deleteCount?: number, ...newObjects: (V | VU)[]): V[];
clear(): void;
forEach<T>(callback: (value: V, index: number, id: Value) => T | void): T | undefined;
forEach<T, S>(callback: (this: S, value: V, index: number, id: Value) => T | void, thisArg: S): T | undefined;
values(): Cursor<V>;
keys(): Cursor<Value>;
entries(): Cursor<[Value, V]>;
/** @override */
readonly downlink: ListDownlink<V, VU> | null;
/** @internal @override */
createDownlink(warp: WarpRef): ListDownlink<V, VU>;
/** @internal @override */
bindDownlink(downlink: ListDownlink<V, VU>): ListDownlink<V, VU>;
/** @internal */
initDownlink?(downlink: ListDownlink<V, VU>): ListDownlink<V, VU>;
}
/** @beta */
export const ListDownlinkFastener = (function (_super: typeof DownlinkFastener) {
const ListDownlinkFastener: ListDownlinkFastenerFactory = _super.extend("ListDownlinkFastener");
ListDownlinkFastener.prototype.valueForm = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>, valueForm?: Form<V, VU> | null): Form<V, VU> | null | typeof this {
if (valueForm === void 0) {
return this.ownValueForm;
} else {
if (this.ownValueForm !== valueForm) {
(this as Mutable<typeof this>).ownValueForm = valueForm;
this.relink();
}
return this;
}
} as typeof ListDownlinkFastener.prototype.valueForm;
Object.defineProperty(ListDownlinkFastener.prototype, "length", {
get: function (this: ListDownlinkFastener<unknown>): number {
const downlink = this.downlink;
return downlink !== null ? downlink.length : 0;
},
configurable: true,
});
ListDownlinkFastener.prototype.isEmpty = function (this: ListDownlinkFastener<unknown>): boolean {
const downlink = this.downlink;
return downlink !== null ? downlink.isEmpty() : true;
};
ListDownlinkFastener.prototype.get = function <V>(this: ListDownlinkFastener<unknown, V>, index: number, id?: Value): V | undefined {
const downlink = this.downlink;
return downlink !== null ? downlink.get(index, id) : void 0;
};
ListDownlinkFastener.prototype.getEntry = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>, index: number, id?: Value): [V, Value] | undefined {
const downlink = this.downlink;
return downlink !== null ? downlink.getEntry(index, id) : void 0;
};
ListDownlinkFastener.prototype.set = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>, index: number, newObject: V | VU, id?: Value): ListDownlinkFastener<unknown, V, VU> {
const downlink = this.downlink;
if (downlink != null) {
downlink.set(index, newObject, id);
}
return this;
};
ListDownlinkFastener.prototype.insert = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>, index: number, newObject: V | VU, id?: Value): ListDownlinkFastener<unknown, V, VU> {
const downlink = this.downlink;
if (downlink != null) {
downlink.insert(index, newObject, id);
}
return this;
};
ListDownlinkFastener.prototype.remove = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>, index: number, id?: Value): ListDownlinkFastener<unknown, V, VU> {
const downlink = this.downlink;
if (downlink != null) {
downlink.remove(index, id);
}
return this;
};
ListDownlinkFastener.prototype.push = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>, ...newObjects: (V | VU)[]): number {
const downlink = this.downlink;
return downlink !== null ? downlink.push(...newObjects) : 0;
};
ListDownlinkFastener.prototype.pop = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>): V | undefined {
const downlink = this.downlink;
return downlink !== null ? downlink.pop() : void 0;
};
ListDownlinkFastener.prototype.unshift = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>, ...newObjects: (V | VU)[]): number {
const downlink = this.downlink;
return downlink !== null ? downlink.unshift(...newObjects) : 0;
};
ListDownlinkFastener.prototype.shift = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>): V | undefined {
const downlink = this.downlink;
return downlink !== null ? downlink.shift() : void 0;
};
ListDownlinkFastener.prototype.move = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>, fromIndex: number, toIndex: number, id?: Value): ListDownlinkFastener<unknown, V, VU> {
const downlink = this.downlink;
if (downlink != null) {
downlink.move(fromIndex, toIndex, id);
}
return this;
};
ListDownlinkFastener.prototype.splice = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>, start: number, deleteCount?: number, ...newObjects: (V | VU)[]): V[] {
const downlink = this.downlink;
return downlink !== null ? downlink.splice(start, deleteCount, ...newObjects) : [];
};
ListDownlinkFastener.prototype.clear = function (this: ListDownlinkFastener<unknown>): void {
const downlink = this.downlink;
if (downlink != null) {
downlink.clear();
}
};
ListDownlinkFastener.prototype.forEach = function <V, VU, T, S>(this: ListDownlinkFastener<unknown, V, VU>, callback: (this: S | undefined, value: V, index: number, id: Value) => T | void, thisArg?: S): T | undefined {
const downlink = this.downlink;
return downlink !== null ? downlink.forEach(callback, thisArg) : void 0;
};
ListDownlinkFastener.prototype.values = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>): Cursor<V> {
const downlink = this.downlink;
return downlink !== null ? downlink.values() : Cursor.empty();
};
ListDownlinkFastener.prototype.keys = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>): Cursor<Value> {
const downlink = this.downlink;
return downlink !== null ? downlink.keys() : Cursor.empty();
};
ListDownlinkFastener.prototype.entries = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>): Cursor<[Value, V]> {
const downlink = this.downlink;
return downlink !== null ? downlink.entries() : Cursor.empty();
};
ListDownlinkFastener.prototype.createDownlink = function <V, VU>(this: ListDownlinkFastener<unknown, V, VU>, warp: WarpRef): ListDownlink<V, VU> {
let downlink = warp.downlinkList() as unknown as ListDownlink<V, VU>;
if (this.ownValueForm !== null) {
downlink = downlink.valueForm(this.ownValueForm);
}
return downlink;
};
ListDownlinkFastener.construct = function <F extends ListDownlinkFastener<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
if (fastener === null) {
fastener = function (index: number, value?: ListDownlinkFastenerType<F> | ListDownlinkFastenerInitType<F>): ListDownlinkFastenerType<F> | undefined | FastenerOwner<F> {
if (arguments.length === 0) {
return fastener!.get(index);
} else {
fastener!.set(index, value!);
return fastener!.owner;
}
} as F;
delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name
Object.setPrototypeOf(fastener, fastenerClass.prototype);
}
fastener = _super.construct(fastenerClass, fastener, owner) as F;
(fastener as Mutable<typeof fastener>).ownValueForm = null;
return fastener;
};
ListDownlinkFastener.define = function <O, V, VU>(className: string, descriptor: ListDownlinkFastenerDescriptor<O, V, VU>): ListDownlinkFastenerFactory<ListDownlinkFastener<any, V, VU>> {
let superClass = descriptor.extends as ListDownlinkFastenerFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
const valueForm = descriptor.valueForm;
let hostUri = descriptor.hostUri;
let nodeUri = descriptor.nodeUri;
let laneUri = descriptor.laneUri;
let prio = descriptor.prio;
let rate = descriptor.rate;
let body = descriptor.body;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
delete descriptor.valueForm;
delete descriptor.hostUri;
delete descriptor.nodeUri;
delete descriptor.laneUri;
delete descriptor.prio;
delete descriptor.rate;
delete descriptor.body;
if (superClass === void 0 || superClass === null) {
superClass = this;
}
const fastenerClass = superClass.extend(className, descriptor);
fastenerClass.construct = function (fastenerClass: {prototype: ListDownlinkFastener<any, any>}, fastener: ListDownlinkFastener<O, V, VU> | null, owner: O): ListDownlinkFastener<O, V, VU> {
fastener = superClass!.construct(fastenerClass, fastener, owner);
if (affinity !== void 0) {
fastener.initAffinity(affinity);
}
if (inherits !== void 0) {
fastener.initInherits(inherits);
}
if (hostUri !== void 0) {
(fastener as Mutable<typeof fastener>).ownHostUri = hostUri as Uri;
}
if (nodeUri !== void 0) {
(fastener as Mutable<typeof fastener>).ownNodeUri = nodeUri as Uri;
}
if (laneUri !== void 0) {
(fastener as Mutable<typeof fastener>).ownLaneUri = laneUri as Uri;
}
if (prio !== void 0) {
(fastener as Mutable<typeof fastener>).ownPrio = prio as number;
}
if (rate !== void 0) {
(fastener as Mutable<typeof fastener>).ownRate = rate as number;
}
if (body !== void 0) {
(fastener as Mutable<typeof fastener>).ownBody = body as Value;
}
if (valueForm !== void 0) {
(fastener as Mutable<typeof fastener>).ownValueForm = valueForm;
}
return fastener;
};
if (typeof hostUri === "function") {
fastenerClass.prototype.initHostUri = hostUri;
hostUri = void 0;
} else if (hostUri !== void 0) {
hostUri = Uri.fromAny(hostUri);
}
if (typeof nodeUri === "function") {
fastenerClass.prototype.initNodeUri = nodeUri;
nodeUri = void 0;
} else if (nodeUri !== void 0) {
nodeUri = Uri.fromAny(nodeUri);
}
if (typeof laneUri === "function") {
fastenerClass.prototype.initLaneUri = laneUri;
laneUri = void 0;
} else if (laneUri !== void 0) {
laneUri = Uri.fromAny(laneUri);
}
if (typeof prio === "function") {
fastenerClass.prototype.initPrio = prio;
prio = void 0;
}
if (typeof rate === "function") {
fastenerClass.prototype.initRate = rate;
rate = void 0;
}
if (typeof body === "function") {
fastenerClass.prototype.initBody = body;
body = void 0;
} else if (body !== void 0) {
body = Value.fromAny(body);
}
return fastenerClass;
};
return ListDownlinkFastener;
})(DownlinkFastener); | the_stack |
import * as assert from 'assert';
import * as path from 'path';
import * as sinon from 'sinon';
import * as fsWatcher from '../../../../../client/common/platform/fileSystemWatcher';
import * as platformUtils from '../../../../../client/common/utils/platform';
import { PythonEnvKind } from '../../../../../client/pythonEnvironments/base/info';
import { getEnvs } from '../../../../../client/pythonEnvironments/base/locatorUtils';
import { PythonEnvsChangedEvent } from '../../../../../client/pythonEnvironments/base/watcher';
import * as externalDependencies from '../../../../../client/pythonEnvironments/common/externalDependencies';
import {
CustomVirtualEnvironmentLocator,
VENVFOLDERS_SETTING_KEY,
VENVPATH_SETTING_KEY,
} from '../../../../../client/pythonEnvironments/base/locators/lowLevel/customVirtualEnvLocator';
import { createBasicEnv } from '../../common';
import { TEST_LAYOUT_ROOT } from '../../../common/commonTestConstants';
import { assertBasicEnvsEqual } from '../envTestUtils';
suite('CustomVirtualEnvironment Locator', () => {
const testVirtualHomeDir = path.join(TEST_LAYOUT_ROOT, 'virtualhome');
const testVenvPathWithTilda = path.join('~', 'customfolder');
let getUserHomeDirStub: sinon.SinonStub;
let getOSTypeStub: sinon.SinonStub;
let readFileStub: sinon.SinonStub;
let locator: CustomVirtualEnvironmentLocator;
let watchLocationForPatternStub: sinon.SinonStub;
let getPythonSettingStub: sinon.SinonStub;
let onDidChangePythonSettingStub: sinon.SinonStub;
let untildify: sinon.SinonStub;
setup(async () => {
untildify = sinon.stub(externalDependencies, 'untildify');
untildify.callsFake((value: string) => value.replace('~', testVirtualHomeDir));
getUserHomeDirStub = sinon.stub(platformUtils, 'getUserHomeDir');
getUserHomeDirStub.returns(testVirtualHomeDir);
getPythonSettingStub = sinon.stub(externalDependencies, 'getPythonSetting');
getOSTypeStub = sinon.stub(platformUtils, 'getOSType');
getOSTypeStub.returns(platformUtils.OSType.Linux);
watchLocationForPatternStub = sinon.stub(fsWatcher, 'watchLocationForPattern');
watchLocationForPatternStub.returns({
dispose: () => {
/* do nothing */
},
});
onDidChangePythonSettingStub = sinon.stub(externalDependencies, 'onDidChangePythonSetting');
onDidChangePythonSettingStub.returns({
dispose: () => {
/* do nothing */
},
});
const expectedDotProjectFile = path.join(
testVirtualHomeDir,
'.local',
'share',
'virtualenvs',
'project2-vnNIWe9P',
'.project',
);
readFileStub = sinon.stub(externalDependencies, 'readFile');
readFileStub.withArgs(expectedDotProjectFile).returns(path.join(TEST_LAYOUT_ROOT, 'pipenv', 'project2'));
readFileStub.callThrough();
locator = new CustomVirtualEnvironmentLocator();
});
teardown(async () => {
await locator.dispose();
sinon.restore();
});
test('iterEnvs(): Windows with both settings set', async () => {
getPythonSettingStub.withArgs('venvPath').returns(testVenvPathWithTilda);
getPythonSettingStub.withArgs('venvFolders').returns(['.venvs', '.virtualenvs', 'Envs']);
getOSTypeStub.returns(platformUtils.OSType.Windows);
const expectedEnvs = [
createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'win1', 'python.exe')),
createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'win2', 'bin', 'python.exe')),
createBasicEnv(
PythonEnvKind.VirtualEnv,
path.join(testVirtualHomeDir, '.virtualenvs', 'win1', 'python.exe'),
),
createBasicEnv(
PythonEnvKind.VirtualEnv,
path.join(testVirtualHomeDir, '.virtualenvs', 'win2', 'bin', 'python.exe'),
),
createBasicEnv(
PythonEnvKind.VirtualEnvWrapper,
path.join(testVirtualHomeDir, 'Envs', 'wrapper_win1', 'python.exe'),
),
createBasicEnv(
PythonEnvKind.VirtualEnvWrapper,
path.join(testVirtualHomeDir, 'Envs', 'wrapper_win2', 'bin', 'python.exe'),
),
createBasicEnv(
PythonEnvKind.VirtualEnv,
path.join(testVirtualHomeDir, 'customfolder', 'win1', 'python.exe'),
),
createBasicEnv(
PythonEnvKind.VirtualEnv,
path.join(testVirtualHomeDir, 'customfolder', 'win2', 'bin', 'python.exe'),
),
];
const iterator = locator.iterEnvs();
const actualEnvs = await getEnvs(iterator);
assertBasicEnvsEqual(actualEnvs, expectedEnvs);
});
test('iterEnvs(): Non-Windows with both settings set', async () => {
const testWorkspaceFolder = path.join(TEST_LAYOUT_ROOT, 'workspace', 'folder1');
getPythonSettingStub.withArgs('venvPath').returns(path.join(testWorkspaceFolder, 'posix2conda'));
getPythonSettingStub
.withArgs('venvFolders')
.returns(['.venvs', '.virtualenvs', 'envs', path.join('.local', 'share', 'virtualenvs')]);
const expectedEnvs = [
createBasicEnv(PythonEnvKind.Unknown, path.join(testWorkspaceFolder, 'posix2conda', 'python')),
createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'posix1', 'python')),
createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'posix2', 'bin', 'python')),
createBasicEnv(
PythonEnvKind.VirtualEnvWrapper,
path.join(testVirtualHomeDir, '.virtualenvs', 'posix1', 'python'),
),
createBasicEnv(
PythonEnvKind.VirtualEnvWrapper,
path.join(testVirtualHomeDir, '.virtualenvs', 'posix2', 'bin', 'python'),
),
createBasicEnv(
PythonEnvKind.Pipenv,
path.join(testVirtualHomeDir, '.local', 'share', 'virtualenvs', 'project2-vnNIWe9P', 'bin', 'python'),
),
];
const iterator = locator.iterEnvs();
const actualEnvs = await getEnvs(iterator);
assertBasicEnvsEqual(actualEnvs, expectedEnvs);
});
test('iterEnvs(): No User home dir set', async () => {
getUserHomeDirStub.returns(undefined);
getPythonSettingStub.withArgs('venvPath').returns(testVenvPathWithTilda);
getPythonSettingStub.withArgs('venvFolders').returns(['.venvs', '.virtualenvs', 'Envs']);
getOSTypeStub.returns(platformUtils.OSType.Windows);
const expectedEnvs = [
createBasicEnv(
PythonEnvKind.VirtualEnv,
path.join(testVirtualHomeDir, 'customfolder', 'win1', 'python.exe'),
),
createBasicEnv(
PythonEnvKind.VirtualEnv,
path.join(testVirtualHomeDir, 'customfolder', 'win2', 'bin', 'python.exe'),
),
];
const iterator = locator.iterEnvs();
const actualEnvs = await getEnvs(iterator);
assertBasicEnvsEqual(actualEnvs, expectedEnvs);
});
test('iterEnvs(): with only venvFolders set', async () => {
getPythonSettingStub.withArgs('venvFolders').returns(['.venvs', '.virtualenvs', 'Envs']);
getOSTypeStub.returns(platformUtils.OSType.Windows);
const expectedEnvs = [
createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'win1', 'python.exe')),
createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'win2', 'bin', 'python.exe')),
createBasicEnv(
PythonEnvKind.VirtualEnv,
path.join(testVirtualHomeDir, '.virtualenvs', 'win1', 'python.exe'),
),
createBasicEnv(
PythonEnvKind.VirtualEnv,
path.join(testVirtualHomeDir, '.virtualenvs', 'win2', 'bin', 'python.exe'),
),
createBasicEnv(
PythonEnvKind.VirtualEnvWrapper,
path.join(testVirtualHomeDir, 'Envs', 'wrapper_win1', 'python.exe'),
),
createBasicEnv(
PythonEnvKind.VirtualEnvWrapper,
path.join(testVirtualHomeDir, 'Envs', 'wrapper_win2', 'bin', 'python.exe'),
),
];
const iterator = locator.iterEnvs();
const actualEnvs = await getEnvs(iterator);
assertBasicEnvsEqual(actualEnvs, expectedEnvs);
});
test('iterEnvs(): with only venvPath set', async () => {
const testWorkspaceFolder = path.join(TEST_LAYOUT_ROOT, 'workspace', 'folder1');
getPythonSettingStub.withArgs('venvPath').returns(path.join(testWorkspaceFolder, 'posix2conda'));
const expectedEnvs = [
createBasicEnv(PythonEnvKind.Unknown, path.join(testWorkspaceFolder, 'posix2conda', 'python')),
];
const iterator = locator.iterEnvs();
const actualEnvs = await getEnvs(iterator);
assertBasicEnvsEqual(actualEnvs, expectedEnvs);
});
test('onChanged fires if venvPath setting changes', async () => {
const events: PythonEnvsChangedEvent[] = [];
const expected: PythonEnvsChangedEvent[] = [{}];
locator.onChanged((e) => events.push(e));
await getEnvs(locator.iterEnvs());
const venvPathCall = onDidChangePythonSettingStub
.getCalls()
.filter((c) => c.args[0] === VENVPATH_SETTING_KEY)[0];
const callback = venvPathCall.args[1];
callback(); // Callback is called when venvPath setting changes
assert.deepEqual(events, expected, 'Unexpected events');
});
test('onChanged fires if venvFolders setting changes', async () => {
const events: PythonEnvsChangedEvent[] = [];
const expected: PythonEnvsChangedEvent[] = [{}];
locator.onChanged((e) => events.push(e));
await getEnvs(locator.iterEnvs());
const venvFoldersCall = onDidChangePythonSettingStub
.getCalls()
.filter((c) => c.args[0] === VENVFOLDERS_SETTING_KEY)[0];
const callback = venvFoldersCall.args[1];
callback(); // Callback is called when venvFolders setting changes
assert.deepEqual(events, expected, 'Unexpected events');
});
}); | the_stack |
import { mechanicsEngine } from "..";
/**
* Stuff to access the file system on Cordova app
*/
export const cordovaFS = {
/**
* The current download (see downloadAsync and cancelCurrentDownload)
*/
currentDownload: null as FileTransfer,
// TODO: Replace this with functions with Promises
saveFile(originalFileName: string, fileContent: Blob, callback: () => void) {
cordovaFS.requestFileSystemAsync()
.then((fs: FileSystem) => {
console.log("file system open: " + fs.name);
cordovaFS.getUnusedName(originalFileName, fs, (fileName) => {
// Get the file to save
fs.root.getFile(fileName,
{
create: true,
exclusive: false
},
(fileEntry) => {
console.log("fileEntry is file?" + fileEntry.isFile.toString());
cordovaFS.writeFile(fileEntry, fileContent, callback);
},
() => { alert("Error getting file"); }
);
});
},
() => { alert("Error requesting file system"); });
},
// TODO: Remove this and use writeFileContentAsync
writeFile(fileEntry: FileEntry, fileContent: Blob, callback: () => void) {
cordovaFS.writeFileContentAsync(fileEntry, fileContent)
.then(() => { callback(); });
},
/**
* Write a content on a file
* @param fileEntry The file to write
* @param fileContent The file content
* @returns Promise with the write process. The parameter is the written file entry
*/
writeFileContentAsync(fileEntry: FileEntry, fileContent: Blob): JQueryPromise<FileEntry> {
const dfd = jQuery.Deferred<FileEntry>();
cordovaFS.createWriterAsync(fileEntry)
.then((fileWriter: FileWriter) => {
fileWriter.onwriteend = () => {
console.log("Successful file write");
dfd.resolve(fileEntry);
};
fileWriter.onerror = (error) => {
let msg = "Failed to write file";
if (error) {
msg += ": " + error.toString();
}
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
};
fileWriter.write(fileContent);
});
return dfd.promise();
},
/**
* Creates a new FileWriter associated with a file
* @param fileEntry The file
* @returns Promise with the new FileWriter
*/
createWriterAsync(fileEntry: FileEntry): JQueryPromise<FileWriter> {
const dfd = jQuery.Deferred<FileWriter>();
fileEntry.createWriter(
(fileWriter: FileWriter) => {
dfd.resolve(fileWriter);
},
(error: FileError) => {
const msg = "Error creating file writer. Code: " + error.code;
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
}
);
return dfd.promise();
},
/**
* Get the name and extension of a file name
* @param fileName The file name to check
* @returns The name and extension. The extension will be an empty string, if no extension was found
*/
getFileNameAndExtension(fileName: string): { name: string, extension: string } {
const idx = fileName.lastIndexOf(".");
if (idx < 0) {
return { name: fileName, extension: "" };
}
return {
name: fileName.substr(0, idx),
extension: fileName.substr(idx + 1)
};
},
/**
* Get an unused name "version" for a file name.
* If the file name is "a.ext", and it exists, it will return a "a-xxx.ext", where xxx is a number
* TODO: Change to return a Promise
* @param fileName The file name to check
* @param fs The file system. We will check existing files on the root directory
* @param callback Callback to call with the new file name
*/
getUnusedName(fileName: string, fs: FileSystem, callback: (fileName: string) => void) {
const nameAndExtension = cordovaFS.getFileNameAndExtension(fileName);
cordovaFS.enumerateFiles(fs, (entries) => {
console.log("Searching unused name for " + fileName);
let idx = 0;
const hasSameName = (f) => f.name === fileName;
while (true) {
fileName = nameAndExtension.name + (idx > 0 ? "-" + idx : "") + "." + nameAndExtension.extension;
console.log("Checking " + fileName);
if (entries.some(hasSameName)) {
idx++;
continue;
}
try {
callback(fileName);
} catch (ex) {
mechanicsEngine.debugWarning("Error calling callback: " + ex.toString());
}
return;
}
});
},
// TODO: Remove this and use getRootFilesAsync
enumerateFiles(fs: FileSystem, callback: (entries: Entry[]) => void) {
console.log("file system open: " + fs.name);
const dirReader = fs.root.createReader();
dirReader.readEntries(
(entries) => {
console.log("Got list of files. Running callback");
callback(entries);
console.log("Callback finished");
},
() => {
mechanicsEngine.debugWarning("Error listing files");
alert("Error listing files");
callback([]);
}
);
},
/**
* Get the the entries contained on the file system root directory
* @param fs The cordova file sytem
* @returns Promise with array of entries on the root file system
*/
getRootFilesAsync(fs: FileSystem): JQueryPromise<Entry[]> {
console.log("file system open: " + fs.name);
return cordovaFS.readEntriesAsync(fs.root);
},
/**
* Get the the entries contained on a directory
* @param dirEntry The directory to read
* @returns Promise with array of entries on the directory
*/
readEntriesAsync(dirEntry: DirectoryEntry): JQueryPromise<Entry[]> {
const dfd = jQuery.Deferred<Entry[]>();
const dirReader = dirEntry.createReader();
dirReader.readEntries(
(entries: Entry[]) => {
console.log("Got list of files");
dfd.resolve(entries);
},
(error: FileError) => {
const msg = "Error listing files. Error code: " + error.code;
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
}
);
return dfd.promise();
},
/**
* Copy a file to other directory
* @param fileEntry The file / directory to copy
* @param parent The destination directory
* @param newFileName The new file name. If it's null, it will be the original
* @returns Promise with the new copied file
*/
copyToAsync(fileEntry: Entry, parent: DirectoryEntry, newFileName: string = null): JQueryPromise<Entry> {
const dfd = jQuery.Deferred<Entry>();
fileEntry.copyTo(parent, newFileName,
(entry: Entry) => {
dfd.resolve(entry);
},
(error: FileError) => {
const msg = "Error copying file. Error code: " + error.code;
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
}
);
return dfd.promise();
},
/**
* Copy a set of files to other directory
* @param entries The files to copy
* @param parent The destination directory
* @returns Promise with the copy process
*/
copySetToAsync(entries: Entry[], parent: DirectoryEntry): JQueryPromise<void> {
console.log("Copying " + entries.length + " files to other directory");
const promises: Array< JQueryPromise<Entry> > = [];
for (const entry of entries) {
promises.push( cordovaFS.copyToAsync(entry, parent) );
}
// Wait for all copys to finish
return $.when.apply($, promises);
},
/**
* Load the text content from a file on the root of the persistent file system.
* @param fileName The file name to read
* @returns The promise with the file content
*/
readRootTextFileAsync(fileName: string): JQueryPromise<string> {
return cordovaFS.requestFileSystemAsync()
.then((fs: FileSystem) => {
return cordovaFS.getFileAsync(fs.root, fileName);
})
.then((fileEntry: FileEntry) => {
return cordovaFS.readFileAsync(fileEntry, false) as JQueryPromise<string>;
});
},
/**
* Get a file from an FileEntry
* @param entry The entry
* @returns Promise with the File
*/
fileAsync(entry: FileEntry): JQueryPromise<File> {
const dfd = jQuery.Deferred<File>();
entry.file(
(file: File) => {
console.log("file call OK");
dfd.resolve(file);
},
(fileError: FileError) => {
const msg = "Error getting file: " + fileError.code;
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
}
);
return dfd.promise();
},
/**
* Read a file content
* @param entry The entry to read
* @param binary True if the content should be read as binary. False to read as text
* @returns Promise with the contet file (text or binary)
*/
readFileAsync(entry: FileEntry, binary: boolean): JQueryPromise<string|ArrayBuffer> {
const dfd = jQuery.Deferred<string|ArrayBuffer>();
cordovaFS.fileAsync(entry)
.then(
// tslint:disable-next-line only-arrow-functions
function(file: File) {
const reader = new FileReader();
reader.onloadend = function() {
console.log("File read finished");
dfd.resolve(this.result);
};
// Types for reader.onerror seem to be wrong. We asume the documentation is right:
reader.onerror = (error: any) => {
let msg = "Error reading file";
if (error && error.message) {
msg += ": " + error.message;
}
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
};
if (binary) {
// reader.readAsBinaryString(file);
reader.readAsArrayBuffer(file);
} else {
reader.readAsText(file);
}
},
(error: any) => { dfd.reject(error); }
);
return dfd.promise();
},
/**
* Delete file
* @param entry The file entry to delete
* @returns Promise with the deletion process
*/
deleteFileAsync(fileEntry: FileEntry): JQueryPromise<void> {
const dfd = jQuery.Deferred<void>();
console.log("Deleting file " + fileEntry.toURL());
fileEntry.remove(
() => {
console.log("File deleted");
dfd.resolve();
},
(error: FileError) => {
const msg = "Error deleting entry. Error code: " + error.code;
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
}
);
return dfd.promise();
},
/**
* Delete directory recursivelly
* @param directoryEntry The directory entry to delete
* @returns Promise with the deletion process
*/
deleteDirRecursivelyAsync(directoryEntry: DirectoryEntry): JQueryPromise<void> {
const dfd = jQuery.Deferred<void>();
console.log("Deleting directory " + directoryEntry.toURL());
directoryEntry.removeRecursively(
() => {
console.log("Directory deleted");
dfd.resolve();
},
(fileError) => {
dfd.reject("Error deleting directory " + directoryEntry.toURL() +
" (code " + fileError.code + ")");
}
);
return dfd.promise();
},
/**
* Requests a filesystem in which to store application data.
* TODO: Use this anywhere
* @returns Promise with the LocalFileSystem.PERSISTENT file System
*/
requestFileSystemAsync(): JQueryPromise<FileSystem> {
const dfd = jQuery.Deferred<FileSystem>();
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
(fileSystem) => {
dfd.resolve(fileSystem);
},
(fileError) => {
// TODO: Test this (codes?)
dfd.reject("Error requesting file system (code " + fileError.code + ")");
}
);
return dfd.promise();
},
/**
* Look up file system Entry referred to by local URI.
* @param uri URI referring to a local file or directory
* @returns Promise with the file / directory entry
*/
resolveLocalFileSystemURIAsync(uri: string): JQueryPromise<Entry> {
const dfd = jQuery.Deferred<Entry>();
window.resolveLocalFileSystemURI(uri,
(entry: Entry) => {
console.log("URI resolved");
dfd.resolve(entry);
},
(error: FileError) => {
const msg = "Error resolving local file URI (code " + error.code + ")";
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
}
);
return dfd.promise();
},
/**
* Creates or looks up a directory
* TODO: Use this anywhere
* @param dir The parent directory
* @param path Either an absolute path or a relative path from the parent directory to the directory to be looked up or created.
* @param options create : true to create the directory, if it does not exist
* @returns Promise with the directory
*/
getDirectoryAsync(dir: DirectoryEntry, path: string, options: Flags): JQueryPromise<DirectoryEntry> {
const dfd = jQuery.Deferred<DirectoryEntry>();
dir.getDirectory(path, options,
(subdir) => {
dfd.resolve(subdir);
},
(fileError) => {
// TODO: Test this (codes?)
dfd.reject("Error getting / creating directory " + dir.toURL() + "/" + path +
": (code " + fileError.code + ")");
}
);
return dfd.promise();
},
/**
* Get a file from a directory
* @param dir The directory
* @param fileName The file name to get / create
* @param options Options to get / create the file
* @returns Promise with the file
*/
getFileAsync(dir: DirectoryEntry, fileName: string, options: object = { create: false, exclusive: false }): JQueryPromise<FileEntry> {
const dfd = jQuery.Deferred<FileEntry>();
dir.getFile(fileName, options,
(fileEntry: FileEntry) => {
console.log("Got the file: " + fileName);
dfd.resolve(fileEntry);
},
(error: FileError) => {
const msg = "Error getting / creating file. Error code: " + error.code;
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
}
);
return dfd.promise();
},
/**
* Download a file from Internet
* @param url URL to dowload
* @param dstPath Destination path where the file will be download
* @param progressCallback Optional callback to call with the download progress. Parameter is the downloaded
* percentage (0.0 - 100.0)
* @returns Promise with the process. Parameter is the downloaded file FileEntry
*/
downloadAsync(url: string, dstPath: string, progressCallback: (percent: number) => void = null): JQueryPromise<FileEntry> {
const dfd = jQuery.Deferred<FileEntry>();
console.log("Downloading " + url + " to " + dstPath);
const fileTransfer = new FileTransfer();
cordovaFS.currentDownload = fileTransfer;
if (progressCallback) {
console.log("Registering progress callback");
fileTransfer.onprogress = (progressEvent) => {
if (!progressEvent.lengthComputable || progressEvent.total === 0) {
console.log("No computable length");
return;
}
const percent = (progressEvent.loaded / progressEvent.total) * 100.0;
console.log("Calling progress callback (" + percent + "%)");
progressCallback(percent);
};
} else {
console.log("No callback progress");
}
fileTransfer.download(url, dstPath,
(zipFileEntry) => {
// Download ok
cordovaFS.currentDownload = null;
dfd.resolve(zipFileEntry);
},
(fileTransferError) => {
// Download failed
cordovaFS.currentDownload = null;
let msg = "Download of " + url + " to " + dstPath + " failed.\n Code: " + fileTransferError.code;
if (fileTransferError.http_status) {
msg += "\n http_status: " + fileTransferError.http_status.toString();
}
if (fileTransferError.exception) {
msg += "\n exception: " + fileTransferError.exception.toString();
}
dfd.reject(msg);
},
true
);
return dfd.promise();
},
cancelCurrentDownload() {
try {
if (!cordovaFS.currentDownload) {
return;
}
cordovaFS.currentDownload.abort();
} catch (e) {
mechanicsEngine.debugWarning(e);
}
},
zipAsync(dirToCompressPath: string, zipFilePath: string): JQueryPromise<void> {
const dfd = jQuery.Deferred<void>();
// Create the zip
Zeep.zip({ from: dirToCompressPath, to: zipFilePath },
() => {
console.log("Zip created succesfuly");
dfd.resolve();
},
(error) => {
let msg = "Error creating zip file";
if (error) {
msg += ": " + error.toString();
}
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
}
);
return dfd.promise();
},
/**
* Uncompress a zip file
* @param zipPath Path to the zip file
* @param dstDir Path to the directory where uncompress the zip file
* @returns Promise with the process
*/
unzipAsync(zipPath: string, dstDir: string): JQueryPromise<void> {
const dfd = jQuery.Deferred<void>();
console.log("Unzipping " + zipPath + " to " + dstDir);
zip.unzip(zipPath, dstDir, (resultCode) => {
// Check the unzip operation
if (resultCode === 0) {
dfd.resolve();
} else {
dfd.reject("Unknown error unzipping " + zipPath + " to " + dstDir);
}
});
return dfd.promise();
},
/**
* Copy a file to the Download directory, and notify the DownloadManager of that file.
* @param url URL / path to the local file to copy to the Download directory.
* @param title the title that would appear for this file in Downloads App.
* @param description the description that would appear for this file in Downloads App.
* @param mimeType mimetype of the file.
*/
copyToDownloadAsync(url: string, title: string, description: string, mimeType: string): JQueryPromise<void> {
const dfd = jQuery.Deferred<void>();
CopyToDownload.copyToDownload(url, title, description, false, mimeType, true,
() => {
console.log("copyToDownloadAsync ok");
dfd.resolve();
},
(error) => {
let msg = "error copying file to Download folder";
if (error) {
msg += ": " + error.toString();
}
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
}
);
return dfd.promise();
},
/**
* Copy a file with native filesystem URLs, without Cordova functions
* @param srcFileUrl URL to the source file to copy
* @param dstDirectoryUrl URL to the target directory where to copy
* @returns Promise with the process. The parameter is the FileEntry for the new copied file
*/
copyNativePathsAsync(srcFileUrl: string, dstDirectoryUrl: string): JQueryPromise<FileEntry> {
const dfd = jQuery.Deferred<string>();
// Do the copy
CopyToDownload.copyNativePaths(srcFileUrl, dstDirectoryUrl,
(dstFilePath: string) => {
console.log("copyNativePathsAsync ok");
dfd.resolve(dstFilePath);
},
(error) => {
let msg = "error copying file with native paths";
if (error) {
msg += ": " + error.toString();
}
mechanicsEngine.debugWarning(msg);
dfd.reject(msg);
}
);
// Return the FileEntry for the copied file
return dfd.promise()
.then((dstFilePath: string) => {
return cordovaFS.resolveLocalFileSystemURIAsync(dstFilePath) as JQueryPromise<FileEntry>;
});
}
}; | the_stack |
import utils from './utils.js';
import expect from 'expect';
import {
getTestState,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
itFailsFirefox,
describeFailsFirefox,
} from './mocha-utils'; // eslint-disable-line import/extensions
const bigint = typeof BigInt !== 'undefined';
describe('Evaluation specs', function () {
setupTestBrowserHooks();
setupTestPageAndContextHooks();
describe('Page.evaluate', function () {
it('should work', async () => {
const { page } = getTestState();
const result = await page.evaluate(() => 7 * 3);
expect(result).toBe(21);
});
(bigint ? it : xit)('should transfer BigInt', async () => {
const { page } = getTestState();
const result = await page.evaluate((a: BigInt) => a, BigInt(42));
expect(result).toBe(BigInt(42));
});
it('should transfer NaN', async () => {
const { page } = getTestState();
const result = await page.evaluate((a) => a, NaN);
expect(Object.is(result, NaN)).toBe(true);
});
it('should transfer -0', async () => {
const { page } = getTestState();
const result = await page.evaluate((a) => a, -0);
expect(Object.is(result, -0)).toBe(true);
});
it('should transfer Infinity', async () => {
const { page } = getTestState();
const result = await page.evaluate((a) => a, Infinity);
expect(Object.is(result, Infinity)).toBe(true);
});
it('should transfer -Infinity', async () => {
const { page } = getTestState();
const result = await page.evaluate((a) => a, -Infinity);
expect(Object.is(result, -Infinity)).toBe(true);
});
it('should transfer arrays', async () => {
const { page } = getTestState();
const result = await page.evaluate((a) => a, [1, 2, 3]);
expect(result).toEqual([1, 2, 3]);
});
it('should transfer arrays as arrays, not objects', async () => {
const { page } = getTestState();
const result = await page.evaluate((a) => Array.isArray(a), [1, 2, 3]);
expect(result).toBe(true);
});
it('should modify global environment', async () => {
const { page } = getTestState();
await page.evaluate(() => (globalThis.globalVar = 123));
expect(await page.evaluate('globalVar')).toBe(123);
});
it('should evaluate in the page context', async () => {
const { page, server } = getTestState();
await page.goto(server.PREFIX + '/global-var.html');
expect(await page.evaluate('globalVar')).toBe(123);
});
itFailsFirefox(
'should return undefined for objects with symbols',
async () => {
const { page } = getTestState();
expect(await page.evaluate(() => [Symbol('foo4')])).toBe(undefined);
}
);
it('should work with function shorthands', async () => {
const { page } = getTestState();
const a = {
sum(a, b) {
return a + b;
},
async mult(a, b) {
return a * b;
},
};
expect(await page.evaluate(a.sum, 1, 2)).toBe(3);
expect(await page.evaluate(a.mult, 2, 4)).toBe(8);
});
it('should work with unicode chars', async () => {
const { page } = getTestState();
const result = await page.evaluate((a) => a['中文字符'], {
中文字符: 42,
});
expect(result).toBe(42);
});
itFailsFirefox('should throw when evaluation triggers reload', async () => {
const { page } = getTestState();
let error = null;
await page
.evaluate(() => {
location.reload();
return new Promise(() => {});
})
.catch((error_) => (error = error_));
expect(error.message).toContain('Protocol error');
});
it('should await promise', async () => {
const { page } = getTestState();
const result = await page.evaluate(() => Promise.resolve(8 * 7));
expect(result).toBe(56);
});
it('should work right after framenavigated', async () => {
const { page, server } = getTestState();
let frameEvaluation = null;
page.on('framenavigated', async (frame) => {
frameEvaluation = frame.evaluate(() => 6 * 7);
});
await page.goto(server.EMPTY_PAGE);
expect(await frameEvaluation).toBe(42);
});
itFailsFirefox('should work from-inside an exposed function', async () => {
const { page } = getTestState();
// Setup inpage callback, which calls Page.evaluate
await page.exposeFunction('callController', async function (a, b) {
return await page.evaluate<(a: number, b: number) => number>(
(a, b) => a * b,
a,
b
);
});
const result = await page.evaluate(async function () {
return await globalThis.callController(9, 3);
});
expect(result).toBe(27);
});
it('should reject promise with exception', async () => {
const { page } = getTestState();
let error = null;
await page
// @ts-expect-error we know the object doesn't exist
.evaluate(() => notExistingObject.property)
.catch((error_) => (error = error_));
expect(error).toBeTruthy();
expect(error.message).toContain('notExistingObject');
});
it('should support thrown strings as error messages', async () => {
const { page } = getTestState();
let error = null;
await page
.evaluate(() => {
throw 'qwerty';
})
.catch((error_) => (error = error_));
expect(error).toBeTruthy();
expect(error.message).toContain('qwerty');
});
it('should support thrown numbers as error messages', async () => {
const { page } = getTestState();
let error = null;
await page
.evaluate(() => {
throw 100500;
})
.catch((error_) => (error = error_));
expect(error).toBeTruthy();
expect(error.message).toContain('100500');
});
it('should return complex objects', async () => {
const { page } = getTestState();
const object = { foo: 'bar!' };
const result = await page.evaluate((a) => a, object);
expect(result).not.toBe(object);
expect(result).toEqual(object);
});
(bigint ? it : xit)('should return BigInt', async () => {
const { page } = getTestState();
const result = await page.evaluate(() => BigInt(42));
expect(result).toBe(BigInt(42));
});
it('should return NaN', async () => {
const { page } = getTestState();
const result = await page.evaluate(() => NaN);
expect(Object.is(result, NaN)).toBe(true);
});
it('should return -0', async () => {
const { page } = getTestState();
const result = await page.evaluate(() => -0);
expect(Object.is(result, -0)).toBe(true);
});
it('should return Infinity', async () => {
const { page } = getTestState();
const result = await page.evaluate(() => Infinity);
expect(Object.is(result, Infinity)).toBe(true);
});
it('should return -Infinity', async () => {
const { page } = getTestState();
const result = await page.evaluate(() => -Infinity);
expect(Object.is(result, -Infinity)).toBe(true);
});
it('should accept "undefined" as one of multiple parameters', async () => {
const { page } = getTestState();
const result = await page.evaluate(
(a, b) => Object.is(a, undefined) && Object.is(b, 'foo'),
undefined,
'foo'
);
expect(result).toBe(true);
});
it('should properly serialize null fields', async () => {
const { page } = getTestState();
expect(await page.evaluate(() => ({ a: undefined }))).toEqual({});
});
itFailsFirefox(
'should return undefined for non-serializable objects',
async () => {
const { page } = getTestState();
expect(await page.evaluate(() => window)).toBe(undefined);
}
);
itFailsFirefox('should fail for circular object', async () => {
const { page } = getTestState();
const result = await page.evaluate(() => {
const a: { [x: string]: any } = {};
const b = { a };
a.b = b;
return a;
});
expect(result).toBe(undefined);
});
itFailsFirefox('should be able to throw a tricky error', async () => {
const { page } = getTestState();
const windowHandle = await page.evaluateHandle(() => window);
const errorText = await windowHandle
.jsonValue<string>()
.catch((error_) => error_.message);
const error = await page
.evaluate<(errorText: string) => Error>((errorText) => {
throw new Error(errorText);
}, errorText)
.catch((error_) => error_);
expect(error.message).toContain(errorText);
});
it('should accept a string', async () => {
const { page } = getTestState();
const result = await page.evaluate('1 + 2');
expect(result).toBe(3);
});
it('should accept a string with semi colons', async () => {
const { page } = getTestState();
const result = await page.evaluate('1 + 5;');
expect(result).toBe(6);
});
it('should accept a string with comments', async () => {
const { page } = getTestState();
const result = await page.evaluate('2 + 5;\n// do some math!');
expect(result).toBe(7);
});
it('should accept element handle as an argument', async () => {
const { page } = getTestState();
await page.setContent('<section>42</section>');
const element = await page.$('section');
const text = await page.evaluate<(e: HTMLElement) => string>(
(e) => e.textContent,
element
);
expect(text).toBe('42');
});
it('should throw if underlying element was disposed', async () => {
const { page } = getTestState();
await page.setContent('<section>39</section>');
const element = await page.$('section');
expect(element).toBeTruthy();
await element.dispose();
let error = null;
await page
.evaluate((e: HTMLElement) => e.textContent, element)
.catch((error_) => (error = error_));
expect(error.message).toContain('JSHandle is disposed');
});
itFailsFirefox(
'should throw if elementHandles are from other frames',
async () => {
const { page, server } = getTestState();
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const bodyHandle = await page.frames()[1].$('body');
let error = null;
await page
.evaluate((body: HTMLElement) => body.innerHTML, bodyHandle)
.catch((error_) => (error = error_));
expect(error).toBeTruthy();
expect(error.message).toContain(
'JSHandles can be evaluated only in the context they were created'
);
}
);
itFailsFirefox('should simulate a user gesture', async () => {
const { page } = getTestState();
const result = await page.evaluate(() => {
document.body.appendChild(document.createTextNode('test'));
document.execCommand('selectAll');
return document.execCommand('copy');
});
expect(result).toBe(true);
});
itFailsFirefox('should throw a nice error after a navigation', async () => {
const { page } = getTestState();
const executionContext = await page.mainFrame().executionContext();
await Promise.all([
page.waitForNavigation(),
executionContext.evaluate(() => window.location.reload()),
]);
const error = await executionContext
.evaluate(() => null)
.catch((error_) => error_);
expect((error as Error).message).toContain('navigation');
});
itFailsFirefox(
'should not throw an error when evaluation does a navigation',
async () => {
const { page, server } = getTestState();
await page.goto(server.PREFIX + '/one-style.html');
const result = await page.evaluate(() => {
(window as any).location = '/empty.html';
return [42];
});
expect(result).toEqual([42]);
}
);
it('should transfer 100Mb of data from page to node.js', async function () {
const { page } = getTestState();
const a = await page.evaluate<() => string>(() =>
Array(100 * 1024 * 1024 + 1).join('a')
);
expect(a.length).toBe(100 * 1024 * 1024);
});
it('should throw error with detailed information on exception inside promise ', async () => {
const { page } = getTestState();
let error = null;
await page
.evaluate(
() =>
new Promise(() => {
throw new Error('Error in promise');
})
)
.catch((error_) => (error = error_));
expect(error.message).toContain('Error in promise');
});
});
describeFailsFirefox('Page.evaluateOnNewDocument', function () {
it('should evaluate before anything else on the page', async () => {
const { page, server } = getTestState();
await page.evaluateOnNewDocument(function () {
globalThis.injected = 123;
});
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => globalThis.result)).toBe(123);
});
it('should work with CSP', async () => {
const { page, server } = getTestState();
server.setCSP('/empty.html', 'script-src ' + server.PREFIX);
await page.evaluateOnNewDocument(function () {
globalThis.injected = 123;
});
await page.goto(server.PREFIX + '/empty.html');
expect(await page.evaluate(() => globalThis.injected)).toBe(123);
// Make sure CSP works.
await page
.addScriptTag({ content: 'window.e = 10;' })
.catch((error) => void error);
expect(await page.evaluate(() => (window as any).e)).toBe(undefined);
});
});
describe('Frame.evaluate', function () {
itFailsFirefox('should have different execution contexts', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(page.frames().length).toBe(2);
await page.frames()[0].evaluate(() => (globalThis.FOO = 'foo'));
await page.frames()[1].evaluate(() => (globalThis.FOO = 'bar'));
expect(await page.frames()[0].evaluate(() => globalThis.FOO)).toBe('foo');
expect(await page.frames()[1].evaluate(() => globalThis.FOO)).toBe('bar');
});
itFailsFirefox('should have correct execution contexts', async () => {
const { page, server } = getTestState();
await page.goto(server.PREFIX + '/frames/one-frame.html');
expect(page.frames().length).toBe(2);
expect(
await page.frames()[0].evaluate(() => document.body.textContent.trim())
).toBe('');
expect(
await page.frames()[1].evaluate(() => document.body.textContent.trim())
).toBe(`Hi, I'm frame`);
});
it('should execute after cross-site navigation', async () => {
const { page, server } = getTestState();
await page.goto(server.EMPTY_PAGE);
const mainFrame = page.mainFrame();
expect(await mainFrame.evaluate(() => window.location.href)).toContain(
'localhost'
);
await page.goto(server.CROSS_PROCESS_PREFIX + '/empty.html');
expect(await mainFrame.evaluate(() => window.location.href)).toContain(
'127'
);
});
});
}); | the_stack |
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as Protocol from '../../generated/protocol.js';
import * as CookieTable from '../../ui/legacy/components/cookie_table/cookie_table.js';
import * as UI from '../../ui/legacy/legacy.js';
import requestCookiesViewStyles from './requestCookiesView.css.js';
const UIStrings = {
/**
*@description Text in Request Cookies View of the Network panel
*/
thisRequestHasNoCookies: 'This request has no cookies.',
/**
* @description Title for a table which shows all of the cookies associated with a selected network
* request, in the Network panel. Noun phrase.
*/
requestCookies: 'Request Cookies',
/**
*@description Tooltip to explain what request cookies are
*/
cookiesThatWereSentToTheServerIn: 'Cookies that were sent to the server in the \'cookie\' header of the request',
/**
*@description Label for showing request cookies that were not actually sent
*/
showFilteredOutRequestCookies: 'show filtered out request cookies',
/**
*@description Text in Request Headers View of the Network Panel
*/
noRequestCookiesWereSent: 'No request cookies were sent.',
/**
*@description Text in Request Cookies View of the Network panel
*/
responseCookies: 'Response Cookies',
/**
*@description Tooltip to explain what response cookies are
*/
cookiesThatWereReceivedFromThe:
'Cookies that were received from the server in the \'`set-cookie`\' header of the response',
/**
*@description Label for response cookies with invalid syntax
*/
malformedResponseCookies: 'Malformed Response Cookies',
/**
* @description Tooltip to explain what malformed response cookies are. Malformed cookies are
* cookies that did not match the expected format and could not be interpreted, and are invalid.
*/
cookiesThatWereReceivedFromTheServer:
'Cookies that were received from the server in the \'`set-cookie`\' header of the response but were malformed',
};
const str_ = i18n.i18n.registerUIStrings('panels/network/RequestCookiesView.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
export class RequestCookiesView extends UI.Widget.Widget {
private request: SDK.NetworkRequest.NetworkRequest;
private readonly showFilteredOutCookiesSetting: Common.Settings.Setting<boolean>;
private readonly emptyWidget: UI.EmptyWidget.EmptyWidget;
private readonly requestCookiesTitle: HTMLElement;
private readonly requestCookiesEmpty: HTMLElement;
private readonly requestCookiesTable: CookieTable.CookiesTable.CookiesTable;
private readonly responseCookiesTitle: HTMLElement;
private readonly responseCookiesTable: CookieTable.CookiesTable.CookiesTable;
private readonly malformedResponseCookiesTitle: HTMLElement;
private readonly malformedResponseCookiesList: HTMLElement;
constructor(request: SDK.NetworkRequest.NetworkRequest) {
super();
this.element.classList.add('request-cookies-view');
this.request = request;
this.showFilteredOutCookiesSetting = Common.Settings.Settings.instance().createSetting(
'show-filtered-out-request-cookies', /* defaultValue */ false);
this.emptyWidget = new UI.EmptyWidget.EmptyWidget(i18nString(UIStrings.thisRequestHasNoCookies));
this.emptyWidget.show(this.element);
this.requestCookiesTitle = this.element.createChild('div');
const titleText = this.requestCookiesTitle.createChild('span', 'request-cookies-title');
titleText.textContent = i18nString(UIStrings.requestCookies);
UI.Tooltip.Tooltip.install(titleText, i18nString(UIStrings.cookiesThatWereSentToTheServerIn));
const requestCookiesCheckbox =
(UI.SettingsUI.createSettingCheckbox(
i18nString(UIStrings.showFilteredOutRequestCookies), this.showFilteredOutCookiesSetting, true) as
UI.UIUtils.CheckboxLabel);
requestCookiesCheckbox.checkboxElement.addEventListener('change', () => {
this.refreshRequestCookiesView();
});
this.requestCookiesTitle.appendChild(requestCookiesCheckbox);
this.requestCookiesEmpty = this.element.createChild('div', 'cookies-panel-item');
this.requestCookiesEmpty.textContent = i18nString(UIStrings.noRequestCookiesWereSent);
this.requestCookiesTable = new CookieTable.CookiesTable.CookiesTable(/* renderInline */ true);
this.requestCookiesTable.contentElement.classList.add('cookie-table', 'cookies-panel-item');
this.requestCookiesTable.show(this.element);
this.responseCookiesTitle = this.element.createChild('div', 'request-cookies-title');
this.responseCookiesTitle.textContent = i18nString(UIStrings.responseCookies);
this.responseCookiesTitle.title = i18nString(UIStrings.cookiesThatWereReceivedFromThe);
this.responseCookiesTable = new CookieTable.CookiesTable.CookiesTable(/* renderInline */ true);
this.responseCookiesTable.contentElement.classList.add('cookie-table', 'cookies-panel-item');
this.responseCookiesTable.show(this.element);
this.malformedResponseCookiesTitle = this.element.createChild('div', 'request-cookies-title');
this.malformedResponseCookiesTitle.textContent = i18nString(UIStrings.malformedResponseCookies);
UI.Tooltip.Tooltip.install(
this.malformedResponseCookiesTitle, i18nString(UIStrings.cookiesThatWereReceivedFromTheServer));
this.malformedResponseCookiesList = this.element.createChild('div');
}
private getRequestCookies(): {
requestCookies: Array<SDK.Cookie.Cookie>,
requestCookieToBlockedReasons: Map<SDK.Cookie.Cookie, SDK.CookieModel.BlockedReason[]>,
} {
const requestCookieToBlockedReasons = new Map<SDK.Cookie.Cookie, SDK.CookieModel.BlockedReason[]>();
const requestCookies = this.request.includedRequestCookies().slice();
if (this.showFilteredOutCookiesSetting.get()) {
for (const blockedCookie of this.request.blockedRequestCookies()) {
requestCookieToBlockedReasons.set(blockedCookie.cookie, blockedCookie.blockedReasons.map(blockedReason => {
return {
attribute: SDK.NetworkRequest.cookieBlockedReasonToAttribute(blockedReason),
uiString: SDK.NetworkRequest.cookieBlockedReasonToUiString(blockedReason),
};
}));
requestCookies.push(blockedCookie.cookie);
}
}
return {requestCookies, requestCookieToBlockedReasons};
}
private getResponseCookies(): {
responseCookies: Array<SDK.Cookie.Cookie>,
responseCookieToBlockedReasons: Map<SDK.Cookie.Cookie, Array<SDK.CookieModel.BlockedReason>>,
malformedResponseCookies: Array<SDK.NetworkRequest.BlockedSetCookieWithReason>,
} {
let responseCookies: SDK.Cookie.Cookie[] = [];
const responseCookieToBlockedReasons = new Map<SDK.Cookie.Cookie, SDK.CookieModel.BlockedReason[]>();
const malformedResponseCookies: SDK.NetworkRequest.BlockedSetCookieWithReason[] = [];
if (this.request.responseCookies.length) {
const blockedCookieLines: (string|null)[] =
this.request.blockedResponseCookies().map(blockedCookie => blockedCookie.cookieLine);
responseCookies = this.request.responseCookies.filter(cookie => {
// remove the regular cookies that would overlap with blocked cookies
const index = blockedCookieLines.indexOf(cookie.getCookieLine());
if (index !== -1) {
blockedCookieLines[index] = null;
return false;
}
return true;
});
for (const blockedCookie of this.request.blockedResponseCookies()) {
const parsedCookies = SDK.CookieParser.CookieParser.parseSetCookie(blockedCookie.cookieLine);
if ((parsedCookies && !parsedCookies.length) ||
blockedCookie.blockedReasons.includes(Protocol.Network.SetCookieBlockedReason.SyntaxError) ||
blockedCookie.blockedReasons.includes(
Protocol.Network.SetCookieBlockedReason.NameValuePairExceedsMaxSize)) {
malformedResponseCookies.push(blockedCookie);
continue;
}
let cookie: SDK.Cookie.Cookie|(SDK.Cookie.Cookie | null) = blockedCookie.cookie;
if (!cookie && parsedCookies) {
cookie = parsedCookies[0];
}
if (cookie) {
responseCookieToBlockedReasons.set(cookie, blockedCookie.blockedReasons.map(blockedReason => {
return {
attribute: SDK.NetworkRequest.setCookieBlockedReasonToAttribute(blockedReason),
uiString: SDK.NetworkRequest.setCookieBlockedReasonToUiString(blockedReason),
};
}));
responseCookies.push(cookie);
}
}
}
return {responseCookies, responseCookieToBlockedReasons, malformedResponseCookies};
}
private refreshRequestCookiesView(): void {
if (!this.isShowing()) {
return;
}
const gotCookies = this.request.hasRequestCookies() || this.request.responseCookies.length;
if (gotCookies) {
this.emptyWidget.hideWidget();
} else {
this.emptyWidget.showWidget();
}
const {requestCookies, requestCookieToBlockedReasons} = this.getRequestCookies();
const {responseCookies, responseCookieToBlockedReasons, malformedResponseCookies} = this.getResponseCookies();
if (requestCookies.length) {
this.requestCookiesTitle.classList.remove('hidden');
this.requestCookiesEmpty.classList.add('hidden');
this.requestCookiesTable.showWidget();
this.requestCookiesTable.setCookies(requestCookies, requestCookieToBlockedReasons);
} else if (this.request.blockedRequestCookies().length) {
this.requestCookiesTitle.classList.remove('hidden');
this.requestCookiesEmpty.classList.remove('hidden');
this.requestCookiesTable.hideWidget();
} else {
this.requestCookiesTitle.classList.add('hidden');
this.requestCookiesEmpty.classList.add('hidden');
this.requestCookiesTable.hideWidget();
}
if (responseCookies.length) {
this.responseCookiesTitle.classList.remove('hidden');
this.responseCookiesTable.showWidget();
this.responseCookiesTable.setCookies(responseCookies, responseCookieToBlockedReasons);
} else {
this.responseCookiesTitle.classList.add('hidden');
this.responseCookiesTable.hideWidget();
}
if (malformedResponseCookies.length) {
this.malformedResponseCookiesTitle.classList.remove('hidden');
this.malformedResponseCookiesList.classList.remove('hidden');
this.malformedResponseCookiesList.removeChildren();
for (const malformedCookie of malformedResponseCookies) {
const listItem = this.malformedResponseCookiesList.createChild('span', 'cookie-line source-code');
const icon = UI.Icon.Icon.create('smallicon-error', 'cookie-warning-icon');
listItem.appendChild(icon);
UI.UIUtils.createTextChild(listItem, malformedCookie.cookieLine);
if (malformedCookie.blockedReasons.includes(
Protocol.Network.SetCookieBlockedReason.NameValuePairExceedsMaxSize)) {
listItem.title = SDK.NetworkRequest.setCookieBlockedReasonToUiString(
Protocol.Network.SetCookieBlockedReason.NameValuePairExceedsMaxSize);
} else {
listItem.title =
SDK.NetworkRequest.setCookieBlockedReasonToUiString(Protocol.Network.SetCookieBlockedReason.SyntaxError);
}
}
} else {
this.malformedResponseCookiesTitle.classList.add('hidden');
this.malformedResponseCookiesList.classList.add('hidden');
}
}
wasShown(): void {
super.wasShown();
this.registerCSSFiles([requestCookiesViewStyles]);
this.request.addEventListener(
SDK.NetworkRequest.Events.RequestHeadersChanged, this.refreshRequestCookiesView, this);
this.request.addEventListener(
SDK.NetworkRequest.Events.ResponseHeadersChanged, this.refreshRequestCookiesView, this);
this.refreshRequestCookiesView();
}
willHide(): void {
this.request.removeEventListener(
SDK.NetworkRequest.Events.RequestHeadersChanged, this.refreshRequestCookiesView, this);
this.request.removeEventListener(
SDK.NetworkRequest.Events.ResponseHeadersChanged, this.refreshRequestCookiesView, this);
}
} | the_stack |
import { IJSLink, IJSLinkCfg } from "../../@types/helper";
import { ContextInfo } from "../lib";
import { SPTypes } from "../sptypes";
/**
* JSLink Helper Methods
*/
export const JSLink: IJSLink = {
// Hide event flag
_hideEventFl: false,
/**
* Field to Method Mapper
* 1 - Display Form
* 2 - Edit Form
* 3 - New Form
* 4 - View
*/
_fieldToMethodMapper: {
'Attachments': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPFieldAttachments_Default"],
2: ContextInfo.window["SPFieldAttachments_Default"],
3: ContextInfo.window["SPFieldAttachments_Default"]
},
'Boolean': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPField_FormDisplay_DefaultNoEncode"],
2: ContextInfo.window["SPFieldBoolean_Edit"],
3: ContextInfo.window["SPFieldBoolean_Edit"]
},
'Currency': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPField_FormDisplay_Default"],
2: ContextInfo.window["SPFieldNumber_Edit"],
3: ContextInfo.window["SPFieldNumber_Edit"]
},
'Calculated': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPField_FormDisplay_Default"],
2: ContextInfo.window["SPField_FormDisplay_Empty"],
3: ContextInfo.window["SPField_FormDisplay_Empty"]
},
'Choice': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPField_FormDisplay_Default"],
2: ContextInfo.window["SPFieldChoice_Edit"],
3: ContextInfo.window["SPFieldChoice_Edit"]
},
'Computed': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPField_FormDisplay_Default"],
2: ContextInfo.window["SPField_FormDisplay_Default"],
3: ContextInfo.window["SPField_FormDisplay_Default"]
},
'DateTime': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPFieldDateTime_Display"],
2: ContextInfo.window["SPFieldDateTime_Edit"],
3: ContextInfo.window["SPFieldDateTime_Edit"]
},
'File': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPFieldFile_Display"],
2: ContextInfo.window["SPFieldFile_Edit"],
3: ContextInfo.window["SPFieldFile_Edit"]
},
'Integer': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPField_FormDisplay_Default"],
2: ContextInfo.window["SPFieldNumber_Edit"],
3: ContextInfo.window["SPFieldNumber_Edit"]
},
'Lookup': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPFieldLookup_Display"],
2: ContextInfo.window["SPFieldLookup_Edit"],
3: ContextInfo.window["SPFieldLookup_Edit"]
},
'LookupMulti': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPFieldLookup_Display"],
2: ContextInfo.window["SPFieldLookup_Edit"],
3: ContextInfo.window["SPFieldLookup_Edit"]
},
'MultiChoice': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPField_FormDisplay_Default"],
2: ContextInfo.window["SPFieldMultiChoice_Edit"],
3: ContextInfo.window["SPFieldMultiChoice_Edit"]
},
'Note': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPFieldNote_Display"],
2: ContextInfo.window["SPFieldNote_Edit"],
3: ContextInfo.window["SPFieldNote_Edit"]
},
'Number': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPField_FormDisplay_Default"],
2: ContextInfo.window["SPFieldNumber_Edit"],
3: ContextInfo.window["SPFieldNumber_Edit"]
},
'Text': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPField_FormDisplay_Default"],
2: ContextInfo.window["SPFieldText_Edit"],
3: ContextInfo.window["SPFieldText_Edit"]
},
'URL': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPFieldUrl_Display"],
2: ContextInfo.window["SPFieldUrl_Edit"],
3: ContextInfo.window["SPFieldUrl_Edit"]
},
'User': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPFieldUser_Display"],
2: ContextInfo.window["SPClientPeoplePickerCSRTemplate"],
3: ContextInfo.window["SPClientPeoplePickerCSRTemplate"]
},
'UserMulti': {
4: ContextInfo.window["RenderFieldValueDefault"],
1: ContextInfo.window["SPFieldUserMulti_Display"],
2: ContextInfo.window["SPClientPeoplePickerCSRTemplate"],
3: ContextInfo.window["SPClientPeoplePickerCSRTemplate"]
}
},
/**
* Methods
*/
/**
* Disables edit for the specified field.
* @param ctx - The client context.
* @param field - The field to disable edit.
* @param requireValueFl - Flag to only disable the field, if a value exists.
*/
disableEdit: (ctx: any, field: any, requireValueFl?: boolean): string => {
let fieldValue = ctx.CurrentFieldValue;
// Ensure a value exists
if (fieldValue) {
// Update the context, based on the field type
switch (ctx.CurrentFieldSchema.Type) {
case "MultiChoice":
let regExp = new RegExp(SPTypes.ClientTemplatesUtility.UserLookupDelimitString, "g");
// Update the field value
fieldValue = ctx.CurrentFieldValue
// Replace the delimiter
.replace(regExp, "; ")
// Trim the delimiter from the beginning
.replace(/^; /g, "")
// Trim the delimiter from the end
.replace(/; $/g, "");
break;
case "Note":
// Replace the return characters
fieldValue = "<div>" + ctx.CurrentFieldValue.replace(/\n/g, "<br />") + "</div>";
break;
case "User":
case "UserMulti":
for (let i = 0; i < ctx.CurrentFieldValue.length; i++) {
let userValue = ctx.CurrentFieldValue[i];
// Add the user value
fieldValue +=
// User Lookup ID
userValue.EntityData.SPUserID +
// Delimiter
SPTypes.ClientTemplatesUtility.UserLookupDelimitString +
// User Lookup Value
userValue.DisplayText +
// Optional Delimiter
((i == ctx.CurrentFieldValue.length - 1 ? "" : SPTypes.ClientTemplatesUtility.UserLookupDelimitString));
}
break;
};
// Update the current field value
ctx.CurrentFieldValue = fieldValue;
}
// Determine the control mode
let controlMode = SPTypes.ControlMode.Display;
if (requireValueFl && (fieldValue == null || fieldValue == "")) {
// Inherit the control mode
controlMode = ctx.ControlMode;
}
// Return the display value of the field
return JSLink.renderField(ctx, field, controlMode);
},
/**
* Disable quick edit for the specified field.
* @param ctx - The client context.
* @param field - The field to disable edit.
*/
disableQuickEdit: (ctx: any, field: any) => {
// Ensure we are in grid edit mode
if (ctx.inGridMode) {
// Disable editing for this field
field.AllowGridEditing = false;
return "";
}
// Return the default field value html
return JSLink.renderField(ctx, field);
},
/**
* Returns the list view.
* @param ctx - The client context.
*/
getListView: (ctx: any) => {
// Get the webpart
let wp = JSLink.getWebPart(ctx);
if (wp) {
// Find the list form table
wp = wp.querySelector(".ms-formtable");
}
// Return the list view
return wp;
},
/**
* Returns the list view items.
* @param ctx - The client context.
*/
getListViewItems: (ctx: any) => {
// Return the list view items
return ctx.ListData ? ctx.ListData.Row : [];
},
/**
* Returns the selected list view items
*/
getListViewSelectedItems: () => {
// Return the selected items
return ContextInfo.window["SP"].ListOperation.Selection.getSelectedItems();
},
/**
* Returns the webpart containing the JSLink field/form/view.
* @param ctx - The client context.
*/
getWebPart: (ctx) => {
// Return the webpart
return ContextInfo.document.querySelector("#WebPart" + (ctx.FormUniqueId || ctx.wpq));
},
/**
* Hides the specified field.
* @param ctx - The client context.
* @param field - The field to hide.
*/
hideField: (ctx: any, field: any) => {
// Ensure the hide event has been created
if (!JSLink._hideEventFl) {
// Set the flag
JSLink._hideEventFl = true;
// Create the event
ContextInfo.window.addEventListener("load", () => {
// Query for the elements to hide
let fieldElements: any = ContextInfo.document.querySelectorAll(".hide-field");
for (let fieldElement of fieldElements) {
// Get the parent row
let parentRow = fieldElement.parentNode && fieldElement.parentNode.parentNode ? fieldElement.parentNode.parentNode : null;
if (parentRow) {
// Ensure the parent row exists
if (fieldElement.parentNode.getAttribute("data-field-name") != parentRow.getAttribute("data-field-name")) {
// Find the parent row
while (parentRow && parentRow.nodeName.toLowerCase() != "tr") {
// Update the parent node
parentRow = parentRow.parentNode;
}
}
// Hide the parent row
if (parentRow) {
parentRow.style.display = "none";
}
}
}
});
}
},
/**
* Registers the JSLink configuration
* @param cfg - The JSLink configuration.
*/
register: (cfg: IJSLinkCfg) => {
// Ensure a configuration exists
if (cfg) {
// Get the template manager
let templateManager = ContextInfo.window.SPClientTemplates;
templateManager = templateManager ? templateManager.TemplateManager : null;
// Ensure it exists
if (templateManager) {
// Apply the customization
templateManager.RegisterTemplateOverrides(cfg);
}
}
},
/**
* Removes the field and html from the page.
* @param ctx - The client context.
* @param field - The field to remove.
*/
removeField: (ctx: any, field: any) => {
// Hide the field
JSLink.hideField(ctx, field);
// Return an empty element
return "<div class='hide-field'></div>";
},
/**
* Method to render the default html for a field.
* @param ctx - The client context.
* @param field - The form field.
* @param formType - The form type. (Display, Edit, New or View)
*/
renderField: (ctx, field, formType?: number) => {
// Determine the field type
var fieldType = field ? field.Type : (ctx.CurrentFieldSchema ? ctx.CurrentFieldSchema.Type : null);
// Ensure the form type is set
formType = formType ? formType : ctx.ControlMode;
// Ensure a field to method mapper exists
if (JSLink._fieldToMethodMapper[fieldType] && JSLink._fieldToMethodMapper[fieldType][formType]) {
// Return the default html for this field
var defaultHtml = JSLink._fieldToMethodMapper[fieldType][formType](ctx);
if (defaultHtml) { return defaultHtml; }
}
// Set the field renderer based on the field type
var field = ctx.CurrentFieldSchema;
var fieldRenderer = null;
switch (field.Type) {
case "AllDayEvent": fieldRenderer = new ContextInfo.window["AllDayEventFieldRenderer"](field.Name); break;
case "Attachments": fieldRenderer = new ContextInfo.window["AttachmentFieldRenderer"](field.Name); break;
case "BusinessData": fieldRenderer = new ContextInfo.window["BusinessDataFieldRenderer"](field.Name); break;
case "Computed": fieldRenderer = new ContextInfo.window["ComputedFieldRenderer"](field.Name); break;
case "CrossProjectLink": fieldRenderer = new ContextInfo.window["ProjectLinkFieldRenderer"](field.Name); break;
case "Currency": fieldRenderer = new ContextInfo.window["NumberFieldRenderer"](field.Name); break;
case "DateTime": fieldRenderer = new ContextInfo.window["DateTimeFieldRenderer"](field.Name); break;
case "Lookup": fieldRenderer = new ContextInfo.window["LookupFieldRenderer"](field.Name); break;
case "LookupMulti": fieldRenderer = new ContextInfo.window["LookupFieldRenderer"](field.Name); break;
case "Note": fieldRenderer = new ContextInfo.window["NoteFieldRenderer"](field.Name); break;
case "Number": fieldRenderer = new ContextInfo.window["NumberFieldRenderer"](field.Name); break;
case "Recurrence": fieldRenderer = new ContextInfo.window["RecurrenceFieldRenderer"](field.Name); break;
case "Text": fieldRenderer = new ContextInfo.window["TextFieldRenderer"](field.Name); break;
case "URL": fieldRenderer = new ContextInfo.window["UrlFieldRenderer"](field.Name); break;
case "User": fieldRenderer = new ContextInfo.window["UserFieldRenderer"](field.Name); break;
case "UserMulti": fieldRenderer = new ContextInfo.window["UserFieldRenderer"](field.Name); break;
case "WorkflowStatus": fieldRenderer = new ContextInfo.window["RawFieldRenderer"](field.Name); break;
};
// Get the current item
var currentItem = ctx.CurrentItem || ctx.ListData.Items[0];
// Return the item's field value html
return fieldRenderer ? fieldRenderer.RenderField(ctx, field, currentItem, ctx.ListSchema) : currentItem[field.Name];
}
} | the_stack |
import { CommonModule } from '@angular/common';
import {
Component,
NgModule,
} from '@angular/core';
import {
FormControl,
FormsModule,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import {
TsOption,
TsOptionModule,
} from '@terminus/ui/option';
import {
TsSelectionListChange,
TsSelectionListFormatter,
TsSelectionListModule,
} from '@terminus/ui/selection-list';
interface State extends TsOption {
name: string;
population: string;
disabled?: boolean;
}
export const STATES: State[] = [
{
name: 'Arkansas',
population: '2.978M',
},
{
name: 'Alabama',
population: '3.29M',
disabled: true,
},
{
name: 'Alaska',
population: '1.341M',
},
{
name: 'California',
population: '39.14M',
},
{
name: 'Florida',
population: '20.27M',
},
{
name: 'Texas',
population: '27.47M',
},
{
name: 'Arizona',
population: '24.112M',
},
{
name: 'Arkansas 2',
population: '2.978M',
},
{
name: 'Alabama 2',
population: '3.29M',
},
{
name: 'Alaska 2',
population: '1.341M',
},
{
name: 'California 2',
population: '39.14M',
},
{
name: 'Florida 2',
population: '20.27M',
},
{
name: 'Texas 2',
population: '27.47M',
},
{
name: 'Arizona 2',
population: '24.112M',
},
{
name: 'Arkansas 3',
population: '2.978M',
},
{
name: 'Alabama 3',
population: '3.29M',
},
{
name: 'Alaska 3',
population: '1.341M',
},
{
name: 'California 3',
population: '39.14M',
},
{
name: 'Florida 3',
population: '20.27M',
},
{
name: 'Texas 3',
population: '27.47M',
},
{
name: 'Arizona 3',
population: '24.112M',
},
];
interface GroupedStates {
name: string;
children: State[];
disabled?: boolean;
}
const STATES_GROUPED: GroupedStates[] = [
{
name: 'Group A',
children: [
{
name: 'Arkansas',
population: '2.978M',
},
{
name: 'Alabama',
population: '3.29M',
disabled: true,
},
{
name: 'Alaska',
population: '1.341M',
},
],
},
{
name: 'Group B',
disabled: true,
children: [
{
name: 'California',
population: '39.14M',
},
{
name: 'Florida',
population: '20.27M',
},
{
name: 'Texas',
population: '27.47M',
},
],
},
];
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="allowMultiple"
[reopenAfterSelection]="keepOpen"
[showProgress]="showProgress"
[isDisabled]="disabled"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
{{ option.name }}
</ts-option>
</ts-selection-list>
`,
})
export class Basic {
public myCtrl = new FormControl();
public states: State[] = STATES.slice();
public showProgress = false;
public allowMultiple = true;
public keepOpen = true;
public disabled: boolean | undefined;
public change = v => {};
public changeOptionsLength() {
this.states = STATES.slice(0, 5);
}
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="allowMultiple"
[reopenAfterSelection]="keepOpen"
[showProgress]="showProgress"
[isDisabled]="disabled"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
{{ option.name }}
</ts-option>
</ts-selection-list>
<ts-selection-list
[formControl]="secondCtrl"
[allowMultiple]="allowMultiple"
[reopenAfterSelection]="keepOpen"
[showProgress]="showProgress"
[isDisabled]="disabled"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
{{ option.name }}
</ts-option>
</ts-selection-list>
`,
})
export class Multiple {
public myCtrl = new FormControl();
public secondCtrl = new FormControl();
public states: State[] = STATES.slice();
public showProgress = false;
public allowMultiple = true;
public keepOpen = true;
public disabled: boolean | undefined;
public change = v => { };
public changeOptionsLength() {
this.states = STATES.slice(0, 5);
}
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="true"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
>
{{ option.name }}
</ts-option>
</ts-selection-list>
`,
})
export class Required {
public myCtrl = new FormControl(null, [Validators.required]);
public states: State[] = STATES.slice();
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="allowMultiple"
[allowDuplicateSelections]="allowDuplicates"
[reopenAfterSelection]="keepOpen"
[displayFormatter]="formatter"
(duplicateSelection)="duplicate($event)"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
<span tsOptionDisplay>
{{ option.name }}
</span>
</ts-option>
</ts-selection-list>
`,
})
export class Seeded {
public states: State[] = STATES.slice();
public myCtrl = new FormControl([STATES[4]]);
public allowMultiple = true;
public allowDuplicates = false;
public keepOpen = false;
public formatter: TsSelectionListFormatter | undefined;
// Must be overwritten with a spy in the test
public duplicate = v => { };
public setNewStates() {
this.states = STATES.slice(3, 7);
}
public setFormatter() {
this.formatter = v => (v as State).population;
}
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="allowMultiple"
[allowDuplicateSelections]="allowDuplicates"
[reopenAfterSelection]="keepOpen"
[displayFormatter]="formatter"
(duplicateSelection)="duplicate($event)"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
<span tsOptionDisplay>
{{ option.name }}
</span>
</ts-option>
</ts-selection-list>
`,
})
export class ManualSeeded {
public states: State[] = STATES.slice();
public myCtrl = new FormControl('');
public allowMultiple = true;
public allowDuplicates = false;
public keepOpen = false;
public formatter: TsSelectionListFormatter | undefined;
// Must be overwritten with a spy in the test
public duplicate = v => { };
public setNewStates() {
this.states = STATES.slice(3, 7);
}
public setFormatter() {
this.formatter = v => (v as State).population;
}
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[displayFormatter]="formatter"
[allowUserInput]="allowUserInput"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
<span tsOptionDisplay>
{{ option.name }}
</span>
</ts-option>
</ts-selection-list>
`,
})
export class SeededSingleSelect {
public states: State[] = STATES.slice();
public myCtrl = new FormControl([STATES[6]]);
public allowUserInput = false;
public formatter(state: State) {
return state.population;
}
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="allowMultiple"
[allowDuplicateSelections]="allowDuplicates"
[reopenAfterSelection]="keepOpen"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
<span tsOptionDisplay>
{{ option.name }}
</span>
</ts-option>
</ts-selection-list>
`,
})
export class PassingInObjectValue {
public states: State[] = STATES.slice();
public myCtrl = new FormControl([STATES[4]]);
public allowMultiple = false;
public allowDuplicates = false;
public keepOpen = false;
// Must be overwritten with a spy in the test
public duplicate = v => { };
}
@Component({
template: `
<ts-selection-list
[(ngModel)]="myModel"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
<span tsOptionDisplay>
{{ option.name }}
</span>
</ts-option>
</ts-selection-list>
`,
})
export class SeededNgModel {
public myModel = [STATES[4]];
public states: State[] = STATES.slice();
}
@Component({
template: `
<ts-selection-list [(ngModel)]="myModel">
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
{{ option.name }}
</ts-option>
</ts-selection-list>
`,
})
export class SeededNgModelError {
public myModel = { id: 'foo' };
public states: State[] = STATES.slice();
}
@Component({
template: `
<ts-selection-list [formControl]="meow">
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
<span tsOptionDisplay>
{{ option.name }}
</span>
</ts-option>
</ts-selection-list>
`,
})
export class SeededNonArray {
public states: State[] = STATES.slice();
public meow = new FormControl(this.states[0]);
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="allowMultiple"
[reopenAfterSelection]="false"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
<span tsOptionDisplay>
{{ option.name }}
</span>
</ts-option>
</ts-selection-list>
`,
})
export class AllowMultipleNoReopen {
public myCtrl = new FormControl();
public states: State[] = STATES.slice();
public allowMultiple = true;
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[isDisabled]="true"
(opened)="wasOpened($event)"
>
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of options"
><span tsOptionDisplay>{{ option.name }}</span></ts-option>
</ts-selection-list>
`,
})
export class Disabled {
public myCtrl = new FormControl();
public options = STATES.slice();
public wasOpened = v => { };
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="true"
>
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of options"
>{{ option.name }}</ts-option>
</ts-selection-list>
`,
})
export class SelectOptionChange {
public myCtrl = new FormControl([STATES[3], STATES[4]]);
public options: State[] = STATES.slice(0, 10);
public updateOptions() {
const otherStates: State[] = STATES.slice(10, 14);
this.options.push(...otherStates);
}
}
@Component({
template: `
<ts-selection-list
[ngModel]="selectedFood"
(ngModelChange)="setFoodByCopy($event)"
>
<ts-option
[value]="option"
[option]="option"
*ngFor="let option of foods"
>{{ option.viewValue }}</ts-option>
</ts-selection-list>
`,
})
export class CustomCompareFn {
public foods: ({ value: string; viewValue: string })[] = [
{
value: 'steak-0',
viewValue: 'Steak',
},
{
value: 'pizza-1',
viewValue: 'Pizza',
},
{
value: 'tacos-2',
viewValue: 'Tacos',
},
];
public selectedFood: { value: string; viewValue: string } = {
value: 'pizza-1',
viewValue: 'Pizza',
};
public comparator: ((f1: any, f2: any) => boolean) | null = this.compareByValue;
public useCompareByValue() {
this.comparator = this.compareByValue;
}
public useCompareByReference() {
this.comparator = this.compareByReference;
}
public useNullComparator() {
this.comparator = null;
}
public compareByValue(f1: any, f2: any) {
return f1 && f2 && f1.value === f2.value;
}
public compareByReference(f1: any, f2: any) {
return f1 === f2;
}
public setFoodByCopy(newValue: { value: string; viewValue: string }) {
this.selectedFood = {
...{},
...newValue,
};
}
}
@Component({
template: `
<ts-selection-list [formControl]="myCtrl">
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of items"
><span tsOptionDisplay>{{ option.name }}</span></ts-option>
</ts-selection-list>
`,
})
export class DeferOptionSelectionStream {
public myCtrl = new FormControl([STATES[4]]);
public items: any[] = [];
public updateOptions() {
this.items = STATES.slice();
}
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
(queryChange)="change($event)"
>
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of options"
>{{ option.name }}</ts-option>
</ts-selection-list>
`,
})
export class Debounce {
public myCtrl = new FormControl([STATES[3], STATES[4]]);
public options = STATES.slice();
public change = v => { };
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
debounceDelay="0"
(queryChange)="change($event)"
>
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of options"
>{{ option.name }}</ts-option>
</ts-selection-list>
`,
})
export class CustomDebounce {
public myCtrl = new FormControl([STATES[3], STATES[4]]);
public options = STATES.slice();
public change = v => { };
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[minimumCharacters]="customCount"
debounceDelay="0"
(queryChange)="change($event)"
>
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of options"
>{{ option.name }}</ts-option>
</ts-selection-list>
`,
})
export class CustomCharacterCount {
public myCtrl = new FormControl([STATES[3], STATES[4]]);
public options = STATES.slice();
public customCount: number | undefined;
public change = v => { };
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[hideRequiredMarker]="hideRequired"
[isRequired]="true"
>
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of options"
>{{ option.name }}</ts-option>
</ts-selection-list>
`,
})
export class HideRequired {
public myCtrl = new FormControl();
public options = STATES.slice();
public hideRequired = false;
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[hint]="myHint"
>
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of options"
>{{ option.name }}</ts-option>
</ts-selection-list>
`,
})
export class Hint {
public myCtrl = new FormControl();
public myHint = 'foo';
public options = STATES.slice();
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[id]="myId"
>
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of options"
>{{ option.name }}</ts-option>
</ts-selection-list>
`,
})
export class Id {
public myCtrl = new FormControl();
public myId = 'foo';
public options = STATES.slice();
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[label]="myLabel"
>
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of options"
>{{ option.name }}</ts-option>
</ts-selection-list>
`,
})
export class Label {
public myCtrl = new FormControl();
public myLabel = 'foo bar';
public options = STATES.slice();
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[validateOnChange]="validateOnChange"
>
<ts-option
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
*ngFor="let option of options"
>{{ option.name }}</ts-option>
</ts-selection-list>
`,
})
export class ValidateOnChange {
public myCtrl = new FormControl(null, Validators.required);
public validateOnChange = true;
public options = STATES.slice();
}
@Component({
template: `
<ts-selection-list [formControl]="myCtrl">
<ts-option
[value]="option"
[option]="option"
*ngFor="let option of items"
>{{ option.viewValue }}</ts-option>
</ts-selection-list>
`,
})
export class NullSelection {
public items = [
{
value: 'foo',
viewValue: 'foo view',
},
{
value: null,
viewValue: null,
},
{
value: 'bar',
viewValue: 'bar view',
},
];
public myCtrl = new FormControl(this.items[2]);
}
@Component({
template: `
<ts-selection-list [formControl]="myCtrl">
<ts-option
[value]="state"
*ngFor="let state of items"
>
<ng-template let-option>
<div class="myClass">
<h4 tsOptionDisplay>{{ option?.state }}</h4>
<small>{{ option?.population }}</small>
</div>
</ng-template>
</ts-option>
</ts-selection-list>
`,
})
export class OptionError {
public myCtrl = new FormControl();
public items = STATES.slice(0, 2);
}
@Component({
template: `
<ts-selection-list [formControl]="myCtrl">
<ts-option
[value]="state"
[option]="state"
[id]="state.name"
*ngFor="let state of items"
(selectionChange)="change($event)"
>
{{ state.name }}
</ts-option>
</ts-selection-list>
`,
})
export class OptionId {
public myCtrl = new FormControl();
public items = STATES.slice(0, 4);
public change = v => { };
}
@Component({
template: `
<ts-selection-list [formControl]="myCtrl">
<ts-select-optgroup
*ngFor="let group of groups"
[id]="group.name"
[label]="group.name"
>
<ts-option
*ngFor="let option of group.children"
[value]="option"
[option]="option"
>
{{ option.name }}
</ts-option>
</ts-select-optgroup>
</ts-selection-list>
`,
})
export class OptgroupIDs {
public myCtrl = new FormControl();
public groups = STATES_GROUPED.slice();
}
@Component({
template: `
<ts-selection-list [formControl]="myCtrl">
<ts-select-optgroup
*ngFor="let group of groups"
[id]="group.name"
[label]="group.name"
>
<ts-option
*ngFor="let option of group.children"
[value]="option"
[option]="option"
>
{{ option.name }}
</ts-option>
</ts-select-optgroup>
</ts-selection-list>
`,
})
export class OptgroupBadIDs {
public myCtrl = new FormControl([STATES[4]]);
public groups = STATES_GROUPED.slice();
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[displayFormatter]="myFormatter"
[allowMultiple]="allowMultiple"
>
<ts-option
*ngFor="let option of states"
[value]="option"
[option]="option"
[isDisabled]="option?.disabled"
>
{{ option.name }}
</ts-option>
</ts-selection-list>
`,
})
export class Formatter {
public myCtrl = new FormControl([STATES[0]]);
public states: State[] = STATES.slice();
public allowMultiple = true;
public myFormatter(v: State): string {
return v.name.toUpperCase();
}
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="allowMultiple"
>
<ts-option
*ngFor="let option of options"
[value]="option"
[option]="option"
>
{{ option }}
</ts-option>
</ts-selection-list>
`,
})
export class SimpleArray {
public myCtrl = new FormControl();
public options: string[] = ['foo', 'bar', 'baz'];
public allowMultiple = true;
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="allowMultiple"
(selectionChange)="mySelection($event)"
>
<ts-option
*ngFor="let option of options"
[value]="option"
[option]="option"
>
{{ option }}
</ts-option>
</ts-selection-list>
`,
})
export class SelectionEvent {
public myCtrl = new FormControl(['bar']);
public options: string[] = ['foo', 'bar', 'baz'];
public allowMultiple = true;
public lastSelection: TsSelectionListChange | undefined;
public mySelection(e: TsSelectionListChange): void {
this.lastSelection = e;
}
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[allowMultiple]="true"
(backdropClicked)="clicked()"
>
<ts-option
*ngFor="let option of options"
[value]="option"
[option]="option"
>
{{ option }}
</ts-option>
</ts-selection-list>
`,
})
export class BackdropClick {
public myCtrl = new FormControl(['bar']);
public options: string[] = ['foo', 'bar', 'baz'];
public clicked = () => {};
}
@Component({
template: `
<ts-selection-list
[formControl]="myCtrl"
[noValidationOrHint]="validationFlag"
></ts-selection-list>
`,
})
export class NoValidationOrHint {
public myCtrl = new FormControl();
public validationFlag = true;
}
/**
* NOTE: Currently all exported Components must belong to a module. So this is our useless module to avoid the build error.
*/
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
TsSelectionListModule,
TsOptionModule,
],
declarations: [
AllowMultipleNoReopen,
BackdropClick,
Basic,
CustomCharacterCount,
CustomCompareFn,
CustomDebounce,
Debounce,
DeferOptionSelectionStream,
Disabled,
Formatter,
HideRequired,
Hint,
Id,
Label,
Multiple,
NoValidationOrHint,
NullSelection,
OptgroupBadIDs,
OptgroupIDs,
OptionError,
OptionId,
PassingInObjectValue,
Required,
Seeded,
ManualSeeded,
SeededNgModel,
SeededNgModelError,
SeededNonArray,
SeededSingleSelect,
SelectionEvent,
SelectOptionChange,
SimpleArray,
ValidateOnChange,
],
})
export class TsSelectionListTestComponentsModule { } | the_stack |
import { CreateEndpointBasicAuthRepresentation } from '../model/createEndpointBasicAuthRepresentation';
import { EndpointBasicAuthRepresentation } from '../model/endpointBasicAuthRepresentation';
import { EndpointConfigurationRepresentation } from '../model/endpointConfigurationRepresentation';
import { BaseApi } from './base.api';
import { throwIfNotDefined } from '../../../assert';
/**
* Adminendpoints service.
* @module AdminendpointsApi
*/
export class AdminEndpointsApi extends BaseApi {
/**
* Add an endpoint authorization
*
*
*
* @param createRepresentation createRepresentation
* @return Promise<EndpointBasicAuthRepresentation>
*/
createBasicAuthConfiguration(createRepresentation: CreateEndpointBasicAuthRepresentation): Promise<EndpointBasicAuthRepresentation> {
throwIfNotDefined(createRepresentation, 'createRepresentation');
let postBody = createRepresentation;
let pathParams = {
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/admin/basic-auths', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, EndpointBasicAuthRepresentation);
}
/**
* Create an endpoint
*
*
*
* @param representation representation
* @return Promise<EndpointConfigurationRepresentation>
*/
createEndpointConfiguration(representation: EndpointConfigurationRepresentation): Promise<EndpointConfigurationRepresentation> {
throwIfNotDefined(representation, 'representation');
let postBody = representation;
let pathParams = {
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/admin/endpoints', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, EndpointConfigurationRepresentation);
}
/**
* Get an endpoint authorization
*
*
*
* @param basicAuthId basicAuthId
* @param tenantId tenantId
* @return Promise<EndpointBasicAuthRepresentation>
*/
getBasicAuthConfiguration(basicAuthId: number, tenantId: number): Promise<EndpointBasicAuthRepresentation> {
throwIfNotDefined(basicAuthId, 'basicAuthId');
throwIfNotDefined(tenantId, 'tenantId');
let postBody = null;
let pathParams = {
'basicAuthId': basicAuthId
};
let queryParams = {
'tenantId': tenantId
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/admin/basic-auths/{basicAuthId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, EndpointBasicAuthRepresentation);
}
/**
* List endpoint authorizations
*
*
*
* @param tenantId tenantId
* @return Promise<EndpointBasicAuthRepresentation>
*/
getBasicAuthConfigurations(tenantId: number): Promise<EndpointBasicAuthRepresentation> {
throwIfNotDefined(tenantId, 'tenantId');
let postBody = null;
let pathParams = {
};
let queryParams = {
'tenantId': tenantId
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/admin/basic-auths', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, EndpointBasicAuthRepresentation);
}
/**
* Get an endpoint
*
*
*
* @param endpointConfigurationId endpointConfigurationId
* @param tenantId tenantId
* @return Promise<EndpointConfigurationRepresentation>
*/
getEndpointConfiguration(endpointConfigurationId: number, tenantId: number): Promise<EndpointConfigurationRepresentation> {
throwIfNotDefined(endpointConfigurationId, 'endpointConfigurationId');
throwIfNotDefined(tenantId, 'tenantId');
let postBody = null;
let pathParams = {
'endpointConfigurationId': endpointConfigurationId
};
let queryParams = {
'tenantId': tenantId
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/admin/endpoints/{endpointConfigurationId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, EndpointConfigurationRepresentation);
}
/**
* List endpoints
*
*
*
* @param tenantId tenantId
* @return Promise<EndpointConfigurationRepresentation>
*/
getEndpointConfigurations(tenantId: number): Promise<EndpointConfigurationRepresentation> {
throwIfNotDefined(tenantId, 'tenantId');
let postBody = null;
let pathParams = {
};
let queryParams = {
'tenantId': tenantId
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/admin/endpoints', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, EndpointConfigurationRepresentation);
}
/**
* Delete an endpoint authorization
*
*
*
* @param basicAuthId basicAuthId
* @param tenantId tenantId
* @return Promise<{}>
*/
removeBasicAuthConfiguration(basicAuthId: number, tenantId: number): Promise<any> {
throwIfNotDefined(basicAuthId, 'basicAuthId');
throwIfNotDefined(tenantId, 'tenantId');
let postBody = null;
let pathParams = {
'basicAuthId': basicAuthId
};
let queryParams = {
'tenantId': tenantId
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/admin/basic-auths/{basicAuthId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Delete an endpoint
*
*
*
* @param endpointConfigurationId endpointConfigurationId
* @param tenantId tenantId
* @return Promise<{}>
*/
removeEndpointConfiguration(endpointConfigurationId: number, tenantId: number): Promise<any> {
throwIfNotDefined(endpointConfigurationId, 'endpointConfigurationId');
throwIfNotDefined(tenantId, 'tenantId');
let postBody = null;
let pathParams = {
'endpointConfigurationId': endpointConfigurationId
};
let queryParams = {
'tenantId': tenantId
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/admin/endpoints/{endpointConfigurationId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
/**
* Update an endpoint authorization
*
*
*
* @param basicAuthId basicAuthId
* @param createRepresentation createRepresentation
* @return Promise<EndpointBasicAuthRepresentation>
*/
updateBasicAuthConfiguration(basicAuthId: number, createRepresentation: CreateEndpointBasicAuthRepresentation): Promise<EndpointBasicAuthRepresentation> {
throwIfNotDefined(basicAuthId, 'basicAuthId');
throwIfNotDefined(createRepresentation, 'createRepresentation');
let postBody = createRepresentation;
let pathParams = {
'basicAuthId': basicAuthId
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/admin/basic-auths/{basicAuthId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, EndpointBasicAuthRepresentation);
}
/**
* Update an endpoint
*
*
*
* @param endpointConfigurationId endpointConfigurationId
* @param representation representation
* @return Promise<EndpointConfigurationRepresentation>
*/
updateEndpointConfiguration(endpointConfigurationId: number, representation: EndpointConfigurationRepresentation): Promise<EndpointConfigurationRepresentation> {
throwIfNotDefined(endpointConfigurationId, 'endpointConfigurationId');
throwIfNotDefined(representation, 'representation');
let postBody = representation;
let pathParams = {
'endpointConfigurationId': endpointConfigurationId
};
let queryParams = {
};
let headerParams = {
};
let formParams = {
};
let contentTypes = ['application/json'];
let accepts = ['application/json'];
return this.apiClient.callApi(
'/api/enterprise/admin/endpoints/{endpointConfigurationId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, EndpointConfigurationRepresentation);
}
} | the_stack |
import CardNode, { CardData, CardRenderHook } from '../models/card-node'
import { detect, forEach, ForEachable } from '../utils/array-utils'
import AtomNode, { AtomData, AtomRenderHook } from '../models/atom-node'
import { Type } from '../models/types'
import { startsWith, endsWith } from '../utils/string-utils'
import { addClassName, removeClassName } from '../utils/dom-utils'
import MarkupSection, { MARKUP_SECTION_ELEMENT_NAMES } from '../models/markup-section'
import assert, { unwrap, assertNotNull, assertExistsIn } from '../utils/assert'
import { TAB } from '../utils/characters'
import Markup from '../models/markup'
import Marker from '../models/marker'
import Section from '../models/_section'
import { Attributable } from '../models/_attributable'
import { TagNameable } from '../models/_tag-nameable'
import ListSection from '../models/list-section'
import RenderNode from '../models/render-node'
import { Option, Maybe, Dict } from '../utils/types'
import Atom from '../models/atom'
import Editor from '../editor/editor'
import { hasChildSections } from '../models/_has-child-sections'
import Post from '../models/post'
import ListItem from '../models/list-item'
import Image from '../models/image'
import Card from '../models/card'
import RenderTree from '../models/render-tree'
import { PostNode } from '../models/post-node-builder'
export const CARD_ELEMENT_CLASS_NAME = '__mobiledoc-card'
export const NO_BREAK_SPACE = '\u00A0'
export const TAB_CHARACTER = '\u2003'
export const SPACE = ' '
export const ZWNJ = '\u200c'
export const ATOM_CLASS_NAME = '-mobiledoc-kit__atom'
export const EDITOR_HAS_NO_CONTENT_CLASS_NAME = '__has-no-content'
export const EDITOR_ELEMENT_CLASS_NAME = '__mobiledoc-editor'
function createElementFromMarkup(doc: Document, markup: Markup) {
let element = doc.createElement(markup.tagName)
Object.keys(markup.attributes).forEach(k => {
element.setAttribute(k, markup.attributes[k])
})
return element
}
const TWO_SPACES = `${SPACE}${SPACE}`
const SPACE_AND_NO_BREAK = `${SPACE}${NO_BREAK_SPACE}`
const SPACES_REGEX = new RegExp(TWO_SPACES, 'g')
const TAB_REGEX = new RegExp(TAB, 'g')
const endsWithSpace = function (text: string) {
return endsWith(text, SPACE)
}
const startsWithSpace = function (text: string) {
return startsWith(text, SPACE)
}
// FIXME: This can be done more efficiently with a single pass
// building a correct string based on the original.
function renderHTMLText(marker: Marker) {
let text = marker.value
text = text.replace(SPACES_REGEX, SPACE_AND_NO_BREAK).replace(TAB_REGEX, TAB_CHARACTER)
// If the first marker has a leading space or the last marker has a
// trailing space, the browser will collapse the space when we position
// the cursor.
// See https://github.com/bustle/mobiledoc-kit/issues/68
// and https://github.com/bustle/mobiledoc-kit/issues/75
if (marker.isMarker && endsWithSpace(text) && !marker.next) {
text = text.substr(0, text.length - 1) + NO_BREAK_SPACE
}
if (
marker.isMarker &&
startsWithSpace(text) &&
(!marker.prev || (marker.prev.isMarker && endsWithSpace(marker.prev.value)))
) {
text = NO_BREAK_SPACE + text.substr(1)
}
return text
}
// ascends from element upward, returning the last parent node that is not
// parentElement
function penultimateParentOf(element: Node, parentElement: Node) {
while (
parentElement &&
element.parentNode !== parentElement &&
element.parentNode !== document.body // ensure the while loop stops
) {
element = element.parentNode as Node
}
return element
}
function setSectionAttributesOnElement(section: Attributable, element: HTMLElement) {
section.eachAttribute((key, value) => {
element.setAttribute(key, value)
})
}
function renderMarkupSection(section: TagNameable & Attributable) {
let element: HTMLElement
if (MARKUP_SECTION_ELEMENT_NAMES.indexOf(section.tagName) !== -1) {
element = document.createElement(section.tagName)
} else {
element = document.createElement('div')
addClassName(element, section.tagName)
}
setSectionAttributesOnElement(section, element)
return element
}
function renderListSection(section: ListSection) {
let element = document.createElement(section.tagName)
setSectionAttributesOnElement(section, element)
return element
}
function renderListItem() {
return document.createElement('li')
}
function renderCursorPlaceholder() {
return document.createElement('br')
}
function renderInlineCursorPlaceholder() {
return document.createTextNode(ZWNJ)
}
function renderCard() {
let wrapper = document.createElement('div')
let cardElement = document.createElement('div')
cardElement.contentEditable = 'false'
addClassName(cardElement, CARD_ELEMENT_CLASS_NAME)
wrapper.appendChild(renderInlineCursorPlaceholder())
wrapper.appendChild(cardElement)
wrapper.appendChild(renderInlineCursorPlaceholder())
return { wrapper, cardElement }
}
/**
* Wrap the element in all of the opened markups
* @return {DOMElement} the wrapped element
* @private
*/
function wrapElement(element: Node, openedMarkups: Markup[]): Node {
let wrappedElement = element
for (let i = openedMarkups.length - 1; i >= 0; i--) {
let markup = openedMarkups[i]
let openedElement = createElementFromMarkup(document, markup)
openedElement.appendChild(wrappedElement)
wrappedElement = openedElement
}
return wrappedElement
}
// Attach the element to its parent element at the correct position based on the
// previousRenderNode
function attachElementToParent(element: Node, parentElement: Node, previousRenderNode: Option<RenderNode> = null) {
if (previousRenderNode) {
let previousSibling = previousRenderNode.element!
let previousSiblingPenultimate = penultimateParentOf(previousSibling, parentElement)
parentElement.insertBefore(element, previousSiblingPenultimate.nextSibling)
} else {
parentElement.insertBefore(element, parentElement.firstChild)
}
}
function renderAtom(atom: Atom, element: HTMLElement, previousRenderNode: Option<RenderNode>) {
let atomElement = document.createElement('span')
atomElement.contentEditable = 'false'
let wrapper = document.createElement('span')
addClassName(wrapper, ATOM_CLASS_NAME)
let headTextNode = renderInlineCursorPlaceholder()
let tailTextNode = renderInlineCursorPlaceholder()
wrapper.appendChild(headTextNode)
wrapper.appendChild(atomElement)
wrapper.appendChild(tailTextNode)
let wrappedElement = wrapElement(wrapper, atom.openedMarkups)
attachElementToParent(wrappedElement, element, previousRenderNode)
return {
markupElement: wrappedElement,
wrapper,
atomElement,
headTextNode,
tailTextNode,
}
}
function getNextMarkerElement(renderNode: RenderNode) {
let element = renderNode.element!.parentNode
let marker = renderNode.postNode! as Marker
let closedCount = marker.closedMarkups.length
while (closedCount--) {
element = element!.parentNode
}
return element
}
interface RenderMarkerResult {
element: Node
markupElement: Node
}
/**
* Render the marker
* @param {Marker} marker the marker to render
* @param {DOMNode} element the element to attach the rendered marker to
* @param {RenderNode} [previousRenderNode] The render node before this one, which
* affects the determination of where to insert this rendered marker.
* @return {Object} With properties `element` and `markupElement`.
* The node (textNode) that has the text for
* this marker, and the outermost rendered element. If the marker has no
* markups, element and markupElement will be the same textNode
* @private
*/
function renderMarker(marker: Marker, parentElement: Node, previousRenderNode: Option<RenderNode>): RenderMarkerResult {
let text = renderHTMLText(marker)
let element = document.createTextNode(text)
let markupElement = wrapElement(element, marker.openedMarkups)
attachElementToParent(markupElement, parentElement, previousRenderNode)
return { element, markupElement }
}
// Attach the render node's element to the DOM,
// replacing the originalElement if it exists
function attachRenderNodeElementToDOM(renderNode: RenderNode, originalElement: Option<Node> = null) {
const element = unwrap(renderNode.element)
assertNotNull('expected RenderNode to have a parent', renderNode.parent)
if (originalElement) {
// RenderNode has already rendered
let parentElement = renderNode.parent.element!
parentElement.replaceChild(element, originalElement)
} else {
// RenderNode has not yet been rendered
let parentElement: Node
let nextSiblingElement: Option<Node>
if (renderNode.prev) {
let previousElement = unwrap(renderNode.prev.element)
parentElement = unwrap(previousElement.parentNode)
nextSiblingElement = previousElement.nextSibling
} else {
parentElement = renderNode.parent.element!
nextSiblingElement = parentElement.firstChild
}
parentElement.insertBefore(element, nextSiblingElement)
}
}
function removeRenderNodeSectionFromParent(renderNode: RenderNode, section: Section) {
assertNotNull('expected RenderNode to have a parent', renderNode.parent)
assertNotNull('expected parent RenderNode to have a PostNode', renderNode.parent.postNode)
const parent = renderNode.parent.postNode
assert('expected PostNode to have sections', hasChildSections(parent))
parent.sections.remove(section)
}
function removeRenderNodeElementFromParent(renderNode: RenderNode) {
if (renderNode.element && renderNode.element.parentNode) {
renderNode.element.parentNode.removeChild(renderNode.element)
}
}
function validateCards(cards: CardData[] = []) {
forEach(cards, card => {
assert(`Card "${card.name}" must define type "dom", has: "${card.type}"`, card.type === 'dom')
assert(`Card "${card.name}" must define \`render\` method`, !!card.render)
})
return cards
}
function validateAtoms(atoms: AtomData[] = []) {
forEach(atoms, atom => {
assert(`Atom "${atom.name}" must define type "dom", has: "${atom.type}"`, atom.type === 'dom')
assert(`Atom "${atom.name}" must define \`render\` method`, !!atom.render)
})
return atoms
}
type VisitArgs = [RenderNode, ForEachable<PostNode>, boolean?]
type VisitFn = (...args: VisitArgs) => void
class Visitor {
editor: Editor
cards: CardData[]
atoms: AtomData[]
unknownCardHandler: CardRenderHook
unknownAtomHandler: AtomRenderHook
options: Dict<unknown>
constructor(
editor: Editor,
cards: CardData[],
atoms: AtomData[],
unknownCardHandler: CardRenderHook,
unknownAtomHandler: AtomRenderHook,
options: Dict<unknown>
) {
this.editor = editor
this.cards = validateCards(cards)
this.atoms = validateAtoms(atoms)
this.unknownCardHandler = unknownCardHandler
this.unknownAtomHandler = unknownAtomHandler
this.options = options
}
_findCard(cardName: string) {
let card = detect(this.cards, card => card.name === cardName)
return card || this._createUnknownCard(cardName)
}
_createUnknownCard(cardName: string): CardData {
assert(`Unknown card "${cardName}" found, but no unknownCardHandler is defined`, !!this.unknownCardHandler)
return {
name: cardName,
type: 'dom',
render: this.unknownCardHandler,
edit: this.unknownCardHandler,
}
}
_findAtom(atomName: string) {
let atom = detect(this.atoms, atom => atom.name === atomName)
return atom || this._createUnknownAtom(atomName)
}
_createUnknownAtom(atomName: string): AtomData {
assert(`Unknown atom "${atomName}" found, but no unknownAtomHandler is defined`, !!this.unknownAtomHandler)
return {
name: atomName,
type: 'dom',
render: this.unknownAtomHandler,
}
}
[Type.POST](renderNode: RenderNode, post: Post, visit: VisitFn) {
if (!renderNode.element) {
renderNode.element = document.createElement('div')
}
let element = renderNode.element as Element
addClassName(element, EDITOR_ELEMENT_CLASS_NAME)
if (post.hasContent) {
removeClassName(element, EDITOR_HAS_NO_CONTENT_CLASS_NAME)
} else {
addClassName(element, EDITOR_HAS_NO_CONTENT_CLASS_NAME)
}
visit(renderNode, post.sections)
}
[Type.MARKUP_SECTION](renderNode: RenderNode, section: MarkupSection, visit: VisitFn) {
const originalElement = renderNode.element
// Always rerender the section -- its tag name or attributes may have changed.
// TODO make this smarter, only rerendering and replacing the element when necessary
renderNode.element = renderMarkupSection(section)
renderNode.cursorElement = null
attachRenderNodeElementToDOM(renderNode, originalElement)
if (section.isBlank) {
let cursorPlaceholder = renderCursorPlaceholder()
renderNode.element.appendChild(cursorPlaceholder)
renderNode.cursorElement = cursorPlaceholder
} else {
const visitAll = true
visit(renderNode, section.markers, visitAll)
}
}
[Type.LIST_SECTION](renderNode: RenderNode, section: ListSection, visit: VisitFn) {
const originalElement = renderNode.element
renderNode.element = renderListSection(section)
attachRenderNodeElementToDOM(renderNode, originalElement)
const visitAll = true
visit(renderNode, section.items, visitAll)
}
[Type.LIST_ITEM](renderNode: RenderNode, item: ListItem, visit: VisitFn) {
// FIXME do we need to do anything special for rerenders?
renderNode.element = renderListItem()
renderNode.cursorElement = null
attachRenderNodeElementToDOM(renderNode, null)
if (item.isBlank) {
let cursorPlaceholder = renderCursorPlaceholder()
renderNode.element.appendChild(cursorPlaceholder)
renderNode.cursorElement = cursorPlaceholder
} else {
const visitAll = true
visit(renderNode, item.markers, visitAll)
}
}
[Type.MARKER](renderNode: RenderNode, marker: Marker) {
let parentElement: Node
if (renderNode.prev) {
parentElement = getNextMarkerElement(renderNode.prev)!
} else {
parentElement = renderNode.parent!.element!
}
let { element, markupElement } = renderMarker(marker, parentElement, renderNode.prev)
renderNode.element = element
renderNode.markupElement = markupElement
}
[Type.IMAGE_SECTION](renderNode: RenderNode<HTMLImageElement>, section: Image) {
if (renderNode.element) {
if (renderNode.element.src !== section.src) {
renderNode.element.src = section.src || ''
}
} else {
let element = document.createElement('img')
element.src = section.src || ''
if (renderNode.prev) {
let previousElement = renderNode.prev.element!
let nextElement = previousElement.nextSibling
if (nextElement) {
nextElement.parentNode!.insertBefore(element, nextElement)
}
}
if (!element.parentNode) {
renderNode.parent!.element!.appendChild(element)
}
renderNode.element = element
}
}
[Type.CARD](renderNode: RenderNode, section: Card) {
const originalElement = renderNode.element
const { editor, options } = this
const card = this._findCard(section.name)
let { wrapper, cardElement } = renderCard()
renderNode.element = wrapper
attachRenderNodeElementToDOM(renderNode, originalElement)
const cardNode = new CardNode(editor, card, section, cardElement, options)
renderNode.cardNode = cardNode
const initialMode = section._initialMode
cardNode[initialMode]()
}
[Type.ATOM](renderNode: RenderNode, atomModel: Atom) {
let parentElement: Node
if (renderNode.prev) {
parentElement = getNextMarkerElement(renderNode.prev)!
} else {
parentElement = renderNode.parent!.element!
}
const { editor, options } = this
const { wrapper, markupElement, atomElement, headTextNode, tailTextNode } = renderAtom(
atomModel,
parentElement as HTMLElement,
renderNode.prev
)
const atom = this._findAtom(atomModel.name)
let atomNode = renderNode.atomNode
if (!atomNode) {
// create new AtomNode
atomNode = new AtomNode(editor, atom, atomModel, atomElement, options)
} else {
// retarget atomNode to new atom element
atomNode.element = atomElement
}
atomNode.render()
renderNode.atomNode = atomNode
renderNode.element = wrapper
renderNode.headTextNode = headTextNode
renderNode.tailTextNode = tailTextNode
renderNode.markupElement = markupElement
}
}
let destroyHooks = {
[Type.POST](/*renderNode, post*/) {
assert('post destruction is not supported by the renderer', false)
},
[Type.MARKUP_SECTION](renderNode: RenderNode, section: MarkupSection) {
removeRenderNodeSectionFromParent(renderNode, section)
removeRenderNodeElementFromParent(renderNode)
},
[Type.LIST_SECTION](renderNode: RenderNode, section: ListSection) {
removeRenderNodeSectionFromParent(renderNode, section)
removeRenderNodeElementFromParent(renderNode)
},
[Type.LIST_ITEM](renderNode: RenderNode, li: ListItem) {
removeRenderNodeSectionFromParent(renderNode, li)
removeRenderNodeElementFromParent(renderNode)
},
[Type.MARKER](renderNode: RenderNode, marker: Marker) {
// FIXME before we render marker, should delete previous renderNode's element
// and up until the next marker element
// If an atom throws during render we may end up later destroying a renderNode
// that has not rendered yet, so exit early here if so.
if (!renderNode.isRendered) {
return
}
let { markupElement } = renderNode
if (marker.section) {
marker.section.markers.remove(marker)
}
if (markupElement!.parentNode) {
// if no parentNode, the browser already removed this element
markupElement!.parentNode.removeChild(markupElement!)
}
},
[Type.IMAGE_SECTION](renderNode: RenderNode, section: Image) {
removeRenderNodeSectionFromParent(renderNode, section)
removeRenderNodeElementFromParent(renderNode)
},
[Type.CARD](renderNode: RenderNode, section: Card) {
if (renderNode.cardNode) {
renderNode.cardNode.teardown()
}
removeRenderNodeSectionFromParent(renderNode, section)
removeRenderNodeElementFromParent(renderNode)
},
[Type.ATOM](renderNode: RenderNode, atom: Atom) {
if (renderNode.atomNode) {
renderNode.atomNode.teardown()
}
// an atom is a kind of marker so just call its destroy hook vs copying here
destroyHooks[Type.MARKER](renderNode, (atom as unknown) as Marker)
},
}
// removes children from parentNode (a RenderNode) that are scheduled for removal
function removeDestroyedChildren(parentNode: RenderNode, forceRemoval = false) {
let child = parentNode.childNodes.head
let nextChild: Option<RenderNode>, method: Type
while (child) {
nextChild = child.next
if (child.isRemoved || forceRemoval) {
removeDestroyedChildren(child, true)
method = child.postNode!.type
assertExistsIn(`editor-dom cannot destroy "${method}"`, method, destroyHooks)
;(destroyHooks[method] as any)(child, child.postNode)
parentNode.childNodes.remove(child)
}
child = nextChild
}
}
// Find an existing render node for the given postNode, or
// create one, insert it into the tree, and return it
function lookupNode(renderTree: RenderTree, parentNode: RenderNode, postNode: PostNode, previousNode: RenderNode) {
if (postNode.renderNode) {
return postNode.renderNode
} else {
const renderNode = renderTree.buildRenderNode(postNode)
parentNode.childNodes.insertAfter(renderNode, previousNode)
return renderNode
}
}
export default class Renderer {
editor: Editor
visitor: Visitor
nodes: RenderNode[]
hasRendered: boolean
renderTree: Option<RenderTree> = null
constructor(
editor: Editor,
cards: CardData[],
atoms: AtomData[],
unknownCardHandler: CardRenderHook,
unknownAtomHandler: AtomRenderHook,
options: {}
) {
this.editor = editor
this.visitor = new Visitor(editor, cards, atoms, unknownCardHandler, unknownAtomHandler, options)
this.nodes = []
this.hasRendered = false
}
destroy() {
if (!this.hasRendered) {
return
}
let renderNode = unwrap(this.renderTree).rootNode
let force = true
removeDestroyedChildren(renderNode, force)
}
visit(renderTree: RenderTree, parentNode: RenderNode, postNodes: ForEachable<PostNode>, visitAll = false) {
let previousNode: RenderNode
postNodes.forEach(postNode => {
let node = lookupNode(renderTree, parentNode, postNode, previousNode)
if (node.isDirty || visitAll) {
this.nodes.push(node)
}
previousNode = node
})
}
render(renderTree: RenderTree) {
this.hasRendered = true
this.renderTree = renderTree
let renderNode: Maybe<RenderNode> = renderTree.rootNode
let method: Type
let postNode: PostNode
while (renderNode) {
removeDestroyedChildren(renderNode)
postNode = renderNode.postNode!
method = postNode.type
assertExistsIn(`EditorDom visitor cannot handle type ${method}`, method, this.visitor)
this.visitor[method](renderNode as any, postNode as any, (...args: VisitArgs) => this.visit(renderTree, ...args))
renderNode.markClean()
renderNode = this.nodes.shift()
}
}
} | the_stack |
import * as React from "react";
import {Input} from "./Input";
import {OutputEditor} from "./OutputEditor";
import {JavaSettings, JavaSettingsForm} from "./JavaSettings";
import {PythonSettings, PythonSettingsForm} from "./PythonSettings";
import {CsharpSettings, CsharpSettingsForm} from "./CsharpSettings";
import {GoSettings, GoSettingsForm} from "./GoSettings";
import {RustSettings, RustSettingsForm} from "./RustSettings";
import {OpenApiSettings, OpenApiSettingsForm} from "./OpenApiSettings";
import {SwiftSettings, SwiftSettingsForm} from "./SwiftSettings";
import {DartSettings, DartSettingsForm} from "./DartSettings";
import {IAnnotation, IMarker} from 'react-ace';
import AceEditor from 'react-ace';
const deepEqual = require("deep-equal");
const ace_languages = [
"csharp",
"golang",
"java",
"javascript",
"json",
"python",
"rust",
"swift",
"dart",
"yaml",
]
const themes = [
"monokai",
"github",
]
const FORMAT_LANGUAGE_MAP: {[key: string]: string} = {
csharp: "csharp",
go: "golang",
java: "java",
js: "javascript",
json: "json",
python: "python",
reproto: "reproto",
rust: "rust",
openapi: "yaml",
swift: "swift",
dart: "dart",
yaml: "yaml",
};
// modes in local_modules.
require("brace/mode/reproto.js")
// support searching ace editor.
// require('brace/ext/searchbox');
ace_languages.forEach((lang) => {
require(`brace/mode/${lang}`)
require(`brace/snippets/${lang}`)
})
themes.forEach((theme) => {
require(`brace/theme/${theme}`)
})
const DEFAULT_JSON = require("../static/default.json");
const DEFAULT_YAML = require("raw-loader!../static/default.yaml");
const COMMON_REPROTO: any = require("raw-loader!../static/common.reproto");
const COMMON2_REPROTO: any = require("raw-loader!../static/common2.reproto");
const IMPORT_REPROTO: any = require("raw-loader!../static/import.reproto");
const TYPE_REPROTO: any = require("raw-loader!../static/type.reproto");
const TUPLE_REPROTO: any = require("raw-loader!../static/tuple.reproto");
const INTERFACE_REPROTO: any = require("raw-loader!../static/interface.reproto");
const UNTAGGED_REPROTO: any = require("raw-loader!../static/untagged.reproto");
const SERVICE_REPROTO: any = require("raw-loader!../static/service.reproto");
const SERVICE_OPENAPI_REPROTO: any = require("raw-loader!../static/service.openapi.reproto");
const DEFAULT_NEW_FILE_REPROTO: any = require("raw-loader!../static/default-new.reproto");
const logo = require("../static/logo.256.png");
interface Dialog {
className: string;
message: any;
}
interface Compiled {
request: Derive;
result: DeriveResult;
}
interface Derive {
content: any;
root_name: string;
format: string;
output: string;
package_prefix: string;
}
interface Marker {
message: string;
row_start: number;
row_end: number;
col_start: number;
col_end: number;
}
interface DeriveFile {
path: string;
content: string;
}
interface DeriveResult {
files: DeriveFile[];
error?: string;
error_markers: Marker[];
info_markers: Marker[];
}
enum Format {
Json = "json",
Yaml = "yaml",
Reproto = "reproto",
}
enum Output {
Csharp = "csharp",
Go = "go",
Java = "java",
JavaScript = "js",
Json = "json",
OpenApi = "openapi",
Python = "python",
Reproto = "reproto",
Rust = "rust",
Swift = "swift",
Dart = "dart",
}
export interface MainProps {
}
interface ContentSet {
[key: string]: string;
}
interface File {
package: string;
version?: string;
content: string;
}
interface Settings {
java: JavaSettings;
python: PythonSettings;
csharp: CsharpSettings;
go: GoSettings;
rust: RustSettings;
openapi: OpenApiSettings;
swift: SwiftSettings;
dart: DartSettings;
}
export interface MainState {
contentSet: ContentSet;
// set of files
files: File[],
// current selected package.
fileIndex: number,
// If we are editing the file metadata right now.
file_editing_meta: boolean;
// Settings for various outputs.
settings: Settings;
format: Format;
output: Output;
root_name: string;
package_prefix: string;
settings_enabled: boolean,
// Error annotations (gutter markers) on input.
inputAnnotations: IAnnotation[];
// Error markers on input.
inputMarkers: IMarker[];
// Result of last compilation.
compiled?: Compiled;
error?: string;
derive?: (value: Derive) => DeriveResult;
}
export class Main extends React.Component<MainProps, MainState> {
constructor(props: MainProps) {
super(props);
this.state = {
contentSet: {
json: JSON.stringify(DEFAULT_JSON, null, 4),
yaml: DEFAULT_YAML.default,
},
files: [
{
package: "example.type",
content: TYPE_REPROTO.default,
},
{
package: "example.interface",
content: INTERFACE_REPROTO.default,
},
{
package: "example.untagged",
content: UNTAGGED_REPROTO.default,
},
{
package: "example.service",
content: SERVICE_REPROTO.default,
},
{
package: "example.service.openapi",
content: SERVICE_OPENAPI_REPROTO.default,
},
{
package: "example.tuple",
content: TUPLE_REPROTO.default,
},
{
package: "example.import",
content: IMPORT_REPROTO.default,
},
{
package: "example.common",
version: "1.0.0",
content: COMMON_REPROTO.default,
},
{
package: "example.common",
version: "2.0.0",
content: COMMON2_REPROTO.default,
},
],
fileIndex: 0,
file_editing_meta: false,
settings: {
java: {
jackson: true,
lombok: true,
},
python: {
requests: true,
},
rust: {
chrono: true,
reqwest: true,
},
openapi: {
json: false,
},
csharp: {
json_net: true,
},
go: {
encoding_json: true,
},
swift: {
codable: true,
simple: false,
},
dart: {
},
},
root_name: "Generated",
package_prefix: "reproto",
settings_enabled: false,
inputAnnotations: [],
inputMarkers: [],
format: Format.Reproto,
output: Output.Java,
};
}
componentWillUpdate(nextProps: MainProps, nextState: MainState) {
// Update URL if needed
const { format, output, fileIndex, files } = nextState;
let f = files[fileIndex];
let params = new URLSearchParams(location.search);
let update = false;
if (params.get("input") != format) {
params.set("input", format);
update = true;
}
if (params.get("output") != output) {
params.set("output", output);
update = true;
}
if (params.get("package") != f["package"]) {
params.set("package", f["package"]);
update = true;
}
if (update) {
window.history.replaceState({}, "", location.pathname + "?" + params);
}
}
componentDidMount() {
const params = new URLSearchParams(location.search)
const input = params.get("input")
const output = params.get("output")
const pkg = params.get("package")
this.setPackage(pkg);
this.setFormat(input);
this.setOutput(output);
import('../../pkg').then(mod => {
this.setState({derive: mod.derive}, () => this.recompile());
});
}
content(): string {
let {format} = this.state;
if (format == "reproto") {
return this.state.files[this.state.fileIndex].content;
} else {
return this.state.contentSet[format];
}
}
recompile() {
this.setState((state: MainState, props: MainProps) => {
let {
contentSet,
format,
output,
root_name,
package_prefix,
files,
fileIndex,
settings,
compiled,
derive,
} = state;
let content = this.content();
if (!derive) {
return {};
}
let compile = true;
let content_request;
if (format == "reproto") {
content_request = {type: "file_index", index: fileIndex};
} else {
content_request = {type: "content", content: content};
}
const request = {
content: content_request,
files: files,
root_name: root_name,
package_prefix: package_prefix,
format: format,
output: output,
settings: settings,
};
// no need to dispatch new request if it's identical to the old one...
if (compiled && deepEqual(compiled.request, request)) {
return {} as MainProps;
}
const result = derive(request) as DeriveResult;
const inputAnnotations: IAnnotation[] = [];
const inputMarkers: IMarker[] = [];
result.error_markers.forEach(m => {
inputAnnotations.push({
row: m.row_start,
column: m.col_start,
type: 'error',
text: m.message,
});
inputMarkers.push({
startRow: m.row_start,
startCol: m.col_start,
endRow: m.row_end,
endCol: m.col_end,
className: "error-marker",
type: "text",
});
});
result.info_markers.forEach(m => {
inputAnnotations.push({
row: m.row_start,
column: m.col_start,
type: 'info',
text: m.message,
});
inputMarkers.push({
startRow: m.row_start,
startCol: m.col_start,
endRow: m.row_end,
endCol: m.col_end,
className: "info-marker",
type: "text",
});
});
// Don't hide old result on errors.
if (result.error && compiled) {
result.files = compiled.result.files;
}
return {
compiled: {
request: request,
result: result,
},
inputAnnotations: inputAnnotations,
inputMarkers: inputMarkers,
};
});
}
setContent(format: Format, value: string) {
console.log("new content", value.length);
this.setState((state: MainState, props: MainProps) => {
let {fileIndex, files, contentSet} = this.state;
if (format == "reproto") {
let new_files = files.map((file, index) => {
if (index == fileIndex) {
let new_file = {...file};
new_file.content = value;
return new_file;
} else {
return file;
}
});
return {files: new_files} as MainState;
} else {
let new_content_set = {...contentSet};
new_content_set[format] = value;
return {contentSet: new_content_set} as MainState;
}
}, () => this.recompile());
}
setFile(fileIndex: number, cb: (file: File) => void) {
this.setState((state: MainState, props: MainProps) => {
let {files} = state;
let new_files = files.map((file, index) => {
if (index == fileIndex) {
let new_file = {...file};
cb(new_file);
return new_file;
} else {
return file;
}
});
return {files: new_files};
}, () => this.recompile());
}
setFileIndex(value: string) {
this.setState({
fileIndex: Number(value)
}, () => this.recompile());
}
setFormat(value: string) {
let format;
switch (value) {
case "yaml":
format = "yaml" as Format;
break;
case "reproto":
format = "reproto" as Format;
break;
case "json":
format = "json" as Format;
break;
default:
return;
}
this.setState({
format: format
}, () => this.recompile());
}
setPackage(pkg: string) {
this.setState((state) => {
const { files } = state;
const index = files.findIndex((f: File) => f["package"] == pkg);
if (index < 0) {
return {};
}
return {fileIndex: index} as MainState;
}, () => this.recompile());
}
setOutput(value: string) {
let output;
switch (value) {
case "reproto":
output = "reproto" as Output;
break;
case "java":
output = "java" as Output;
break;
case "csharp":
output = "csharp" as Output;
break;
case "go":
output = "go" as Output;
break;
case "swift":
output = "swift" as Output;
break;
case "dart":
output = "dart" as Output;
break;
case "python":
output = "python" as Output;
break;
case "rust":
output = "rust" as Output;
break;
case "openapi":
output = "openapi" as Output;
break;
case "js":
output = "js" as Output;
break;
case "json":
output = "json" as Output;
break;
default:
return;
}
this.setState({
output: output
}, () => this.recompile());
}
setRootName(root_name: string) {
this.setState({
root_name: root_name
}, () => this.recompile());
}
setPackagePrefix(package_prefix: string) {
this.setState({
package_prefix: package_prefix
}, () => this.recompile());
}
updateJava(cb: (settings: JavaSettings) => void) {
this.setState((state: MainState, props: MainProps) => {
let settings = {...state.settings};
settings.java = {...settings.java};
cb(settings.java);
return {settings: settings};
}, () => this.recompile());
}
updatePython(cb: (settings: PythonSettings) => void) {
this.setState((state: MainState, props: MainProps) => {
let settings = {...state.settings};
settings.python = {...settings.python};
cb(settings.python);
return {settings: settings};
}, () => this.recompile());
}
updateRust(cb: (settings: RustSettings) => void) {
this.setState((state: MainState, props: MainProps) => {
let settings = {...state.settings};
settings.rust = {...settings.rust};
cb(settings.rust);
return {settings: settings};
}, () => this.recompile());
}
updateOpenApi(cb: (settings: OpenApiSettings) => void) {
this.setState((state: MainState, props: MainProps) => {
let settings = {...state.settings};
settings.openapi = {...settings.openapi};
cb(settings.openapi);
return {settings: settings};
}, () => this.recompile());
}
updateSwift(cb: (settings: SwiftSettings) => void) {
this.setState((state: MainState, props: MainProps) => {
let settings = {...state.settings};
settings.swift = {...settings.swift};
cb(settings.swift);
return {settings: settings};
}, () => this.recompile());
}
updateDart(cb: (settings: DartSettings) => void) {
this.setState((state: MainState, props: MainProps) => {
let settings = {...state.settings};
settings.dart = {...settings.dart};
cb(settings.dart);
return {settings: settings};
}, () => this.recompile());
}
updateCsharp(cb: (settings: CsharpSettings) => void) {
this.setState((state: MainState, props: MainProps) => {
let settings = {...state.settings};
settings.csharp = {...settings.csharp};
cb(settings.csharp);
return {settings: settings};
}, () => this.recompile());
}
updateGo(cb: (settings: GoSettings) => void) {
this.setState((state: MainState, props: MainProps) => {
let settings = {...state.settings};
settings.go = {...settings.go};
cb(settings.go);
return {settings: settings};
}, () => this.recompile());
}
newFile() {
this.setState((state: MainState, props: MainProps) => {
let { files } = state;
files = [...files];
let fileIndex = files.length;
files.push({
content: DEFAULT_NEW_FILE_REPROTO,
package: "new"
});
return {
files: files,
fileIndex: fileIndex,
file_editing_meta: true,
};
}, () => this.recompile());
}
deleteFile() {
this.setState((state: MainState, props: MainProps) => {
let { files, fileIndex } = state;
return {
files: files.filter((_, i: number) => i != fileIndex),
fileIndex: 0,
file_editing_meta: false,
};
}, () => this.recompile());
}
render() {
let {
contentSet,
files,
fileIndex,
format,
output,
root_name,
package_prefix,
inputAnnotations,
inputMarkers,
settings,
compiled,
derive,
settings_enabled,
} = this.state;
let content = this.content();
let inputMode = FORMAT_LANGUAGE_MAP[format as string];
let outputMode = FORMAT_LANGUAGE_MAP[output as string];
if (!inputMode) {
throw Error(`Invalid input mode: ${format}`);
}
if (!outputMode) {
throw Error(`Invalid output mode: ${output}`);
}
let dialogs: Dialog[] = [];
let compiledFiles: DeriveFile[] = [];
var settingsForm = undefined;
var view = undefined;
if (format == "reproto") {
let {version, package: file_package} = files[fileIndex];
let {file_editing_meta} = this.state;
if (file_editing_meta) {
view = (
<div className="form-row">
<div className="input-group input-group-sm col mb-2">
<div className="input-group-prepend">
<label htmlFor="file-package" className="input-group-text lb-sm">File:</label>
</div>
<input
id="file-package"
type="text"
className="form-control form-control-sm"
placeholder="package"
onChange={e => {
let value = e.target.value;
this.setFile(fileIndex, file => file.package = value);
}}
value={file_package} />
</div>
<div className="col-md-4 mb-2">
<input
id="file-version"
type="text"
className="form-control form-control-sm"
placeholder="version"
onChange={e => {
let value = e.target.value;
this.setFile(fileIndex, file => {
if (value == "") {
delete file.version;
} else {
file.version = value;
}
});
}}
value={version || ""} />
</div>
<div className="col-auto mb-2">
<button
type="button"
title="Save file"
className="btn btn-primary btn-sm w-100"
onClick={() => {
this.setState({file_editing_meta: false});
}}>
<i className="fa fa-save"></i>
</button>
</div>
<div className="col-auto mb-2">
<button
type="button"
title="Delete file"
className="btn btn-danger btn-sm w-100"
onClick={() => {
this.deleteFile();
}}>
<i className="fa fa-trash"></i>
</button>
</div>
</div>
);
} else {
view = (
<div className="form-row">
<div className="input-group input-group-sm col mb-2">
<div className="input-group-prepend">
<label htmlFor="file-package" className="input-group-text lb-sm">File:</label>
</div>
<select
id="file-package"
value={fileIndex}
className="form-control"
onChange={e => this.setFileIndex(e.target.value)}>
{ files.map((f, index) => {
return <option key={index} value={index}>{f.package} {f.version || ""}</option>;
}) }
</select>
</div>
<div className="col-auto mb-2">
<button
type="button"
title="Edit file name and version"
className="btn btn-info btn-sm w-100"
onClick={() => {
this.setState({file_editing_meta: true});
}}>
<i className="fa fa-edit"></i>
</button>
</div>
<div className="col-auto mb-2">
<button
type="button"
title="Add a new file"
className="btn btn-success btn-sm w-100"
onClick={() => {
this.newFile();
}}>
<i className="fa fa-plus"></i>
</button>
</div>
<div className="col-auto mb-2">
<button
type="button"
title="Delete file"
className="btn btn-danger btn-sm w-100"
onClick={() => {
this.deleteFile();
}}>
<i className="fa fa-trash"></i>
</button>
</div>
</div>
);
}
}
if (!derive) {
dialogs.push({
className: "alert alert-info",
message: (
<div className="clearfix">
<i className="fa fa-spinner fa-spin" style={{display: "inline-block", float: "left", fontSize: "150%"}} />
<div className="ml-2" style={{display: "inline-block", float: "left"}}>
<span>
Loading <a href="https://github.com/reproto/reproto/blob/master/eval/reproto_wasm.rs" target="_blank">reproto wasm</a>
</span>
<br />
<small>Did you know that wasm <a href="https://hacks.mozilla.org/2018/01/making-webassembly-even-faster-firefoxs-new-streaming-and-tiering-compiler/">loads <em>faster</em> in Firefox</a>?</small>
</div>
</div>
),
});
}
if (format) {
switch (output) {
case "java":
settingsForm = <JavaSettingsForm settings={settings.java}
onJackson={update => this.updateJava(java => java.jackson = update)}
onLombok={update => this.updateJava(java => java.lombok = update)}
/>;
break;
case "python":
settingsForm = <PythonSettingsForm settings={settings.python}
onRequests={update => this.updatePython(python => python.requests = update)}
/>;
break;
case "rust":
settingsForm = <RustSettingsForm settings={settings.rust}
onChrono={update => this.updateRust(rust => rust.chrono = update)}
onReqwest={update => this.updateRust(rust => rust.reqwest = update)}
/>;
break;
case "openapi":
settingsForm = <OpenApiSettingsForm settings={settings.openapi}
onJson={update => this.updateOpenApi(openapi => openapi.json = update)}
/>;
break;
case "csharp":
settingsForm = <CsharpSettingsForm settings={settings.csharp}
onJsonNet={update => this.updateCsharp(csharp => csharp.json_net = update)}
/>;
break;
case "go":
settingsForm = <GoSettingsForm settings={settings.go}
onEncodingJson={update => this.updateGo(go => go.encoding_json = update)}
/>;
break;
case "swift":
settingsForm = <SwiftSettingsForm settings={settings.swift}
onCodable={update => this.updateSwift(swift => swift.codable = update)}
onSimple={update => this.updateSwift(swift => swift.simple = update)}
/>;
break;
case "dart":
settingsForm = <DartSettingsForm settings={settings.dart}
/>;
break;
default:
break;
}
}
if (compiled) {
let { error, error_markers, files } = compiled.result;
if (files) {
compiledFiles = files;
}
if (error) {
if (error_markers.length == 0) {
dialogs.push({
className: "alert alert-danger",
message: String(error),
});
}
error_markers.forEach(m => {
dialogs.push({
className: "alert alert-danger",
message: (
<small>{m.row_start + 1}:{m.col_start}: {m.message}</small>
),
});
});
}
}
return (
<div className="box">
<div className="box-row header">
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="https://github.com/reproto">
<img src={logo} width={32} height={32} title="reproto" />
</a>
<a className="navbar-brand mr-auto" href="#">reproto eval</a>
<ul className="navbar-nav">
<li className="nav-item">
<a className="nav-link" href="https://github.com/reproto/reproto/tree/master/doc">
<i className="fa fa-book"></i>
docs
</a>
</li>
<li className="nav-item">
<a className="nav-link" href="https://github.com/reproto/reproto">
<i className="fa fa-github"></i>
reproto/reproto
</a>
</li>
</ul>
</nav>
<div className="container-fluid">
<div className="row mb-2 mt-2">
<div className="col-6 col-xl-5 input">
<form>
<div className="input-group input-group-sm mb-2">
<div className="input-group-prepend">
<label htmlFor="output" className="input-group-text lb-sm">Input:</label>
</div>
<select
id="format"
className="form-control"
value={format}
onChange={e => this.setFormat(e.target.value)}>
<option value="reproto">Reproto</option>
<option value="json">JSON (Derive)</option>
<option value="yaml">YAML (Derive)</option>
</select>
</div>
{view}
</form>
</div>
<div className="col">
<form>
<div className="form-row">
<div className="input-group input-group-sm col mb-2">
<div className="input-group-prepend">
<label htmlFor="output" className="input-group-text lb-sm">Output:</label>
</div>
<select
id="output"
className="form-control"
value={output}
onChange={e => this.setOutput(e.target.value)}>
<option value="csharp">C#</option>
<option value="go">Go</option>
<option value="java">Java</option>
<option value="js">JavaScript</option>
<option value="json">JSON (RpIR)</option>
<option value="python">Python</option>
<option value="reproto">Reproto</option>
<option value="rust">Rust</option>
<option value="openapi">OpenAPI</option>
<option value="swift">Swift</option>
<option value="dart">Dart</option>
</select>
</div>
</div>
<div className="form-row">
<div className="input-group input-group-sm col-md-4 mb-2">
<div className="input-group-prepend">
<label htmlFor="package-prefix" className="input-group-text lb-sm">Package:</label>
</div>
<input
id="package-prefix"
type="text"
className="form-control form-control-sm"
value={package_prefix}
onChange={e => this.setPackagePrefix(e.target.value)} />
</div>
{format != "reproto" ?
<div className="input-group input-group-sm col-md-4 mb-2">
<div className="input-group-prepend">
<label htmlFor="root-name" className="input-group-text lb-sm">Generated Name:</label>
</div>
<input
id="root-name"
type="text"
className="form-control form-control-sm"
value={root_name}
onChange={e => this.setRootName(e.target.value)} />
</div> : undefined}
<div className="input-group-sm col-auto mb-2">
<button className="btn btn-sm btn-light"
type="button"
title="Show Settings"
style={{display: settings_enabled ? 'none' : null }}
disabled={!settingsForm}
onClick={() => {
this.setState({settings_enabled: true});
}}>
<i className="fa fa-cog"></i>
Show
</button>
<button className="btn btn-sm btn-dark"
type="button"
title="Hide Settings"
style={{display: settings_enabled ? null : 'none' }}
disabled={!settingsForm}
onClick={() => {
this.setState({settings_enabled: false});
}}>
<i className="fa fa-cog"></i>
Hide
</button>
</div>
</div>
</form>
{settings_enabled ? settingsForm : undefined}
</div>
</div>
</div>
</div>
<div className="box-row content container-fluid">
<div className="row editors">
<div className="col-6 col-xl-5 input">
<AceEditor
tabSize={2}
showGutter={true}
mode={inputMode}
theme="monokai"
width="100%"
height="100%"
value={content}
annotations={inputAnnotations}
markers={inputMarkers}
onChange={value => this.setContent(format, value)}
/>
</div>
<div className="col output">
{dialogs.length > 0 ? (
<div className="dialogs row mt-2">
<div className="col">
{dialogs.map((d, key) => (
<div key={key} className={d.className}>
{d.message}
</div>
))}
</div>
</div>
) : undefined}
{compiledFiles.map((f, index) => {
return (
<div key={index} className="output-file">
<div className="title">
<i className="title-icon fa fa-file"></i>
<span className="title-text">{f.path}</span>
</div>
<OutputEditor mode={outputMode as string} value={f.content} />
</div>
);
})}
</div>
</div>
</div>
</div>
);
}
} | the_stack |
namespace egret.web {
//测试开关,打开会截住老的字体渲染
export const textAtlasRenderEnable: boolean = false;
//测试对象, 先不用singleton的,后续整理代码,就new一个,放在全局的context上做成员变量
export let __textAtlasRender__: TextAtlasRender = null;
//不想改TextNode的代码了,先用这种方式实现,以后稳了再改
export const property_drawLabel: string = 'DrawLabel';
//开启这个,用textAtlas渲染出来的,都是红字,而且加黑框
const textAtlasDebug: boolean = false;
//画一行
export class DrawLabel extends HashObject {
//池子,防止反复创建
private static pool: DrawLabel[] = [];
//记录初始位置
public anchorX: number = 0;
public anchorY: number = 0;
//要画的字块
public textBlocks: TextBlock[] = [];
//清除数据,回池
private clear(): void {
this.anchorX = 0;
this.anchorY = 0;
this.textBlocks.length = 0; //这个没事,实体在book里面存着
}
//池子创建
public static create(): DrawLabel {
const pool = DrawLabel.pool;
if (pool.length === 0) {
pool.push(new DrawLabel);
}
return pool.pop();
}
//回池
public static back(drawLabel: DrawLabel, checkRepeat: boolean): void {
if (!drawLabel) {
return;
}
const pool = DrawLabel.pool;
if (checkRepeat && pool.indexOf(drawLabel) >= 0) {
console.error('DrawLabel.back repeat');
return;
}
drawLabel.clear();
pool.push(drawLabel);
}
}
//记录样式的
class StyleInfo extends HashObject {
//各种记录信息
public readonly textColor: number;
public readonly strokeColor: number;
public readonly size: number;
public readonly stroke: number;
public readonly bold: boolean;
public readonly italic: boolean;
public readonly fontFamily: string;
public readonly font: string;
public readonly format: sys.TextFormat = null;
public readonly description: string;
//
constructor(textNode: sys.TextNode, format: sys.TextFormat) {
super();
//debug强制红色
let saveTextColorForDebug = 0;
if (textAtlasDebug) {
saveTextColorForDebug = textNode.textColor;
textNode.textColor = 0xff0000;
}
//存上
this.textColor = textNode.textColor;
this.strokeColor = textNode.strokeColor;
this.size = textNode.size;
this.stroke = textNode.stroke;
this.bold = textNode.bold;
this.italic = textNode.italic;
this.fontFamily = textNode.fontFamily;
this.format = format;
this.font = getFontString(textNode, this.format);
//描述用于生成hashcode
const textColor = (!format.textColor ? textNode.textColor : format.textColor);
const strokeColor = (!format.strokeColor ? textNode.strokeColor : format.strokeColor);
const stroke = (!format.stroke ? textNode.stroke : format.stroke);
const size = (!format.size ? textNode.size : format.size);
//
this.description = '' + this.font + '-' + size;
this.description += '-' + toColorString(textColor);
this.description += '-' + toColorString(strokeColor);
if (stroke) {
this.description += '-' + stroke * 2;
}
//还原
if (textAtlasDebug) {
textNode.textColor = saveTextColorForDebug;
}
}
}
//测量字体和绘制的
class CharImageRender extends HashObject {
//要渲染的字符串
public char: string = '';
//StyleInfo
public styleInfo: StyleInfo = null;
//生成hashcode的字符串
public hashCodeString: string = '';
//字母:style设置行程唯一值
public charWithStyleHashCode: number = 0;
//测量实际的size
public measureWidth: number = 0;
public measureHeight: number = 0;
//边缘放大之后的偏移
public canvasWidthOffset: number = 0;
public canvasHeightOffset: number = 0;
//描边的记录
public stroke2: number = 0;
//针对中文的加速查找
private static readonly chineseCharactersRegExp: RegExp = new RegExp("^[\u4E00-\u9FA5]$");
private static readonly chineseCharacterMeasureFastMap: { [index: string]: number } = {};
public reset(char: string, styleKey: StyleInfo): CharImageRender {
this.char = char;
this.styleInfo = styleKey;
this.hashCodeString = char + ':' + styleKey.description;
this.charWithStyleHashCode = NumberUtils.convertStringToHashCode(this.hashCodeString);
this.canvasWidthOffset = 0;
this.canvasHeightOffset = 0;
this.stroke2 = 0;
return this;
}
public measureAndDraw(targetCanvas: HTMLCanvasElement): void {
const canvas = targetCanvas;
if (!canvas) {
return;
}
//读取设置
const text = this.char;
const format: sys.TextFormat = this.styleInfo.format;
const textColor = (!format.textColor ? this.styleInfo.textColor : format.textColor);
const strokeColor = (!format.strokeColor ? this.styleInfo.strokeColor : format.strokeColor);
const stroke = (!format.stroke ? this.styleInfo.stroke : format.stroke);
const size = (!format.size ? this.styleInfo.size : format.size);
//开始测量---------------------------------------
this.measureWidth = this.measure(text, this.styleInfo, size);
this.measureHeight = size;//this.styleInfo.size;
//调整 参考TextField: $getRenderBounds(): Rectangle {
let canvasWidth = this.measureWidth;
let canvasHeight = this.measureHeight;
const _strokeDouble = stroke * 2;
if (_strokeDouble > 0) {
canvasWidth += _strokeDouble * 2;
canvasHeight += _strokeDouble * 2;
}
this.stroke2 = _strokeDouble;
//赋值
canvas.width = canvasWidth = Math.ceil(canvasWidth) + 2 * 2;
canvas.height = canvasHeight = Math.ceil(canvasHeight) + 2 * 2;
this.canvasWidthOffset = (canvas.width - this.measureWidth) / 2;
this.canvasHeightOffset = (canvas.height - this.measureHeight) / 2;
//全部保留numberOfPrecision位小数
const numberOfPrecision = 3;
const precision = Math.pow(10, numberOfPrecision);
this.canvasWidthOffset = Math.floor(this.canvasWidthOffset * precision) / precision;
this.canvasHeightOffset = Math.floor(this.canvasHeightOffset * precision) / precision;
//再开始绘制---------------------------------------
const context = egret.sys.getContext2d(canvas);
context.save();
context.textAlign = 'center';
context.textBaseline = 'middle';
context.lineJoin = 'round';
context.font = this.styleInfo.font;
context.fillStyle = toColorString(textColor);
context.strokeStyle = toColorString(strokeColor);
context.clearRect(0, 0, canvas.width, canvas.height);
if (stroke) {
context.lineWidth = stroke * 2;
context.strokeText(text, canvas.width / 2, canvas.height / 2);
}
context.fillText(text, canvas.width / 2, canvas.height / 2);
context.restore();
}
private measure(text: string, styleKey: StyleInfo, textFlowSize: number): number {
const isChinese = CharImageRender.chineseCharactersRegExp.test(text);
if (isChinese) {
if (CharImageRender.chineseCharacterMeasureFastMap[styleKey.font]) {
return CharImageRender.chineseCharacterMeasureFastMap[styleKey.font];
}
}
const measureTextWidth = egret.sys.measureText(text, styleKey.fontFamily, textFlowSize || styleKey.size, styleKey.bold, styleKey.italic);
if (isChinese) {
CharImageRender.chineseCharacterMeasureFastMap[styleKey.font] = measureTextWidth;
}
return measureTextWidth;
}
}
//对外的类
export class TextAtlasRender extends HashObject {
private readonly book: Book = null;
private readonly charImageRender: CharImageRender = new CharImageRender;
private readonly textBlockMap: { [index: number]: TextBlock } = {};
private _canvas: HTMLCanvasElement = null;
private readonly textAtlasTextureCache: WebGLTexture[] = [];
private readonly webglRenderContext: WebGLRenderContext = null;
//
constructor(webglRenderContext: WebGLRenderContext, maxSize: number, border: number) {
super();
this.webglRenderContext = webglRenderContext;
this.book = new Book(maxSize, border);
}
//分析textNode,把数据提取出来,然后给textNode挂上渲染的信息
public static analysisTextNodeAndFlushDrawLabel(textNode: sys.TextNode): void {
if (!textNode) {
return;
}
if (!__textAtlasRender__) {
//创建,后续会转移给WebGLRenderContext
const webglcontext = egret.web.WebGLRenderContext.getInstance(0, 0);
//初期先512,因为不会大规模batch, 老项目最好不要直接使用这个,少数几个总变内容的TextField可以用,所以先不用$maxTextureSize
__textAtlasRender__ = new TextAtlasRender(webglcontext, textAtlasDebug ? 512 : 512/*webglcontext.$maxTextureSize*/, textAtlasDebug ? 12 : 1);
}
//清除命令
textNode[property_drawLabel] = textNode[property_drawLabel] || [];
let drawLabels = textNode[property_drawLabel] as DrawLabel[];
for (const drawLabel of drawLabels) {
//还回去
DrawLabel.back(drawLabel, false);
}
drawLabels.length = 0;
//重新装填
const offset = 4;
const drawData = textNode.drawData;
let anchorX = 0;
let anchorY = 0;
let labelString = '';
let labelFormat: sys.TextFormat = {};
let resultAsRenderTextBlocks: TextBlock[] = [];
for (let i = 0, length = drawData.length; i < length; i += offset) {
anchorX = drawData[i + 0] as number;
anchorY = drawData[i + 1] as number;
labelString = drawData[i + 2] as string;
labelFormat = drawData[i + 3] as sys.TextFormat || {};
resultAsRenderTextBlocks.length = 0;
//提取数据
__textAtlasRender__.convertLabelStringToTextAtlas(labelString, new StyleInfo(textNode, labelFormat), resultAsRenderTextBlocks);
//pool创建 + 添加命令
const drawLabel = DrawLabel.create();
drawLabel.anchorX = anchorX;
drawLabel.anchorY = anchorY;
drawLabel.textBlocks = [].concat(resultAsRenderTextBlocks);
drawLabels.push(drawLabel);
}
}
//字符串转化成为TextBlock
private convertLabelStringToTextAtlas(labelstring: string, styleKey: StyleInfo, resultAsRenderTextBlocks: TextBlock[]): void {
const canvas = this.canvas;
const charImageRender = this.charImageRender;
const textBlockMap = this.textBlockMap;
for (const char of labelstring) {
//不反复创建
charImageRender.reset(char, styleKey);
if (textBlockMap[charImageRender.charWithStyleHashCode]) {
//检查重复
resultAsRenderTextBlocks.push(textBlockMap[charImageRender.charWithStyleHashCode]);
continue;
}
//画到到canvas
charImageRender.measureAndDraw(canvas);
//创建新的文字块
const txtBlock = this.book.createTextBlock(char,
canvas.width, canvas.height,
charImageRender.measureWidth, charImageRender.measureHeight,
charImageRender.canvasWidthOffset, charImageRender.canvasHeightOffset,
charImageRender.stroke2);
if (!txtBlock) {
continue;
}
//需要绘制
resultAsRenderTextBlocks.push(txtBlock);
//记录快速查找
textBlockMap[charImageRender.charWithStyleHashCode] = txtBlock;
//生成纹理
const page = txtBlock.page;
if (!page.webGLTexture) {
page.webGLTexture = this.createTextTextureAtlas(page.pageWidth, page.pageHeight, textAtlasDebug);
}
const gl = this.webglRenderContext.context;
page.webGLTexture[glContext] = gl;
gl.bindTexture(gl.TEXTURE_2D, page.webGLTexture);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
page.webGLTexture[UNPACK_PREMULTIPLY_ALPHA_WEBGL] = true;
gl.texSubImage2D(gl.TEXTURE_2D, 0, txtBlock.subImageOffsetX, txtBlock.subImageOffsetY, gl.RGBA, gl.UNSIGNED_BYTE, canvas);
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
}
}
//给一个page创建一个纹理
private createTextTextureAtlas(width: number, height: number, debug: boolean): WebGLTexture {
let texture: WebGLTexture = null;
if (debug) {
//做一个黑底子的,方便调试代码
const canvas = egret.sys.createCanvas(width, width);
const context = egret.sys.getContext2d(canvas);
context.fillStyle = 'black';
context.fillRect(0, 0, width, width);
texture = egret.sys.createTexture(this.webglRenderContext, canvas);
}
else {
//真的
texture = egret.sys._createTexture(this.webglRenderContext, width, height, null);
}
if (texture) {
//存起来,未来可以删除,或者查看
this.textAtlasTextureCache.push(texture);
}
return texture;
}
//给CharImageRender用的canvas
private get canvas(): HTMLCanvasElement {
if (!this._canvas) {
//就用默认体积24
this._canvas = egret.sys.createCanvas(24, 24);
}
return this._canvas;
}
}
} | the_stack |
import { getColorByChannelIndex } from "./constants/colors";
function clamp(val: number, cmin: number, cmax: number): number {
return Math.min(Math.max(cmin, val), cmax);
}
function controlPointToRGBA(controlPoint) {
return [controlPoint.color[0], controlPoint.color[1], controlPoint.color[2], Math.floor(controlPoint.opacity * 255)];
}
function lerp(xmin, xmax, a) {
return a * (xmax - xmin) + xmin;
}
const LUT_ENTRIES = 256;
const LUT_ARRAY_LENGTH = LUT_ENTRIES * 4;
/**
* @typedef {Object} ControlPoint Used for the TF (transfer function) editor GUI.
* Need to be converted to LUT for rendering.
* @property {number} x The X Coordinate
* @property {number} opacity The Opacity, from 0 to 1
* @property {Array.<number>} color The Color, 3 numbers from 0-255 for r,g,b
*/
/**
* @typedef {Object} Lut Used for rendering.
* @property {Array.<number>} lut LUT_ARRAY_LENGTH element lookup table as array
* (maps scalar intensity to a rgb color plus alpha, with each value from 0-255)
* @property {Array.<ControlPoint>} controlPoints
*/
type ControlPoint = {
x: number;
opacity: number;
color: [number, number, number];
};
type Lut = {
lut: Uint8Array;
controlPoints: ControlPoint[];
};
/**
* Builds a histogram with 256 bins from a data array. Assume data is 8 bit single channel grayscale.
* @class
* @param {Array.<number>} data
*/
export default class Histogram {
private bins: Uint32Array;
private dataMin: number;
private dataMax: number;
private maxBin: number;
private nonzeroPixelCount: number;
constructor(data: Uint8Array) {
// no more than 2^32 pixels of any one intensity in the data!?!?!
this.bins = new Uint32Array(256);
this.bins.fill(0);
this.dataMin = 255;
this.dataMax = 0;
this.maxBin = 0;
// build up the histogram
for (let i = 0; i < data.length; ++i) {
this.bins[data[i]]++;
}
// track the first and last nonzero bins with at least 1 sample
for (let i = 1; i < this.bins.length; i++) {
if (this.bins[i] > 0) {
this.dataMin = i;
break;
}
}
for (let i = this.bins.length - 1; i >= 1; i--) {
if (this.bins[i] > 0) {
this.dataMax = i;
break;
}
}
// total number of pixels minus the number of zero pixels
this.nonzeroPixelCount = data.length - this.bins[0];
// get the bin with the most frequently occurring NONZERO value
this.maxBin = 1;
let max = this.bins[1];
for (let i = 1; i < this.bins.length; i++) {
if (this.bins[i] > max) {
this.maxBin = i;
max = this.bins[i];
}
}
}
/**
* Return the min data value
* @return {number}
*/
getMin(): number {
return this.dataMin;
}
/**
* Return the max data value
* @return {number}
*/
getMax(): number {
return this.dataMax;
}
/* eslint-disable @typescript-eslint/naming-convention */
/**
* Generate a Window/level lookup table
* @return {Lut}
* @param {number} wnd in 0..1 range
* @param {number} lvl in 0..1 range
*/
lutGenerator_windowLevel(wnd: number, lvl: number): Lut {
// simple linear mapping for actual range
const b = lvl - wnd * 0.5;
const e = lvl + wnd * 0.5;
return this.lutGenerator_minMax(b * 255, e * 255);
}
/**
* Generate a piecewise linear lookup table that ramps up from 0 to 1 over the b to e domain.
* If e === b, then we use a step function with f(b) = 0 and f(b + 1) = 1
* |
* 1| +---------+-----
* | /
* | /
* | /
* | /
* | /
* 0+=========+---------------+-----
* 0 b e 255
* @return {Lut}
* @param {number} b
* @param {number} e
*/
lutGenerator_minMax(b: number, e: number): Lut {
if (e < b) {
// swap
const tmp = e;
e = b;
b = tmp;
}
const lut = new Uint8Array(LUT_ARRAY_LENGTH);
for (let x = 0; x < lut.length / 4; ++x) {
lut[x * 4 + 0] = 255;
lut[x * 4 + 1] = 255;
lut[x * 4 + 2] = 255;
if (x > e) {
lut[x * 4 + 3] = 255;
} else if (x <= b) {
lut[x * 4 + 3] = 0;
} else {
if (e === b) {
lut[x * 4 + 3] = 255;
} else {
const a = (x - b) / (e - b);
lut[x * 4 + 3] = lerp(0, 255, a);
}
}
}
// Edge case: b and e are both out of bounds
if (b < 0 && e < 0) {
return {
lut: lut,
controlPoints: [
{ x: 0, opacity: 1, color: [255, 255, 255] },
{ x: 255, opacity: 1, color: [255, 255, 255] },
],
};
}
if (b >= 255 && e >= 255) {
return {
lut: lut,
controlPoints: [
{ x: 0, opacity: 0, color: [255, 255, 255] },
{ x: 255, opacity: 0, color: [255, 255, 255] },
],
};
}
// Generate 2 to 4 control points for a minMax LUT, from left to right
const controlPoints: ControlPoint[] = [];
// Add starting point at x = 0
let startVal = 0;
if (b < 0) {
startVal = -b / (e - b);
}
controlPoints.push({ x: 0, opacity: startVal, color: [255, 255, 255] });
// If b > 0, add another point at (b, 0)
if (b > 0) {
controlPoints.push({ x: b, opacity: 0, color: [255, 255, 255] });
}
// If e < 255, Add another point at (e, 1)
if (e < 255) {
if (e === b) {
// Use b + 0.5 as x value instead of e to create a near-vertical ramp
controlPoints.push({ x: b + 0.5, opacity: 1, color: [255, 255, 255] });
} else {
controlPoints.push({ x: e, opacity: 1, color: [255, 255, 255] });
}
}
// Add ending point at x = 255
let endVal = 1;
if (e > 255) {
endVal = (255 - b) / (e - b);
}
controlPoints.push({ x: 255, opacity: endVal, color: [255, 255, 255] });
return {
lut: lut,
controlPoints: controlPoints,
};
}
/**
* Generate a straight 0-1 linear identity lookup table
* @return {Lut}
*/
lutGenerator_fullRange(): Lut {
const lut = new Uint8Array(LUT_ARRAY_LENGTH);
// simple linear mapping for actual range
for (let x = 0; x < lut.length / 4; ++x) {
lut[x * 4 + 0] = 255;
lut[x * 4 + 1] = 255;
lut[x * 4 + 2] = 255;
lut[x * 4 + 3] = x;
}
return {
lut: lut,
controlPoints: [
{ x: 0, opacity: 0, color: [255, 255, 255] },
{ x: 255, opacity: 1, color: [255, 255, 255] },
],
};
}
/**
* Generate a lookup table over the min to max range of the data values
* @return {Lut}
*/
lutGenerator_dataRange(): Lut {
// simple linear mapping for actual range
const b = this.dataMin;
const e = this.dataMax;
return this.lutGenerator_minMax(b, e);
}
/**
* Generate a lookup table with a different color per intensity value
* @return {Lut}
*/
lutGenerator_labelColors(): Lut {
const lut = new Uint8Array(LUT_ARRAY_LENGTH).fill(0);
// TODO specify type for control point
const controlPoints: ControlPoint[] = [];
controlPoints.push({ x: 0, opacity: 0, color: [0, 0, 0] });
let lastr = 0;
let lastg = 0;
let lastb = 0;
let lasta = 0;
let r = 0;
let g = 0;
let b = 0;
let a = 0;
// assumes exactly one bin per intensity value?
// skip zero!!!
for (let i = 1; i < this.bins.length; ++i) {
if (this.bins[i] > 0) {
const rgb = getColorByChannelIndex(i);
lut[i * 4 + 0] = rgb[0];
lut[i * 4 + 1] = rgb[1];
lut[i * 4 + 2] = rgb[2];
lut[i * 4 + 3] = 255;
r = rgb[0];
g = rgb[1];
b = rgb[2];
a = 1;
} else {
// add a zero control point?
r = 0;
g = 0;
b = 0;
a = 0;
}
// if current control point is same as last one don't add it
if (r !== lastr || g !== lastg || b !== lastb || a !== lasta) {
if (lasta === 0) {
controlPoints.push({ x: i - 0.5, opacity: lasta, color: [lastr, lastg, lastb] });
}
controlPoints.push({ x: i, opacity: a, color: [r, g, b] });
lastr = r;
lastg = g;
lastb = b;
lasta = a;
}
}
return {
lut: lut,
controlPoints: controlPoints,
};
}
/**
* Find the bin that contains the percentage of pixels below it
* @return {number}
* @param {number} pct
*/
findBinOfPercentile(pct: number): number {
const pixcount = this.nonzeroPixelCount + this.bins[0];
const limit = pixcount * pct;
let i = 0;
let count = 0;
for (i = 0; i < this.bins.length; ++i) {
count += this.bins[i];
if (count > limit) {
break;
}
}
return i;
}
/**
* Generate a lookup table based on histogram percentiles
* @return {Lut}
* @param {number} pmin
* @param {number} pmax
*/
lutGenerator_percentiles(pmin: number, pmax: number): Lut {
// e.g. 0.50, 0.983 starts from 50th percentile bucket and ends at 98.3 percentile bucket.
const hmin = this.findBinOfPercentile(pmin);
const hmax = this.findBinOfPercentile(pmax);
return this.lutGenerator_minMax(hmin, hmax);
}
/**
* Generate a 10% / 90% lookup table
* @return {Lut}
*/
lutGenerator_bestFit(): Lut {
const pixcount = this.nonzeroPixelCount;
//const pixcount = this.imgData.data.length;
const limit = pixcount / 10;
let i = 0;
let count = 0;
for (i = 1; i < this.bins.length; ++i) {
count += this.bins[i];
if (count > limit) {
break;
}
}
const hmin = i;
count = 0;
for (i = this.bins.length - 1; i >= 1; --i) {
count += this.bins[i];
if (count > limit) {
break;
}
}
const hmax = i;
return this.lutGenerator_minMax(hmin, hmax);
}
/**
* Generate a lookup table attempting to replicate ImageJ's "Auto" button
* @return {Lut}
*/
lutGenerator_auto2(): Lut {
const AUTO_THRESHOLD = 5000;
const pixcount = this.nonzeroPixelCount;
// const pixcount = this.imgData.data.length;
const limit = pixcount / 10;
const threshold = pixcount / AUTO_THRESHOLD;
// this will skip the "zero" bin which contains pixels of zero intensity.
let hmin = this.bins.length - 1;
let hmax = 1;
for (let i = 1; i < this.bins.length; ++i) {
if (this.bins[i] > threshold && this.bins[i] <= limit) {
hmin = i;
break;
}
}
for (let i = this.bins.length - 1; i >= 1; --i) {
if (this.bins[i] > threshold && this.bins[i] <= limit) {
hmax = i;
break;
}
}
if (hmax < hmin) {
// just reset to whole range in this case.
return this.lutGenerator_fullRange();
} else {
return this.lutGenerator_minMax(hmin, hmax);
}
}
/**
* Generate a lookup table using a percentile of the most commonly occurring value
* @return {Lut}
*/
lutGenerator_auto(): Lut {
// simple linear mapping cutting elements with small appearence
// get 10% threshold
const PERCENTAGE = 0.1;
const th = Math.floor(this.bins[this.maxBin] * PERCENTAGE);
let b = 0;
let e = this.bins.length - 1;
for (let x = 1; x < this.bins.length; ++x) {
if (this.bins[x] > th) {
b = x;
break;
}
}
for (let x = this.bins.length - 1; x >= 1; --x) {
if (this.bins[x] > th) {
e = x;
break;
}
}
return this.lutGenerator_minMax(b, e);
}
/**
* Generate an "equalized" lookup table
* @return {Lut}
*/
lutGenerator_equalize(): Lut {
const map: number[] = [];
for (let i = 0; i < this.bins.length; ++i) {
map[i] = 0;
}
// summed area table?
map[0] = this.bins[0];
for (let i = 1; i < this.bins.length; ++i) {
map[i] = map[i - 1] + this.bins[i];
}
const div = map[map.length - 1] - map[0];
if (div > 0) {
const lut = new Uint8Array(LUT_ARRAY_LENGTH);
// compute lut and track control points for the piecewise linear sections
const lutControlPoints: ControlPoint[] = [{ x: 0, opacity: 0, color: [255, 255, 255] }];
lut[0] = 255;
lut[1] = 255;
lut[2] = 255;
lut[3] = 0;
let slope = 0;
let lastSlope = 0;
let opacity = 0;
let lastOpacity = 0;
for (let i = 1; i < lut.length / 4; ++i) {
lut[i * 4 + 0] = 255;
lut[i * 4 + 1] = 255;
lut[i * 4 + 2] = 255;
lastOpacity = opacity;
opacity = clamp(Math.round(255 * (map[i] - map[0])), 0, 255);
lut[i * 4 + 3] = opacity;
slope = opacity - lastOpacity;
// if map[i]-map[i-1] is the same as map[i+1]-map[i] then we are in a linear segment and do not need a new control point
if (slope != lastSlope) {
lutControlPoints.push({ x: i - 1, opacity: lastOpacity / 255.0, color: [255, 255, 255] });
lastSlope = slope;
}
}
lutControlPoints.push({ x: 255, opacity: 1, color: [255, 255, 255] });
return {
lut: lut,
controlPoints: lutControlPoints,
};
} else {
// just reset to whole range in this case...?
return this.lutGenerator_fullRange();
}
}
// @param {Object[]} controlPoints - array of {x:number 0..255, opacity:number 0..1, color:array of 3 numbers 0..255}
// @return {Uint8Array} array of length 256*4 representing the rgba values of the gradient
lutGenerator_fromControlPoints(controlPoints: ControlPoint[]): Lut {
const lut = new Uint8Array(LUT_ARRAY_LENGTH).fill(0);
if (controlPoints.length === 0) {
return { lut: lut, controlPoints: controlPoints };
}
// ensure they are sorted in ascending order of x
controlPoints.sort((a, b) => a.x - b.x);
// special case only one control point.
if (controlPoints.length === 1) {
const rgba = controlPointToRGBA(controlPoints[0]);
// copy val from x to 255.
for (let x = controlPoints[0].x; x < 256; ++x) {
lut[x * 4 + 0] = rgba[0];
lut[x * 4 + 1] = rgba[1];
lut[x * 4 + 2] = rgba[2];
lut[x * 4 + 3] = rgba[3];
}
return { lut: lut, controlPoints: controlPoints };
}
let c0 = controlPoints[0];
let c1 = controlPoints[1];
let color0 = controlPointToRGBA(c0);
let color1 = controlPointToRGBA(c1);
let lastIndex = 1;
let a = 0;
// if the first control point is after 0, act like there are 0s going all the way up to it.
// or lerp up to the first point?
for (let x = c0.x; x < 256; ++x) {
while (x > c1.x) {
// advance control points
c0 = c1;
color0 = color1;
lastIndex++;
if (lastIndex >= controlPoints.length) {
// if the last control point is before 255, then we want to continue its value all the way to 255.
c1 = { x: 255, color: c1.color, opacity: c1.opacity };
} else {
c1 = controlPoints[lastIndex];
}
color1 = controlPointToRGBA(c1);
}
if (c1.x === c0.x) {
// use c1
a = 1.0;
} else {
a = (x - c0.x) / (c1.x - c0.x);
}
// lerp the colors
lut[x * 4 + 0] = lerp(color0[0], color1[0], a);
lut[x * 4 + 1] = lerp(color0[1], color1[1], a);
lut[x * 4 + 2] = lerp(color0[2], color1[2], a);
lut[x * 4 + 3] = lerp(color0[3], color1[3], a);
}
return { lut: lut, controlPoints: controlPoints };
}
/* eslint-enable @typescript-eslint/naming-convention */
}
export { LUT_ARRAY_LENGTH }; | the_stack |
import { BackgroundpageWindow, TabData, LogListenerLine, LogListenerObject, LogListener, CRMAPIMessageInstance, ContextMenuItemTreeItem, ContextMenuOverrides } from './sharedTypes.js';
import { I18NKeys } from "../../_locales/i18n-keys.js";
import { MessageHandling } from "./messagehandling.js";
import { BrowserHandler } from "./browserhandler.js";
import { ModuleData } from "./moduleTypes";
declare const browserAPI: browserAPI;
declare const window: BackgroundpageWindow;
export namespace GlobalDeclarations {
export let modules: ModuleData;
export function initModule(_modules: ModuleData) {
modules = _modules;
}
export function initGlobalFunctions() {
const findNodeMsg = 'you can find it by' +
' calling window.getID("nodename") where nodename is the name of your' +
' node';
window.debugNextScriptCall = (id: CRM.NodeId<CRM.ScriptNode>) => {
if (id !== 0 && !id || typeof id !== 'number') {
throw new Error(`Please supply a valid node ID, ${findNodeMsg}`);
}
const node = modules.crm.crmByIdSafe.get(id);
if (!node) {
throw new Error(`There is no node with the node ID you supplied, ${findNodeMsg}`);
}
if (node.type !== 'script') {
throw new Error('The node you supplied is not of type script');
}
console.log('Listening for next activation. ' +
'Make sure the devtools of the tab on which you ' +
'activate the script are open when you activate it');
if (modules.globalObject.globals.eventListeners.scriptDebugListeners.indexOf(id) === -1) {
modules.globalObject.globals.eventListeners.scriptDebugListeners.push(id);
}
}
window.debugBackgroundScript = (id: CRM.NodeId<CRM.ScriptNode>) => {
if (id !== 0 && !id || typeof id !== 'number') {
throw new Error(`Please supply a valid node ID, ${findNodeMsg}`);
}
const node = modules.crm.crmByIdSafe.get(id);
if (!node) {
throw new Error(`There is no node with the node ID you supplied, ${findNodeMsg}`);
}
if (node.type !== 'script') {
throw new Error('The node you supplied is not of type script');
}
if (node.value.backgroundScript === '') {
throw new Error('Backgroundscript is empty (code is empty string)');
}
modules.CRMNodes.Script.Background.createBackgroundPage(
modules.crm.crmById.get(id), true);
}
window.getID = (searchedName: string) => {
searchedName = searchedName.toLowerCase();
const matches: {
id: CRM.GenericNodeId;
node: CRM.ScriptNode;
}[] = [];
modules.Util.iterateMap(modules.crm.crmById, (id, node) => {
const { name } = node;
if (!name) {
return;
}
if (node.type === 'script' && searchedName === name.toLowerCase()) {
matches.push({
id: id as CRM.GenericNodeId,
node
});
}
});
if (matches.length === 0) {
window.logAsync(window.__(I18NKeys.background.globalDeclarations.getID.noMatches));
} else if (matches.length === 1) {
window.logAsync(window.__(I18NKeys.background.globalDeclarations.getID.oneMatch,
matches[0].id), matches[0].node);
} else {
window.logAsync(window.__(I18NKeys.background.globalDeclarations.getID.multipleMatches));
matches.forEach((match) => {
window.logAsync(`${window.__(I18NKeys.crm.id)}:`, match.id,
`, ${window.__(I18NKeys.crm.node)}:`, match.node);
});
}
};
window.filter = (nodeId: CRM.GenericNodeId | string, tabId: string | TabId | void) => {
modules.globalObject.globals.logging.filter = {
id: ~~nodeId as CRM.GenericNodeId,
tabId: tabId !== undefined ? ~~tabId : null
};
};
window._listenIds = (listener: (ids: {
id: CRM.GenericNodeId;
title: string;
}[]) => void) => {
modules.Logging.Listeners.updateTabAndIdLists().then(({ids}) => {
listener(ids);
modules.listeners.ids.push(listener);
});
};
window._listenTabs = (listener: (tabs: TabData[]) => void) => {
modules.Logging.Listeners.updateTabAndIdLists().then(({tabs}) => {
listener(tabs);
modules.listeners.tabs.push(listener);
});
};
function sortMessages(messages: LogListenerLine[]): LogListenerLine[] {
return messages.sort((a, b) => {
return new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
});
}
function filterMessageText(messages: LogListenerLine[],
filter: string): LogListenerLine[] {
if (filter === '') {
return messages;
}
const filterRegex = new RegExp(filter);
return messages.filter((message: LogListenerLine) => {
for (let i = 0; i < message.data.length; i++) {
if (typeof message.data[i] !== 'function' &&
typeof message.data[i] !== 'object') {
if (filterRegex.test(String(message.data[i]))) {
return true;
}
}
}
return false;
});
}
function getLog(id: string | CRM.GenericNodeId, tab: string | TabId, text: string): LogListenerLine[] {
let messages: LogListenerLine[] = [];
const logging = modules.globalObject.globals.logging;
if (id === 'all') {
for (let nodeId in logging) {
if (logging.hasOwnProperty(nodeId) && nodeId !== 'filter') {
messages = messages.concat(
logging[nodeId].logMessages
);
}
}
} else {
const idLogs = logging[id as CRM.GenericNodeId];
messages = (idLogs && idLogs.logMessages) || [];
}
if (tab === 'all') {
return sortMessages(filterMessageText(messages, text));
} else {
return sortMessages(filterMessageText(messages.filter((message) => {
return message.tabId === tab;
}), text));
}
};
function updateLog (this: LogListenerObject, id: CRM.GenericNodeId | 'ALL',
tab: TabId | 'ALL' | 'background',
textFilter: string): LogListenerLine[] {
if (id === 'ALL' || id === 0) {
this.id = 'all';
} else {
this.id = id;
}
if (tab === 'ALL' || tab === 0) {
this.tab = 'all';
} else if (typeof tab === 'string' && tab.toLowerCase() === 'background') {
this.tab = 0;
} else {
this.tab = tab;
}
if (!textFilter) {
this.text = '';
} else {
this.text = textFilter;
}
return getLog(this.id, this.tab, this.text);
}
window._listenLog = (listener: LogListener,
callback: (filterObj: LogListenerObject) => void): LogListenerLine[] => {
const filterObj: LogListenerObject = {
id: 'all',
tab: 'all',
text: '',
listener: listener,
update(id, tab, textFilter) {
return updateLog.apply(filterObj, [id, tab, textFilter]);
},
index: modules.listeners.log.length
};
callback(filterObj);
modules.listeners.log.push(filterObj);
return getLog('all', 'all', '');
};
window._getIdsAndTabs = async (selectedId: CRM.GenericNodeId, selectedTab: TabId|'background',
callback: (result: {
ids: {
id: string|CRM.GenericNodeId;
title: string;
}[];
tabs: TabData[];
}) => void) => {
callback({
ids: modules.Logging.Listeners.getIds(selectedTab === 'background' ? 0 : selectedTab),
tabs: await modules.Logging.Listeners.getTabs(selectedId)
});
}
window._getCurrentTabIndex = (id: CRM.GenericNodeId, currentTab: TabId|'background',
listener: (newTabIndexes: TabIndex[]) => void) => {
if (currentTab === 'background') {
listener([0]);
} else {
listener(modules.crmValues.tabData.get(currentTab as TabId)
.nodes.get(id).map((_element, index) => {
return index;
}));
}
}
}
function permissionsChanged(available: _browser.permissions.Permissions) {
modules.globalObject.globals.availablePermissions = available.permissions;
}
export async function refreshPermissions() {
if ((window as any).chrome && (window as any).chrome.permissions) {
const chromePermissions: typeof _chrome.permissions = (window as any).chrome.permissions;
if ('onRemoved' in chromePermissions && 'onAdded' in chromePermissions) {
chromePermissions.onRemoved.addListener(permissionsChanged);
chromePermissions.onAdded.addListener(permissionsChanged);
}
}
const available = browserAPI.permissions ? await browserAPI.permissions.getAll() : {
permissions: []
};
modules.globalObject.globals.availablePermissions = available.permissions;
}
export function setHandlerFunction() {
interface HandshakeMessage extends CRMAPIMessageInstance<string, any> {
key?: number[];
}
window.createHandlerFunction = (port) => {
return async (message: HandshakeMessage) => {
const crmValues = modules.crmValues;
const tabData = crmValues.tabData;
const nodeInstances = crmValues.nodeInstances;
const tabNodeData = modules.Util.getLastItem(
tabData.get(message.tabId).nodes.get(message.id)
);
if (!tabNodeData.port) {
if (modules.Util.compareArray(tabNodeData.secretKey, message.key)) {
delete tabNodeData.secretKey;
tabNodeData.port = port;
modules.Util.setMapDefault(nodeInstances, message.id, new window.Map());
const instancesArr: {
id: TabId;
tabIndex: TabIndex;
}[] = [];
const currentInstance: {
id: TabId;
tabIndex: TabIndex;
} = {
id: message.tabId,
tabIndex: tabData.get(message.tabId).nodes.get(message.id).length - 1
}
modules.Util.iterateMap(nodeInstances.get(message.id), (tabId) => {
try {
tabData.get(tabId).nodes.get(message.id).forEach((tabInstance, index, arr) => {
if (tabId === message.tabId && index === arr.length - 1) {
return;
}
instancesArr.push({
id: tabId,
tabIndex: index
});
modules.Util.postMessage(tabInstance.port, {
change: {
type: 'added',
value: currentInstance.id,
tabIndex: currentInstance.tabIndex
},
messageType: 'instancesUpdate'
});
});
} catch (e) {
nodeInstances.get(message.id).delete(tabId);
}
});
modules.Util.setMapDefault(nodeInstances.get(message.id),
message.tabId, []);
nodeInstances.get(message.id).get(message.tabId).push({
hasHandler: false
});
modules.Util.postMessage(port, {
data: 'connected',
instances: instancesArr,
currentInstance: {
id: currentInstance.id,
tabIndex: currentInstance.tabIndex
}
});
}
} else {
await modules.MessageHandling.handleCrmAPIMessage(
(message as any) as MessageHandling.CRMAPICallMessage|
BrowserHandler.ChromeAPIMessage);
}
};
};
}
export function init() {
async function removeNode({id}: ContextMenuItemTreeItem) {
await browserAPI.contextMenus.remove(id).catch(() => { });
}
function setStatusForTree(tree: ContextMenuItemTreeItem[], enabled: boolean) {
for (const item of tree) {
item.enabled = enabled;
if (item.children) {
setStatusForTree(item.children, enabled);
}
}
}
function getFirstRowChange(row: ContextMenuItemTreeItem[], changes: {
[contextMenuId: string]: {
node: CRM.Node;
type: 'hide' | 'show';
}
[contextMenuId: number]: {
node: CRM.Node;
type: 'hide' | 'show';
}
}) {
for (let i in row) {
if (row[i] && changes[row[i].id]) {
return ~~i;
}
}
return Infinity;
}
async function reCreateNode (parentId: string|number, item: ContextMenuItemTreeItem, changes: {
[contextMenuId: string]: {
node: CRM.Node;
type: 'hide' | 'show';
}
[contextMenuId: number]: {
node: CRM.Node;
type: 'hide' | 'show';
}
}) {
const oldId = item.id;
item.enabled = true;
const { settings } = modules.crmValues.contextMenuInfoById.get(item.id);
if (item.node && item.node.type === 'stylesheet' && item.node.value.toggle) {
settings.checked = item.node.value.defaultOn;
}
settings.parentId = parentId;
//This is added by chrome to the object during/after creation so delete it manually
delete settings.generatedId;
const id = await browserAPI.contextMenus.create(settings);
//Update ID
item.id = id;
if (item.node) {
modules.crmValues.contextMenuIds.set(item.node.id, id);
}
modules.crmValues.contextMenuInfoById.set(id,
modules.crmValues.contextMenuInfoById.get(oldId));
modules.crmValues.contextMenuInfoById.delete(oldId);
modules.crmValues.contextMenuInfoById.get(id).enabled = true;
if (item.children) {
await buildSubTreeFromNothing(id, item.children, changes);
}
}
async function buildSubTreeFromNothing(parentId: string|number,
tree: ContextMenuItemTreeItem[], changes: {
[contextMenuId: string]: {
node: CRM.Node;
type: 'hide' | 'show';
}
[contextMenuId: number]: {
node: CRM.Node;
type: 'hide' | 'show';
}
}) {
for (const item of tree) {
if ((changes[item.id] && changes[item.id].type === 'show') ||
!changes[item.id]) {
await reCreateNode(parentId, item, changes);
} else {
modules.crmValues.contextMenuInfoById.get(item.id)
.enabled = false;
}
}
}
async function applyNodeChangesOntree(parentId: string|number,
tree: ContextMenuItemTreeItem[], changes: {
[contextMenuId: string]: {
node: CRM.Node;
type: 'hide' | 'show';
}
[contextMenuId: number]: {
node: CRM.Node;
type: 'hide' | 'show';
}
}) {
//Remove all nodes below it and re-enable them and its children
//First check everything above it
const firstChangeIndex = getFirstRowChange(tree, changes);
if (firstChangeIndex < tree.length) {
//Normally check everything before the changed one
for (let i = 0; i < firstChangeIndex; i++) {
if (tree[i].children && tree[i].children.length > 0) {
await applyNodeChangesOntree(tree[i].id, tree[i].children, changes);
}
}
}
//Check everything below it
for (let i = firstChangeIndex; i < tree.length; i++) {
if (changes[tree[i].id]) {
if (changes[tree[i].id].type === 'hide') {
if (tree[i].enabled === false) {
//The part below already disabled it, no point in disabling it again
continue;
}
await hideNodeAndChildren(tree[i]);
} else {
if (tree[i].enabled) {
//Already enabled
continue;
}
//Create list of nodes to enable afterwards as they are added in order of creating
const enableAfter = [tree[i]];
//Iterate next siblings
for (let j = i + 1; j < tree.length; j++) {
if (changes[tree[j].id]) {
//If changes were happening anyway
if (changes[tree[j].id].type === 'hide') {
if (tree[i].enabled === false) {
//It was already disabled
continue;
}
//If it was going to be removed anyway, remove it now and don't show it again
await hideNodeAndChildren(tree[j]);
} else {
//It was going to be showed, add it to the toShow list
enableAfter.push(tree[j]);
if (tree[j].enabled) {
await removeNode(tree[j]);
}
}
} else if (tree[j].enabled) {
//It was already enabled and should be enabled again
enableAfter.push(tree[j]);
await removeNode(tree[j]);
}
}
for (const enableAfterItem of enableAfter) {
await reCreateNode(parentId, enableAfterItem, changes);
}
}
}
}
}
async function hideNodeAndChildren(node: ContextMenuItemTreeItem) {
//Remove hidden node and its children
await removeNode(node);
//Set it and its children's status to hidden
node.enabled = false;
if (node.children) {
setStatusForTree(node.children, false);
}
}
function getNodeStatusses(subtree: ContextMenuItemTreeItem[],
hiddenNodes: ContextMenuItemTreeItem[] = [],
shownNodes: ContextMenuItemTreeItem[] = []) {
for (let i = 0; i < subtree.length; i++) {
if (subtree[i]) {
(subtree[i].enabled ? shownNodes : hiddenNodes).push(subtree[i]);
getNodeStatusses(subtree[i].children, hiddenNodes, shownNodes);
}
}
return {
hiddenNodes,
shownNodes
}
}
function getToHide(tab: _browser.tabs.Tab, shown: ContextMenuItemTreeItem[]): {
node: CRM.DividerNode | CRM.MenuNode | CRM.LinkNode | CRM.StylesheetNode | CRM.ScriptNode;
id: string | number;
type: 'hide'|'show';
}[] {
return shown.map(({node, id}) => {
if (node === null) {
//It's one of the options contextmenu items
return null;
}
if (modules.crmValues.hideNodesOnPagesData.has(node.id) &&
modules.URLParsing.matchesUrlSchemes(
modules.crmValues.hideNodesOnPagesData.get(node.id), tab.url)) {
//Don't hide on current url
return {
node,
id,
type: 'hide'
} as {
node: CRM.DividerNode | CRM.MenuNode | CRM.LinkNode | CRM.StylesheetNode | CRM.ScriptNode;
id: string | number;
type: 'hide';
};
}
return null;
}).filter(val => !!val)
}
function getToEnable(tab: _browser.tabs.Tab, hidden: ContextMenuItemTreeItem[]): {
node: CRM.DividerNode | CRM.MenuNode | CRM.LinkNode | CRM.StylesheetNode | CRM.ScriptNode;
id: string | number;
type: 'show'|'hide';
}[] {
return hidden.map(({node, id}) => {
if (node === null) {
//It's one of the options contextmenu items
return null;
}
if (!modules.crmValues.hideNodesOnPagesData.has(node.id) ||
!modules.URLParsing.matchesUrlSchemes(
modules.crmValues.hideNodesOnPagesData.get(node.id), tab.url)) {
//Don't hide on current url
return {
node,
id,
type: 'show'
} as {
node: CRM.DividerNode | CRM.MenuNode | CRM.LinkNode | CRM.StylesheetNode | CRM.ScriptNode;
id: string | number;
type: 'show';
}
}
return null;
}).filter(val => !!val).filter(({node}) => {
return !modules.crmValues.hideNodesOnPagesData.has(node.id) ||
!modules.URLParsing.matchesUrlSchemes(
modules.crmValues.hideNodesOnPagesData.get(node.id), tab.url);
});
}
function getContextmenuTabOverrides(nodeId: CRM.GenericNodeId, tabId: TabId): ContextMenuOverrides {
const statuses = modules.crmValues.nodeTabStatuses;
if (!statuses.has(nodeId) || !statuses.get(nodeId)) {
return null;
}
if (!statuses.get(nodeId).tabs.has(tabId) ||
!statuses.get(nodeId).tabs.get(tabId)) {
return null;
}
return statuses.get(nodeId).tabs.get(tabId).overrides;
}
async function tabChangeListener(changeInfo: {
tabIds: TabId[];
windowId?: number;
}) {
//Horrible workaround that allows the hiding of nodes on certain url's that
// surprisingly only takes ~1-2ms per tab switch.
const currentTabId = changeInfo.tabIds[changeInfo.tabIds.length - 1];
const tab = await browserAPI.tabs.get(currentTabId).catch((err) => {
if (err.message.indexOf('No tab with id:') > -1) {
if (modules.storages.failedLookups.length > 1000) {
let removed: number = 0;
while (modules.storages.failedLookups.pop()) {
removed++;
if (removed === 500) {
break;
}
}
modules.storages.failedLookups.push('Cleaning up last 500 array items because size exceeded 1000...');
}
modules.storages.failedLookups.push(currentTabId);
} else {
window.log(err.message);
}
});
if (!tab) {
return;
}
//Show/remove nodes based on current URL
const changes: {
[contextMenuId: string]: {
node: CRM.Node;
type: 'hide' | 'show';
}
[contextMenuId: number]: {
node: CRM.Node;
type: 'hide' | 'show';
}
} = {};
const { shownNodes, hiddenNodes } = getNodeStatusses(modules.crmValues.contextMenuItemTree);
[...getToHide(tab, shownNodes), ...getToEnable(tab, hiddenNodes)].forEach(({ node, id, type }) => {
changes[id] = {
node,
type
}
});
//Apply changes
await applyNodeChangesOntree(modules.crmValues.rootId,
modules.crmValues.contextMenuItemTree, changes);
const statuses = modules.crmValues.nodeTabStatuses;
const ids = modules.crmValues.contextMenuIds;
modules.Util.asyncIterateMap(statuses, async (nodeId, { tabs, defaultCheckedValue }) => {
const isStylesheet = modules.crm.crmById.get(nodeId).type === 'stylesheet';
const currentValue = tabs.get(currentTabId);
const base = isStylesheet ? {
checked: typeof currentValue === 'boolean' ?
currentValue : defaultCheckedValue
} : null;
const overrides = getContextmenuTabOverrides(nodeId, currentTabId);
if (!base && !overrides) {
return true;
}
await browserAPI.contextMenus.update(ids.get(nodeId),
modules.Util.applyContextmenuOverride(base || {},
overrides || {})).catch((err) => {
window.log(err.message);
})
return void 0;
});
}
function onTabUpdated(_id: TabId, changeInfo: {
status?: 'loading'|'complete';
url?: string;
pinned?: boolean;
audible?: boolean;
discarded?: boolean;
autoDiscardable?: boolean;
mutedInfo?: any;
favIconUrl?: string;
title?: string;
}, tab: _browser.tabs.Tab) {
if (changeInfo.status && changeInfo.status === 'loading' &&
changeInfo.url && modules.Util.canRunOnUrl(changeInfo.url)) {
runAlwaysRunNodes(tab);
}
}
function onTabsRemoved(tabId: TabId) {
//Delete all data for this tabId
modules.Util.iterateMap(modules.crmValues.nodeTabStatuses, (_, nodeStatus) => {
nodeStatus.tabs.delete(tabId);
});
//Delete this instance if it exists
const deleted: CRM.GenericNodeId[] = [];
modules.Util.iterateMap(modules.crmValues.nodeInstances, (nodeId, nodeStatus) => {
if (nodeStatus && nodeStatus.has(tabId)) {
deleted.push(nodeId);
nodeStatus.delete(tabId);
}
});
for (let i = 0; i < deleted.length; i++) {
if ((deleted[i] as any).node && (deleted[i] as any).node.id !== undefined) {
modules.crmValues.tabData.get(tabId).nodes.get((deleted[i] as any).node.id)
.forEach((tabInstance) => {
modules.Util.postMessage(tabInstance.port, {
change: {
type: 'removed',
value: tabId
},
messageType: 'instancesUpdate'
});
});
}
}
modules.crmValues.tabData.delete(tabId);
modules.Logging.Listeners.updateTabAndIdLists();
}
function listenNotifications() {
const { notificationListeners } = modules.globalObject.globals.eventListeners;
if (browserAPI.notifications) {
browserAPI.notifications.onClicked.addListener((notificationId: string) => {
const notification = notificationListeners.get(notificationId);
if (notification && notification.onClick !== undefined) {
modules.globalObject.globals.sendCallbackMessage(notification.tabId, notification.tabIndex,
notification.id, {
err: false,
args: [notificationId],
callbackId: notification.onClick
});
}
});
browserAPI.notifications.onClosed.addListener((notificationId, byUser?: boolean) => {
const notification = notificationListeners.get(notificationId);
if (notification && notification.onDone !== undefined) {
modules.globalObject.globals.sendCallbackMessage(notification.tabId, notification.tabIndex,
notification.id, {
err: false,
args: [notificationId, byUser],
callbackId: notification.onClick
});
}
notificationListeners.delete(notificationId);
});
}
}
async function updateKeyCommands() {
if (browserAPI.commands) {
return await browserAPI.commands.getAll();
}
return [];
}
function permute<T>(arr: T[], prefix: T[] = []): T[][] {
if (arr.length === 0) {
return [prefix];
}
return arr.map((x, index) => {
const newRest = [...arr.slice(0, index), ...arr.slice(index + 1)];
const newPrefix = [...prefix, x];
const result = permute(newRest, newPrefix);
return result;
}).reduce((flattened, arr) => [...flattened, ...arr], []);
}
function listenKeyCommands() {
if (!browserAPI.commands) {
return;
}
const shortcutListeners = modules.globalObject.globals.eventListeners.shortcutListeners;
browserAPI.commands.onCommand.addListener(async (command) => {
const commands = await updateKeyCommands();
commands.forEach((registerCommand) => {
if (registerCommand.name === command) {
const keys = registerCommand.shortcut.toLowerCase();
const permutations = permute(keys.split('+'));
permutations.forEach((permutation) => {
const permutationKey = permutation.join('+');
if (shortcutListeners.has(permutationKey) &&
shortcutListeners.get(permutationKey)) {
shortcutListeners.get(permutationKey)
.forEach((listener) => {
listener.callback();
});
}
});
}
});
});
}
browserAPI.tabs.onUpdated.addListener(onTabUpdated);
browserAPI.tabs.onRemoved.addListener(onTabsRemoved);
browserAPI.tabs.onHighlighted && browserAPI.tabs.onHighlighted.addListener(tabChangeListener);
listenNotifications();
listenKeyCommands();
}
export function runAlwaysRunNodes(tab: _browser.tabs.Tab) {
for (const { id } of modules.toExecuteNodes.always.documentStart) {
modules.CRMNodes.Running.executeNode(
modules.crm.crmById.get(id), tab);
}
for (const { id, triggers } of modules.toExecuteNodes.onUrl.documentStart) {
if (modules.URLParsing.matchesUrlSchemes(triggers, tab.url)) {
modules.CRMNodes.Running.executeNode(
modules.crm.crmById.get(id), tab);
}
}
}
export function getResourceData(name: string, scriptId: CRM.NodeId<CRM.ScriptNode>) {
if (modules.storages.resources.get(scriptId)[name] &&
modules.storages.resources.get(scriptId)[name].matchesHashes) {
return modules.storages.urlDataPairs.get(
modules.storages.resources.get(scriptId)[name].sourceUrl).dataURI;
}
return null;
}
const enum RestoreTabStatus {
SUCCESS = 0,
UNKNOWN_ERROR = 1,
IGNORED = 2,
FROZEN = 3
}
export async function restoreOpenTabs() {
const tabs = await browserAPI.tabs.query({});
if (tabs.length === 0) {
return;
}
await window.Promise.all(tabs.map(async (tab) => {
const state = await Promise.race([
modules.Util.iipe<RestoreTabStatus>(async () => {
if (modules.Util.canRunOnUrl(tab.url)) {
try {
await browserAPI.tabs.executeScript(tab.id, {
file: '/js/polyfills/browser.js'
});
await browserAPI.tabs.executeScript(tab.id, {
file: '/js/contentscript.js'
});
return RestoreTabStatus.SUCCESS;
} catch(e) {
return RestoreTabStatus.UNKNOWN_ERROR;
}
} else {
return RestoreTabStatus.IGNORED;
}
}),
new window.Promise<RestoreTabStatus>(async (resolve) => {
await modules.Util.wait(2500);
resolve(RestoreTabStatus.FROZEN);
})
]);
switch (state) {
case RestoreTabStatus.SUCCESS:
window.logAsync(
window.__(I18NKeys.background.globalDeclarations.tabRestore.success,
tab.id));
break;
case RestoreTabStatus.UNKNOWN_ERROR:
window.logAsync(
window.__(I18NKeys.background.globalDeclarations.tabRestore.unknownError,
tab.id));
break;
case RestoreTabStatus.IGNORED:
window.logAsync(
window.__(I18NKeys.background.globalDeclarations.tabRestore.ignored,
tab.id));
break;
case RestoreTabStatus.FROZEN:
window.logAsync(
window.__(I18NKeys.background.globalDeclarations.tabRestore.frozen,
tab.id));
break;
};
}));
}
} | the_stack |
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export { BaseResource, CloudError };
/**
* Credential details of the shares in account.
*/
export interface ShareCredentialDetails {
/**
* Name of the share.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly shareName?: string;
/**
* Type of the share. Possible values include: 'UnknownType', 'HCS', 'BlockBlob', 'PageBlob',
* 'AzureFile', 'ManagedDisk'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly shareType?: ShareDestinationFormatType;
/**
* User name for the share.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly userName?: string;
/**
* Password for the share.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly password?: string;
/**
* Access protocols supported on the device.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly supportedAccessProtocols?: AccessProtocol[];
}
/**
* Credential details of the account.
*/
export interface AccountCredentialDetails {
/**
* Name of the account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly accountName?: string;
/**
* Data Destination Type. Possible values include: 'StorageAccount', 'ManagedDisk'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly dataDestinationType?: DataDestinationType;
/**
* Connection string of the account endpoint to use the account as a storage endpoint on the
* device.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly accountConnectionString?: string;
/**
* Per share level unencrypted access credentials.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly shareCredentialDetails?: ShareCredentialDetails[];
}
/**
* Shipping address where customer wishes to receive the device.
*/
export interface ShippingAddress {
/**
* Street Address line 1.
*/
streetAddress1: string;
/**
* Street Address line 2.
*/
streetAddress2?: string;
/**
* Street Address line 3.
*/
streetAddress3?: string;
/**
* Name of the City.
*/
city?: string;
/**
* Name of the State or Province.
*/
stateOrProvince?: string;
/**
* Name of the Country.
*/
country: string;
/**
* Postal code.
*/
postalCode: string;
/**
* Extended Zip Code.
*/
zipExtendedCode?: string;
/**
* Name of the company.
*/
companyName?: string;
/**
* Type of address. Possible values include: 'None', 'Residential', 'Commercial'
*/
addressType?: AddressType;
}
/**
* Output of the address validation api.
*/
export interface AddressValidationOutput {
/**
* Error code and message of validation response.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly error?: ErrorModel;
/**
* Polymorphic Discriminator
*/
validationType: string;
/**
* The address validation status. Possible values include: 'Valid', 'Invalid', 'Ambiguous'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly validationStatus?: AddressValidationStatus;
/**
* List of alternate addresses.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly alternateAddresses?: ShippingAddress[];
}
/**
* The Network Adapter configuration of a DataBox.
*/
export interface ApplianceNetworkConfiguration {
/**
* Name of the network.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Mac Address.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly macAddress?: string;
}
/**
* Base class for all objects under resource.
*/
export interface ArmBaseObject {
/**
* Name of the object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Id of the object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Type of the object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* The filters for showing the available skus.
*/
export interface AvailableSkuRequest {
/**
* ISO country code. Country for hardware shipment. For codes check:
* https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements
*/
country: string;
/**
* Location for data transfer. For locations check:
* https://management.azure.com/subscriptions/SUBSCRIPTIONID/locations?api-version=2018-01-01
*/
location: string;
/**
* Sku Names to filter for available skus
*/
skuNames?: SkuName[];
}
/**
* The Sku.
*/
export interface Sku {
/**
* The sku name. Possible values include: 'DataBox', 'DataBoxDisk', 'DataBoxHeavy'
*/
name: SkuName;
/**
* The display name of the sku.
*/
displayName?: string;
/**
* The sku family.
*/
family?: string;
}
/**
* Map of destination location to service location.
*/
export interface DestinationToServiceLocationMap {
/**
* Location of the destination.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly destinationLocation?: string;
/**
* Location of the service.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly serviceLocation?: string;
}
/**
* Capacity of the sku.
*/
export interface SkuCapacity {
/**
* Usable capacity in TB.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly usable?: string;
/**
* Maximum capacity in TB.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly maximum?: string;
}
/**
* Describes metadata for retrieving price info.
*/
export interface SkuCost {
/**
* Meter id of the Sku.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly meterId?: string;
/**
* The type of the meter.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly meterType?: string;
}
/**
* Information of the sku.
*/
export interface SkuInformation {
/**
* The Sku.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly sku?: Sku;
/**
* The sku is enabled or not.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly enabled?: boolean;
/**
* The map of destination location to service location.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly destinationToServiceLocationMap?: DestinationToServiceLocationMap[];
/**
* Capacity of the Sku.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly capacity?: SkuCapacity;
/**
* Cost of the Sku.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly costs?: SkuCost[];
/**
* Api versions that support this Sku.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly apiVersions?: string[];
/**
* Reason why the Sku is disabled. Possible values include: 'None', 'Country', 'Region',
* 'Feature', 'OfferType', 'NoSubscriptionInfo'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly disabledReason?: SkuDisabledReason;
/**
* Message for why the Sku is disabled.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly disabledReasonMessage?: string;
/**
* Required feature to access the sku.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly requiredFeature?: string;
}
/**
* Reason for cancellation.
*/
export interface CancellationReason {
/**
* Reason for cancellation.
*/
reason: string;
}
/**
* Notification preference for a job stage.
*/
export interface NotificationPreference {
/**
* Name of the stage. Possible values include: 'DevicePrepared', 'Dispatched', 'Delivered',
* 'PickedUp', 'AtAzureDC', 'DataCopy'
*/
stageName: NotificationStageName;
/**
* Notification is required or not.
*/
sendNotification: boolean;
}
/**
* Contact Details.
*/
export interface ContactDetails {
/**
* Contact name of the person.
*/
contactName: string;
/**
* Phone number of the contact person.
*/
phone: string;
/**
* Phone extension number of the contact person.
*/
phoneExtension?: string;
/**
* Mobile number of the contact person.
*/
mobile?: string;
/**
* List of Email-ids to be notified about job progress.
*/
emailList: string[];
/**
* Notification preference for a job stage.
*/
notificationPreference?: NotificationPreference[];
}
/**
* Contains the possible cases for CopyLogDetails.
*/
export type CopyLogDetailsUnion = CopyLogDetails | DataBoxAccountCopyLogDetails | DataBoxDiskCopyLogDetails | DataBoxHeavyAccountCopyLogDetails;
/**
* Details for log generated during copy.
*/
export interface CopyLogDetails {
/**
* Polymorphic Discriminator
*/
copyLogDetailsType: "CopyLogDetails";
}
/**
* Copy progress.
*/
export interface CopyProgress {
/**
* Name of the storage account where the data needs to be uploaded.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly storageAccountName?: string;
/**
* Data Destination Type. Possible values include: 'StorageAccount', 'ManagedDisk'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly dataDestinationType?: DataDestinationType;
/**
* Id of the account where the data needs to be uploaded.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly accountId?: string;
/**
* Amount of data uploaded by the job as of now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly bytesSentToCloud?: number;
/**
* Total amount of data to be processed by the job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly totalBytesToProcess?: number;
/**
* Number of files processed by the job as of now.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly filesProcessed?: number;
/**
* Total number of files to be processed by the job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly totalFilesToProcess?: number;
/**
* Number of files not adhering to azure naming conventions which were processed by automatic
* renaming
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly invalidFilesProcessed?: number;
/**
* Total amount of data not adhering to azure naming conventions which were processed by
* automatic renaming
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly invalidFileBytesUploaded?: number;
/**
* Number of folders not adhering to azure naming conventions which were processed by automatic
* renaming
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly renamedContainerCount?: number;
/**
* Number of files which could not be copied
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly filesErroredOut?: number;
}
/**
* Contains the possible cases for ValidationInputRequest.
*/
export type ValidationInputRequestUnion = ValidationInputRequest | CreateOrderLimitForSubscriptionValidationRequest | DataDestinationDetailsValidationRequest | PreferencesValidationRequest | SkuAvailabilityValidationRequest | SubscriptionIsAllowedToCreateJobValidationRequest | ValidateAddress;
/**
* Minimum fields that must be present in any type of validation request.
*/
export interface ValidationInputRequest {
/**
* Polymorphic Discriminator
*/
validationType: "ValidationInputRequest";
}
/**
* Request to validate create order limit for current subscription.
*/
export interface CreateOrderLimitForSubscriptionValidationRequest {
/**
* Polymorphic Discriminator
*/
validationType: "ValidateCreateOrderLimit";
/**
* Device type to be used for the job. Possible values include: 'DataBox', 'DataBoxDisk',
* 'DataBoxHeavy'
*/
deviceType: SkuName;
}
/**
* Contains the possible cases for ValidationInputResponse.
*/
export type ValidationInputResponseUnion = ValidationInputResponse | CreateOrderLimitForSubscriptionValidationResponseProperties | DataDestinationDetailsValidationResponseProperties | PreferencesValidationResponseProperties | SkuAvailabilityValidationResponseProperties | SubscriptionIsAllowedToCreateJobValidationResponseProperties;
/**
* Minimum properties that should be present in each individual validation response.
*/
export interface ValidationInputResponse {
/**
* Polymorphic Discriminator
*/
validationType: "ValidationInputResponse";
/**
* Error code and message of validation response.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly error?: ErrorModel;
}
/**
* Properties of create order limit for subscription validation response.
*/
export interface CreateOrderLimitForSubscriptionValidationResponseProperties {
/**
* Polymorphic Discriminator
*/
validationType: "ValidateCreateOrderLimit";
/**
* Error code and message of validation response.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly error?: ErrorModel;
/**
* Create order limit validation status. Possible values include: 'Valid', 'Invalid', 'Skipped'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: ValidationStatus;
}
/**
* Copy log details for a storage account of a DataBox job
*/
export interface DataBoxAccountCopyLogDetails {
/**
* Polymorphic Discriminator
*/
copyLogDetailsType: "DataBox";
/**
* Destination account name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly accountName?: string;
/**
* Link for copy logs.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyLogLink?: string;
}
/**
* Copy Log Details for a disk
*/
export interface DataBoxDiskCopyLogDetails {
/**
* Polymorphic Discriminator
*/
copyLogDetailsType: "DataBoxDisk";
/**
* Disk Serial Number.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly diskSerialNumber?: string;
/**
* Link for copy error logs.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly errorLogLink?: string;
/**
* Link for copy verbose logs.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly verboseLogLink?: string;
}
/**
* DataBox Disk Copy Progress
*/
export interface DataBoxDiskCopyProgress {
/**
* The serial number of the disk
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly serialNumber?: string;
/**
* Bytes copied during the copy of disk.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly bytesCopied?: number;
/**
* Indicates the percentage completed for the copy of the disk.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly percentComplete?: number;
/**
* The Status of the copy. Possible values include: 'NotStarted', 'InProgress', 'Completed',
* 'CompletedWithErrors', 'Failed', 'NotReturned', 'HardwareError', 'DeviceFormatted',
* 'DeviceMetadataModified', 'StorageAccountNotAccessible', 'UnsupportedData'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: CopyStatus;
}
/**
* Contains the possible cases for JobDetails.
*/
export type JobDetailsUnion = JobDetails | DataBoxDiskJobDetails | DataBoxHeavyJobDetails | DataBoxJobDetails;
/**
* Job details.
*/
export interface JobDetails {
/**
* Polymorphic Discriminator
*/
jobDetailsType: "JobDetails";
/**
* The expected size of the data, which needs to be transferred in this job, in terabytes.
*/
expectedDataSizeInTerabytes?: number;
/**
* List of stages that run in the job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly jobStages?: JobStages[];
/**
* Contact details for notification and shipping.
*/
contactDetails: ContactDetails;
/**
* Shipping address of the customer.
*/
shippingAddress: ShippingAddress;
/**
* Delivery package shipping details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly deliveryPackage?: PackageShippingDetails;
/**
* Return package shipping details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly returnPackage?: PackageShippingDetails;
/**
* Destination account details.
*/
destinationAccountDetails: DestinationAccountDetailsUnion[];
/**
* Error details for failure. This is optional.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly errorDetails?: JobErrorDetails[];
/**
* Preferences for the order.
*/
preferences?: Preferences;
/**
* List of copy log details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyLogDetails?: CopyLogDetailsUnion[];
/**
* Shared access key to download the return shipment label
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly reverseShipmentLabelSasKey?: string;
/**
* Shared access key to download the chain of custody logs
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly chainOfCustodySasKey?: string;
}
/**
* DataBox Disk Job Details.
*/
export interface DataBoxDiskJobDetails {
/**
* Polymorphic Discriminator
*/
jobDetailsType: "DataBoxDisk";
/**
* The expected size of the data, which needs to be transferred in this job, in terabytes.
*/
expectedDataSizeInTerabytes?: number;
/**
* List of stages that run in the job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly jobStages?: JobStages[];
/**
* Contact details for notification and shipping.
*/
contactDetails: ContactDetails;
/**
* Shipping address of the customer.
*/
shippingAddress: ShippingAddress;
/**
* Delivery package shipping details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly deliveryPackage?: PackageShippingDetails;
/**
* Return package shipping details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly returnPackage?: PackageShippingDetails;
/**
* Destination account details.
*/
destinationAccountDetails: DestinationAccountDetailsUnion[];
/**
* Error details for failure. This is optional.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly errorDetails?: JobErrorDetails[];
/**
* Preferences for the order.
*/
preferences?: Preferences;
/**
* List of copy log details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyLogDetails?: CopyLogDetailsUnion[];
/**
* Shared access key to download the return shipment label
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly reverseShipmentLabelSasKey?: string;
/**
* Shared access key to download the chain of custody logs
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly chainOfCustodySasKey?: string;
/**
* User preference on what size disks are needed for the job. The map is from the disk size in TB
* to the count. Eg. {2,5} means 5 disks of 2 TB size. Key is string but will be checked against
* an int.
*/
preferredDisks?: { [propertyName: string]: number };
/**
* Copy progress per disk.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyProgress?: DataBoxDiskCopyProgress[];
/**
* Contains the map of disk serial number to the disk size being used for the job. Is returned
* only after the disks are shipped to the customer.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly disksAndSizeDetails?: { [propertyName: string]: number };
/**
* User entered passkey for DataBox Disk job.
*/
passkey?: string;
}
/**
* Contains all the secrets of a Disk.
*/
export interface DiskSecret {
/**
* Serial number of the assigned disk.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly diskSerialNumber?: string;
/**
* Bit Locker key of the disk which can be used to unlock the disk to copy data.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly bitLockerKey?: string;
}
/**
* Contains the possible cases for JobSecrets.
*/
export type JobSecretsUnion = JobSecrets | DataBoxDiskJobSecrets | DataBoxHeavyJobSecrets | DataboxJobSecrets;
/**
* The base class for the secrets
*/
export interface JobSecrets {
/**
* Polymorphic Discriminator
*/
jobSecretsType: "JobSecrets";
/**
* Dc Access Security Code for Customer Managed Shipping
*/
dcAccessSecurityCode?: DcAccessSecurityCode;
}
/**
* The secrets related to disk job.
*/
export interface DataBoxDiskJobSecrets {
/**
* Polymorphic Discriminator
*/
jobSecretsType: "DataBoxDisk";
/**
* Dc Access Security Code for Customer Managed Shipping
*/
dcAccessSecurityCode?: DcAccessSecurityCode;
/**
* Contains the list of secrets object for that device.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly diskSecrets?: DiskSecret[];
/**
* PassKey for the disk Job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly passKey?: string;
/**
* Whether passkey was provided by user.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isPasskeyUserDefined?: boolean;
}
/**
* Copy log details for a storage account for Databox heavy
*/
export interface DataBoxHeavyAccountCopyLogDetails {
/**
* Polymorphic Discriminator
*/
copyLogDetailsType: "DataBoxHeavy";
/**
* Destination account name.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly accountName?: string;
/**
* Link for copy logs.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyLogLink?: string[];
}
/**
* Databox Heavy Device Job Details
*/
export interface DataBoxHeavyJobDetails {
/**
* Polymorphic Discriminator
*/
jobDetailsType: "DataBoxHeavy";
/**
* The expected size of the data, which needs to be transferred in this job, in terabytes.
*/
expectedDataSizeInTerabytes?: number;
/**
* List of stages that run in the job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly jobStages?: JobStages[];
/**
* Contact details for notification and shipping.
*/
contactDetails: ContactDetails;
/**
* Shipping address of the customer.
*/
shippingAddress: ShippingAddress;
/**
* Delivery package shipping details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly deliveryPackage?: PackageShippingDetails;
/**
* Return package shipping details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly returnPackage?: PackageShippingDetails;
/**
* Destination account details.
*/
destinationAccountDetails: DestinationAccountDetailsUnion[];
/**
* Error details for failure. This is optional.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly errorDetails?: JobErrorDetails[];
/**
* Preferences for the order.
*/
preferences?: Preferences;
/**
* List of copy log details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyLogDetails?: CopyLogDetailsUnion[];
/**
* Shared access key to download the return shipment label
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly reverseShipmentLabelSasKey?: string;
/**
* Shared access key to download the chain of custody logs
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly chainOfCustodySasKey?: string;
/**
* Copy progress per account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyProgress?: CopyProgress[];
/**
* Set Device password for unlocking Databox Heavy
*/
devicePassword?: string;
}
/**
* The secrets related to a databox heavy.
*/
export interface DataBoxHeavySecret {
/**
* Serial number of the assigned device.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly deviceSerialNumber?: string;
/**
* Password for out of the box experience on device.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly devicePassword?: string;
/**
* Network configuration of the appliance.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly networkConfigurations?: ApplianceNetworkConfiguration[];
/**
* The base 64 encoded public key to authenticate with the device
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly encodedValidationCertPubKey?: string;
/**
* Per account level access credentials.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly accountCredentialDetails?: AccountCredentialDetails[];
}
/**
* The secrets related to a databox heavy job.
*/
export interface DataBoxHeavyJobSecrets {
/**
* Polymorphic Discriminator
*/
jobSecretsType: "DataBoxHeavy";
/**
* Dc Access Security Code for Customer Managed Shipping
*/
dcAccessSecurityCode?: DcAccessSecurityCode;
/**
* Contains the list of secret objects for a databox heavy job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly cabinetPodSecrets?: DataBoxHeavySecret[];
}
/**
* Databox Job Details
*/
export interface DataBoxJobDetails {
/**
* Polymorphic Discriminator
*/
jobDetailsType: "DataBox";
/**
* The expected size of the data, which needs to be transferred in this job, in terabytes.
*/
expectedDataSizeInTerabytes?: number;
/**
* List of stages that run in the job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly jobStages?: JobStages[];
/**
* Contact details for notification and shipping.
*/
contactDetails: ContactDetails;
/**
* Shipping address of the customer.
*/
shippingAddress: ShippingAddress;
/**
* Delivery package shipping details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly deliveryPackage?: PackageShippingDetails;
/**
* Return package shipping details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly returnPackage?: PackageShippingDetails;
/**
* Destination account details.
*/
destinationAccountDetails: DestinationAccountDetailsUnion[];
/**
* Error details for failure. This is optional.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly errorDetails?: JobErrorDetails[];
/**
* Preferences for the order.
*/
preferences?: Preferences;
/**
* List of copy log details.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyLogDetails?: CopyLogDetailsUnion[];
/**
* Shared access key to download the return shipment label
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly reverseShipmentLabelSasKey?: string;
/**
* Shared access key to download the chain of custody logs
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly chainOfCustodySasKey?: string;
/**
* Copy progress per storage account.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly copyProgress?: CopyProgress[];
/**
* Set Device password for unlocking Databox
*/
devicePassword?: string;
}
/**
* The secrets related to a DataBox.
*/
export interface DataBoxSecret {
/**
* Serial number of the assigned device.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly deviceSerialNumber?: string;
/**
* Password for out of the box experience on device.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly devicePassword?: string;
/**
* Network configuration of the appliance.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly networkConfigurations?: ApplianceNetworkConfiguration[];
/**
* The base 64 encoded public key to authenticate with the device
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly encodedValidationCertPubKey?: string;
/**
* Per account level access credentials.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly accountCredentialDetails?: AccountCredentialDetails[];
}
/**
* The secrets related to a databox job.
*/
export interface DataboxJobSecrets {
/**
* Polymorphic Discriminator
*/
jobSecretsType: "DataBox";
/**
* Dc Access Security Code for Customer Managed Shipping
*/
dcAccessSecurityCode?: DcAccessSecurityCode;
/**
* Contains the list of secret objects for a job.
*/
podSecrets?: DataBoxSecret[];
}
/**
* Contains the possible cases for ScheduleAvailabilityRequest.
*/
export type ScheduleAvailabilityRequestUnion = ScheduleAvailabilityRequest | DataBoxScheduleAvailabilityRequest | DiskScheduleAvailabilityRequest | HeavyScheduleAvailabilityRequest;
/**
* Request body to get the availability for scheduling orders.
*/
export interface ScheduleAvailabilityRequest {
/**
* Polymorphic Discriminator
*/
skuName: "ScheduleAvailabilityRequest";
/**
* Location for data transfer.
* For locations check:
* https://management.azure.com/subscriptions/SUBSCRIPTIONID/locations?api-version=2018-01-01
*/
storageLocation: string;
}
/**
* Request body to get the availability for scheduling data box orders orders.
*/
export interface DataBoxScheduleAvailabilityRequest {
/**
* Polymorphic Discriminator
*/
skuName: "DataBox";
/**
* Location for data transfer.
* For locations check:
* https://management.azure.com/subscriptions/SUBSCRIPTIONID/locations?api-version=2018-01-01
*/
storageLocation: string;
}
/**
* Contains the possible cases for DestinationAccountDetails.
*/
export type DestinationAccountDetailsUnion = DestinationAccountDetails | DestinationManagedDiskDetails | DestinationStorageAccountDetails;
/**
* Details of the destination storage accounts.
*/
export interface DestinationAccountDetails {
/**
* Polymorphic Discriminator
*/
dataDestinationType: "DestinationAccountDetails";
/**
* Arm Id of the destination where the data has to be moved.
*/
accountId?: string;
/**
* Share password to be shared by all shares in SA.
*/
sharePassword?: string;
}
/**
* Request to validate data destination details.
*/
export interface DataDestinationDetailsValidationRequest {
/**
* Polymorphic Discriminator
*/
validationType: "ValidateDataDestinationDetails";
/**
* Destination account details list.
*/
destinationAccountDetails: DestinationAccountDetailsUnion[];
/**
* Location of stamp or geo.
*/
location: string;
}
/**
* Properties of data destination details validation response.
*/
export interface DataDestinationDetailsValidationResponseProperties {
/**
* Polymorphic Discriminator
*/
validationType: "ValidateDataDestinationDetails";
/**
* Error code and message of validation response.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly error?: ErrorModel;
/**
* Data destination details validation status. Possible values include: 'Valid', 'Invalid',
* 'Skipped'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: ValidationStatus;
}
/**
* Dc Access Security code for device.
*/
export interface DcAccessSecurityCode {
/**
* Dc Access Code for dispatching from DC.
*/
forwardDcAccessCode?: string;
/**
* Dc Access code for dropping off at DC.
*/
reverseDcAccessCode?: string;
}
/**
* Details for the destination compute disks.
*/
export interface DestinationManagedDiskDetails {
/**
* Polymorphic Discriminator
*/
dataDestinationType: "ManagedDisk";
/**
* Arm Id of the destination where the data has to be moved.
*/
accountId?: string;
/**
* Share password to be shared by all shares in SA.
*/
sharePassword?: string;
/**
* Destination Resource Group Id where the Compute disks should be created.
*/
resourceGroupId: string;
/**
* Arm Id of the storage account that can be used to copy the vhd for staging.
*/
stagingStorageAccountId: string;
}
/**
* Details for the destination storage account.
*/
export interface DestinationStorageAccountDetails {
/**
* Polymorphic Discriminator
*/
dataDestinationType: "StorageAccount";
/**
* Arm Id of the destination where the data has to be moved.
*/
accountId?: string;
/**
* Share password to be shared by all shares in SA.
*/
sharePassword?: string;
/**
* Destination Storage Account Arm Id.
*/
storageAccountId: string;
}
/**
* Request body to get the availability for scheduling disk orders.
*/
export interface DiskScheduleAvailabilityRequest {
/**
* Polymorphic Discriminator
*/
skuName: "DataBoxDisk";
/**
* Location for data transfer.
* For locations check:
* https://management.azure.com/subscriptions/SUBSCRIPTIONID/locations?api-version=2018-01-01
*/
storageLocation: string;
/**
* The expected size of the data, which needs to be transferred in this job, in terabytes.
*/
expectedDataSizeInTerabytes: number;
}
/**
* Top level error for the job.
*/
export interface ErrorModel {
/**
* Error code that can be used to programmatically identify the error.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly code?: string;
/**
* Describes the error in detail and provides debugging information.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly message?: string;
}
/**
* Request body to get the availability for scheduling heavy orders.
*/
export interface HeavyScheduleAvailabilityRequest {
/**
* Polymorphic Discriminator
*/
skuName: "DataBoxHeavy";
/**
* Location for data transfer.
* For locations check:
* https://management.azure.com/subscriptions/SUBSCRIPTIONID/locations?api-version=2018-01-01
*/
storageLocation: string;
}
/**
* Additional delivery info.
*/
export interface JobDeliveryInfo {
/**
* Scheduled date time.
*/
scheduledDateTime?: Date;
}
/**
* Job Error Details for providing the information and recommended action.
*/
export interface JobErrorDetails {
/**
* Message for the error.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly errorMessage?: string;
/**
* Code for the error.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly errorCode?: number;
/**
* Recommended action for the error.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly recommendedAction?: string;
/**
* Contains the non localized exception message
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly exceptionMessage?: string;
}
/**
* Job stages.
*/
export interface JobStages {
/**
* Name of the job stage. Possible values include: 'DeviceOrdered', 'DevicePrepared',
* 'Dispatched', 'Delivered', 'PickedUp', 'AtAzureDC', 'DataCopy', 'Completed',
* 'CompletedWithErrors', 'Cancelled', 'Failed_IssueReportedAtCustomer',
* 'Failed_IssueDetectedAtAzureDC', 'Aborted', 'CompletedWithWarnings',
* 'ReadyToDispatchFromAzureDC', 'ReadyToReceiveAtAzureDC'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly stageName?: StageName;
/**
* Display name of the job stage.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly displayName?: string;
/**
* Status of the job stage. Possible values include: 'None', 'InProgress', 'Succeeded', 'Failed',
* 'Cancelled', 'Cancelling', 'SucceededWithErrors'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly stageStatus?: StageStatus;
/**
* Time for the job stage in UTC ISO 8601 format.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly stageTime?: Date;
/**
* Job Stage Details
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly jobStageDetails?: any;
/**
* Error details for the stage.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly errorDetails?: JobErrorDetails[];
}
/**
* Shipping details.
*/
export interface PackageShippingDetails {
/**
* Name of the carrier.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly carrierName?: string;
/**
* Tracking Id of shipment.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly trackingId?: string;
/**
* Url where shipment can be tracked.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly trackingUrl?: string;
}
/**
* Preferences related to the shipment logistics of the sku
*/
export interface TransportPreferences {
/**
* Indicates Shipment Logistics type that the customer preferred. Possible values include:
* 'CustomerManaged', 'MicrosoftManaged'
*/
preferredShipmentType: TransportShipmentTypes;
}
/**
* Preferences related to the order
*/
export interface Preferences {
/**
* Preferred Data Center Region.
*/
preferredDataCenterRegion?: string[];
/**
* Preferences related to the shipment logistics of the sku.
*/
transportPreferences?: TransportPreferences;
}
/**
* Model of the Resource.
*/
export interface Resource extends BaseResource {
/**
* The location of the resource. This will be one of the supported and registered Azure Regions
* (e.g. West US, East US, Southeast Asia, etc.). The region of a resource cannot be changed once
* it is created, but if an identical region is specified on update the request will succeed.
*/
location: string;
/**
* The list of key value pairs that describe the resource. These tags can be used in viewing and
* grouping this resource (across resource groups).
*/
tags?: { [propertyName: string]: string };
/**
* The sku type.
*/
sku: Sku;
}
/**
* Job Resource.
*/
export interface JobResource extends Resource {
/**
* Describes whether the job is cancellable or not.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isCancellable?: boolean;
/**
* Describes whether the job is deletable or not.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isDeletable?: boolean;
/**
* Describes whether the shipping address is editable or not.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isShippingAddressEditable?: boolean;
/**
* Name of the stage which is in progress. Possible values include: 'DeviceOrdered',
* 'DevicePrepared', 'Dispatched', 'Delivered', 'PickedUp', 'AtAzureDC', 'DataCopy', 'Completed',
* 'CompletedWithErrors', 'Cancelled', 'Failed_IssueReportedAtCustomer',
* 'Failed_IssueDetectedAtAzureDC', 'Aborted', 'CompletedWithWarnings',
* 'ReadyToDispatchFromAzureDC', 'ReadyToReceiveAtAzureDC'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: StageName;
/**
* Time at which the job was started in UTC ISO 8601 format.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly startTime?: Date;
/**
* Top level error for the job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly error?: ErrorModel;
/**
* Details of a job run. This field will only be sent for expand details filter.
*/
details?: JobDetailsUnion;
/**
* Reason for cancellation.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly cancellationReason?: string;
/**
* Delivery type of Job. Possible values include: 'NonScheduled', 'Scheduled'
*/
deliveryType?: JobDeliveryType;
/**
* Delivery Info of Job.
*/
deliveryInfo?: JobDeliveryInfo;
/**
* Flag to indicate cancellation of scheduled job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly isCancellableWithoutFee?: boolean;
/**
* Name of the object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Id of the object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly id?: string;
/**
* Type of the object.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly type?: string;
}
/**
* Job details for update.
*/
export interface UpdateJobDetails {
/**
* Contact details for notification and shipping.
*/
contactDetails?: ContactDetails;
/**
* Shipping address of the customer.
*/
shippingAddress?: ShippingAddress;
}
/**
* The JobResourceUpdateParameter.
*/
export interface JobResourceUpdateParameter {
/**
* Details of a job to be updated.
*/
details?: UpdateJobDetails;
/**
* Destination account details.
*/
destinationAccountDetails?: DestinationAccountDetailsUnion[];
/**
* The list of key value pairs that describe the resource. These tags can be used in viewing and
* grouping this resource (across resource groups).
*/
tags?: { [propertyName: string]: string };
}
/**
* Operation display
*/
export interface OperationDisplay {
/**
* Provider name.
*/
provider?: string;
/**
* Resource name.
*/
resource?: string;
/**
* Localized name of the operation for display purpose.
*/
operation?: string;
/**
* Localized description of the operation for display purpose.
*/
description?: string;
}
/**
* Operation entity.
*/
export interface Operation {
/**
* Name of the operation. Format:
* {resourceProviderNamespace}/{resourceType}/{read|write|delete|action}
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly name?: string;
/**
* Operation display values.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly display?: OperationDisplay;
/**
* Operation properties.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly properties?: any;
/**
* Origin of the operation. Can be : user|system|user,system
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly origin?: string;
}
/**
* Request to validate preference of transport and data center.
*/
export interface PreferencesValidationRequest {
/**
* Polymorphic Discriminator
*/
validationType: "ValidatePreferences";
/**
* Preference requested with respect to transport type and data center
*/
preference?: Preferences;
/**
* Device type to be used for the job. Possible values include: 'DataBox', 'DataBoxDisk',
* 'DataBoxHeavy'
*/
deviceType: SkuName;
}
/**
* Properties of data center and transport preference validation response.
*/
export interface PreferencesValidationResponseProperties {
/**
* Polymorphic Discriminator
*/
validationType: "ValidatePreferences";
/**
* Error code and message of validation response.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly error?: ErrorModel;
/**
* Validation status of requested data center and transport. Possible values include: 'Valid',
* 'Invalid', 'Skipped'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: ValidationStatus;
}
/**
* Request body to get the transport availability for given sku.
*/
export interface TransportAvailabilityRequest {
/**
* Type of the device. Possible values include: 'DataBox', 'DataBoxDisk', 'DataBoxHeavy'
*/
skuName?: SkuName;
}
/**
* Request body to get the configuration for the region.
*/
export interface RegionConfigurationRequest {
/**
* Request body to get the availability for scheduling orders.
*/
scheduleAvailabilityRequest?: ScheduleAvailabilityRequestUnion;
/**
* Request body to get the transport availability for given sku.
*/
transportAvailabilityRequest?: TransportAvailabilityRequest;
}
/**
* Schedule availability response for given sku in a region.
*/
export interface ScheduleAvailabilityResponse {
/**
* List of dates available to schedule
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly availableDates?: Date[] | string[];
}
/**
* Transport options availability details for given region.
*/
export interface TransportAvailabilityDetails {
/**
* Transport Shipment Type supported for given region. Possible values include:
* 'CustomerManaged', 'MicrosoftManaged'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly shipmentType?: TransportShipmentTypes;
}
/**
* Transport options available for given sku in a region.
*/
export interface TransportAvailabilityResponse {
/**
* List of transport availability details for given region
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly transportAvailabilityDetails?: TransportAvailabilityDetails[];
}
/**
* Configuration response specific to a region.
*/
export interface RegionConfigurationResponse {
/**
* Schedule availability for given sku in a region.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly scheduleAvailabilityResponse?: ScheduleAvailabilityResponse;
/**
* Transport options available for given sku in a region.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly transportAvailabilityResponse?: TransportAvailabilityResponse;
}
/**
* Shipment pick up request details.
*/
export interface ShipmentPickUpRequest {
/**
* Minimum date after which the pick up should commence, this must be in local time of pick up
* area.
*/
startTime: Date;
/**
* Maximum date before which the pick up should commence, this must be in local time of pick up
* area.
*/
endTime: Date;
/**
* Shipment Location in the pickup place. Eg.front desk
*/
shipmentLocation: string;
}
/**
* Shipment pick up response.
*/
export interface ShipmentPickUpResponse {
/**
* Confirmation number for the pick up request.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly confirmationNumber?: string;
/**
* Time by which shipment should be ready for pick up, this is in local time of pick up area.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly readyByTime?: Date;
}
/**
* Request to validate sku availability.
*/
export interface SkuAvailabilityValidationRequest {
/**
* Polymorphic Discriminator
*/
validationType: "ValidateSkuAvailability";
/**
* Device type to be used for the job. Possible values include: 'DataBox', 'DataBoxDisk',
* 'DataBoxHeavy'
*/
deviceType: SkuName;
/**
* ISO country code. Country for hardware shipment. For codes check:
* https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements
*/
country: string;
/**
* Location for data transfer. For locations check:
* https://management.azure.com/subscriptions/SUBSCRIPTIONID/locations?api-version=2018-01-01
*/
location: string;
}
/**
* Properties of sku availability validation response.
*/
export interface SkuAvailabilityValidationResponseProperties {
/**
* Polymorphic Discriminator
*/
validationType: "ValidateSkuAvailability";
/**
* Error code and message of validation response.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly error?: ErrorModel;
/**
* Sku availability validation status. Possible values include: 'Valid', 'Invalid', 'Skipped'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: ValidationStatus;
}
/**
* Request to validate subscription permission to create jobs.
*/
export interface SubscriptionIsAllowedToCreateJobValidationRequest {
/**
* Polymorphic Discriminator
*/
validationType: "ValidateSubscriptionIsAllowedToCreateJob";
}
/**
* Properties of subscription permission to create job validation response.
*/
export interface SubscriptionIsAllowedToCreateJobValidationResponseProperties {
/**
* Polymorphic Discriminator
*/
validationType: "ValidateSubscriptionIsAllowedToCreateJob";
/**
* Error code and message of validation response.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly error?: ErrorModel;
/**
* Validation status of subscription permission to create job. Possible values include: 'Valid',
* 'Invalid', 'Skipped'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: ValidationStatus;
}
/**
* Unencrypted credentials for accessing device.
*/
export interface UnencryptedCredentials {
/**
* Name of the job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly jobName?: string;
/**
* Secrets related to this job.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly jobSecrets?: JobSecretsUnion;
}
/**
* The requirements to validate customer address where the device needs to be shipped.
*/
export interface ValidateAddress {
/**
* Polymorphic Discriminator
*/
validationType: "ValidateAddress";
/**
* Shipping address of the customer.
*/
shippingAddress: ShippingAddress;
/**
* Device type to be used for the job. Possible values include: 'DataBox', 'DataBoxDisk',
* 'DataBoxHeavy'
*/
deviceType: SkuName;
/**
* Preferences related to the shipment logistics of the sku.
*/
transportPreferences?: TransportPreferences;
}
/**
* Contains the possible cases for ValidationRequest.
*/
export type ValidationRequestUnion = ValidationRequest | CreateJobValidations;
/**
* Input request for all pre job creation validation.
*/
export interface ValidationRequest {
/**
* Polymorphic Discriminator
*/
validationCategory: "ValidationRequest";
/**
* List of request details contain validationType and its request as key and value respectively.
*/
individualRequestDetails: ValidationInputRequestUnion[];
}
/**
* It does all pre-job creation validations.
*/
export interface CreateJobValidations {
/**
* Polymorphic Discriminator
*/
validationCategory: "JobCreationValidation";
/**
* List of request details contain validationType and its request as key and value respectively.
*/
individualRequestDetails: ValidationInputRequestUnion[];
}
/**
* Response of pre job creation validations.
*/
export interface ValidationResponse {
/**
* Overall validation status. Possible values include: 'AllValidToProceed',
* 'InputsRevisitRequired', 'CertainInputValidationsSkipped'
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly status?: OverallValidationStatus;
/**
* List of response details contain validationType and its response as key and value
* respectively.
* **NOTE: This property will not be serialized. It can only be populated by the server.**
*/
readonly individualResponseDetails?: ValidationInputResponseUnion[];
}
/**
* Optional Parameters.
*/
export interface JobsListOptionalParams extends msRest.RequestOptionsBase {
/**
* $skipToken is supported on Get list of jobs, which provides the next page in the list of jobs.
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface JobsListByResourceGroupOptionalParams extends msRest.RequestOptionsBase {
/**
* $skipToken is supported on Get list of jobs, which provides the next page in the list of jobs.
*/
skipToken?: string;
}
/**
* Optional Parameters.
*/
export interface JobsGetOptionalParams extends msRest.RequestOptionsBase {
/**
* $expand is supported on details parameter for job, which provides details on the job stages.
*/
expand?: string;
}
/**
* Optional Parameters.
*/
export interface JobsUpdateOptionalParams extends msRest.RequestOptionsBase {
/**
* Defines the If-Match condition. The patch will be performed only if the ETag of the job on the
* server matches this value.
*/
ifMatch?: string;
}
/**
* Optional Parameters.
*/
export interface JobsBeginUpdateOptionalParams extends msRest.RequestOptionsBase {
/**
* Defines the If-Match condition. The patch will be performed only if the ETag of the job on the
* server matches this value.
*/
ifMatch?: string;
}
/**
* Optional Parameters.
*/
export interface ServiceRegionConfigurationOptionalParams extends msRest.RequestOptionsBase {
/**
* Request body to get the availability for scheduling orders.
*/
scheduleAvailabilityRequest?: ScheduleAvailabilityRequestUnion;
/**
* Request body to get the transport availability for given sku.
*/
transportAvailabilityRequest?: TransportAvailabilityRequest;
}
/**
* An interface representing DataBoxManagementClientOptions.
*/
export interface DataBoxManagementClientOptions extends AzureServiceClientOptions {
baseUri?: string;
}
/**
* @interface
* Operation Collection.
* @extends Array<Operation>
*/
export interface OperationList extends Array<Operation> {
/**
* Link for the next set of operations.
*/
nextLink?: string;
}
/**
* @interface
* Job Resource Collection
* @extends Array<JobResource>
*/
export interface JobResourceList extends Array<JobResource> {
/**
* Link for the next set of job resources.
*/
nextLink?: string;
}
/**
* @interface
* List of unencrypted credentials for accessing device.
* @extends Array<UnencryptedCredentials>
*/
export interface UnencryptedCredentialsList extends Array<UnencryptedCredentials> {
/**
* Link for the next set of unencrypted credentials.
*/
nextLink?: string;
}
/**
* @interface
* The available skus operation response.
* @extends Array<SkuInformation>
*/
export interface AvailableSkusResult extends Array<SkuInformation> {
/**
* Link for the next set of skus.
*/
nextLink?: string;
}
/**
* Defines values for DataDestinationType.
* Possible values include: 'StorageAccount', 'ManagedDisk'
* @readonly
* @enum {string}
*/
export type DataDestinationType = 'StorageAccount' | 'ManagedDisk';
/**
* Defines values for ShareDestinationFormatType.
* Possible values include: 'UnknownType', 'HCS', 'BlockBlob', 'PageBlob', 'AzureFile',
* 'ManagedDisk'
* @readonly
* @enum {string}
*/
export type ShareDestinationFormatType = 'UnknownType' | 'HCS' | 'BlockBlob' | 'PageBlob' | 'AzureFile' | 'ManagedDisk';
/**
* Defines values for AccessProtocol.
* Possible values include: 'SMB', 'NFS'
* @readonly
* @enum {string}
*/
export type AccessProtocol = 'SMB' | 'NFS';
/**
* Defines values for AddressValidationStatus.
* Possible values include: 'Valid', 'Invalid', 'Ambiguous'
* @readonly
* @enum {string}
*/
export type AddressValidationStatus = 'Valid' | 'Invalid' | 'Ambiguous';
/**
* Defines values for AddressType.
* Possible values include: 'None', 'Residential', 'Commercial'
* @readonly
* @enum {string}
*/
export type AddressType = 'None' | 'Residential' | 'Commercial';
/**
* Defines values for SkuName.
* Possible values include: 'DataBox', 'DataBoxDisk', 'DataBoxHeavy'
* @readonly
* @enum {string}
*/
export type SkuName = 'DataBox' | 'DataBoxDisk' | 'DataBoxHeavy';
/**
* Defines values for SkuDisabledReason.
* Possible values include: 'None', 'Country', 'Region', 'Feature', 'OfferType',
* 'NoSubscriptionInfo'
* @readonly
* @enum {string}
*/
export type SkuDisabledReason = 'None' | 'Country' | 'Region' | 'Feature' | 'OfferType' | 'NoSubscriptionInfo';
/**
* Defines values for NotificationStageName.
* Possible values include: 'DevicePrepared', 'Dispatched', 'Delivered', 'PickedUp', 'AtAzureDC',
* 'DataCopy'
* @readonly
* @enum {string}
*/
export type NotificationStageName = 'DevicePrepared' | 'Dispatched' | 'Delivered' | 'PickedUp' | 'AtAzureDC' | 'DataCopy';
/**
* Defines values for ValidationStatus.
* Possible values include: 'Valid', 'Invalid', 'Skipped'
* @readonly
* @enum {string}
*/
export type ValidationStatus = 'Valid' | 'Invalid' | 'Skipped';
/**
* Defines values for CopyStatus.
* Possible values include: 'NotStarted', 'InProgress', 'Completed', 'CompletedWithErrors',
* 'Failed', 'NotReturned', 'HardwareError', 'DeviceFormatted', 'DeviceMetadataModified',
* 'StorageAccountNotAccessible', 'UnsupportedData'
* @readonly
* @enum {string}
*/
export type CopyStatus = 'NotStarted' | 'InProgress' | 'Completed' | 'CompletedWithErrors' | 'Failed' | 'NotReturned' | 'HardwareError' | 'DeviceFormatted' | 'DeviceMetadataModified' | 'StorageAccountNotAccessible' | 'UnsupportedData';
/**
* Defines values for StageName.
* Possible values include: 'DeviceOrdered', 'DevicePrepared', 'Dispatched', 'Delivered',
* 'PickedUp', 'AtAzureDC', 'DataCopy', 'Completed', 'CompletedWithErrors', 'Cancelled',
* 'Failed_IssueReportedAtCustomer', 'Failed_IssueDetectedAtAzureDC', 'Aborted',
* 'CompletedWithWarnings', 'ReadyToDispatchFromAzureDC', 'ReadyToReceiveAtAzureDC'
* @readonly
* @enum {string}
*/
export type StageName = 'DeviceOrdered' | 'DevicePrepared' | 'Dispatched' | 'Delivered' | 'PickedUp' | 'AtAzureDC' | 'DataCopy' | 'Completed' | 'CompletedWithErrors' | 'Cancelled' | 'Failed_IssueReportedAtCustomer' | 'Failed_IssueDetectedAtAzureDC' | 'Aborted' | 'CompletedWithWarnings' | 'ReadyToDispatchFromAzureDC' | 'ReadyToReceiveAtAzureDC';
/**
* Defines values for StageStatus.
* Possible values include: 'None', 'InProgress', 'Succeeded', 'Failed', 'Cancelled', 'Cancelling',
* 'SucceededWithErrors'
* @readonly
* @enum {string}
*/
export type StageStatus = 'None' | 'InProgress' | 'Succeeded' | 'Failed' | 'Cancelled' | 'Cancelling' | 'SucceededWithErrors';
/**
* Defines values for TransportShipmentTypes.
* Possible values include: 'CustomerManaged', 'MicrosoftManaged'
* @readonly
* @enum {string}
*/
export type TransportShipmentTypes = 'CustomerManaged' | 'MicrosoftManaged';
/**
* Defines values for JobDeliveryType.
* Possible values include: 'NonScheduled', 'Scheduled'
* @readonly
* @enum {string}
*/
export type JobDeliveryType = 'NonScheduled' | 'Scheduled';
/**
* Defines values for OverallValidationStatus.
* Possible values include: 'AllValidToProceed', 'InputsRevisitRequired',
* 'CertainInputValidationsSkipped'
* @readonly
* @enum {string}
*/
export type OverallValidationStatus = 'AllValidToProceed' | 'InputsRevisitRequired' | 'CertainInputValidationsSkipped';
/**
* Contains response data for the list operation.
*/
export type OperationsListResponse = OperationList & {
/**
* 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: OperationList;
};
};
/**
* Contains response data for the listNext operation.
*/
export type OperationsListNextResponse = OperationList & {
/**
* 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: OperationList;
};
};
/**
* Contains response data for the list operation.
*/
export type JobsListResponse = JobResourceList & {
/**
* 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: JobResourceList;
};
};
/**
* Contains response data for the listByResourceGroup operation.
*/
export type JobsListByResourceGroupResponse = JobResourceList & {
/**
* 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: JobResourceList;
};
};
/**
* Contains response data for the get operation.
*/
export type JobsGetResponse = JobResource & {
/**
* 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: JobResource;
};
};
/**
* Contains response data for the create operation.
*/
export type JobsCreateResponse = JobResource & {
/**
* 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: JobResource;
};
};
/**
* Contains response data for the update operation.
*/
export type JobsUpdateResponse = JobResource & {
/**
* 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: JobResource;
};
};
/**
* Contains response data for the bookShipmentPickUp operation.
*/
export type JobsBookShipmentPickUpResponse = ShipmentPickUpResponse & {
/**
* 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: ShipmentPickUpResponse;
};
};
/**
* Contains response data for the listCredentials operation.
*/
export type JobsListCredentialsResponse = UnencryptedCredentialsList & {
/**
* 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: UnencryptedCredentialsList;
};
};
/**
* Contains response data for the beginCreate operation.
*/
export type JobsBeginCreateResponse = JobResource & {
/**
* 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: JobResource;
};
};
/**
* Contains response data for the beginUpdate operation.
*/
export type JobsBeginUpdateResponse = JobResource & {
/**
* 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: JobResource;
};
};
/**
* Contains response data for the listNext operation.
*/
export type JobsListNextResponse = JobResourceList & {
/**
* 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: JobResourceList;
};
};
/**
* Contains response data for the listByResourceGroupNext operation.
*/
export type JobsListByResourceGroupNextResponse = JobResourceList & {
/**
* 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: JobResourceList;
};
};
/**
* Contains response data for the listAvailableSkus operation.
*/
export type ServiceListAvailableSkusResponse = AvailableSkusResult & {
/**
* 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: AvailableSkusResult;
};
};
/**
* Contains response data for the listAvailableSkusByResourceGroup operation.
*/
export type ServiceListAvailableSkusByResourceGroupResponse = AvailableSkusResult & {
/**
* 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: AvailableSkusResult;
};
};
/**
* Contains response data for the validateAddressMethod operation.
*/
export type ServiceValidateAddressMethodResponse = AddressValidationOutput & {
/**
* 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: AddressValidationOutput;
};
};
/**
* Contains response data for the validateInputsByResourceGroup operation.
*/
export type ServiceValidateInputsByResourceGroupResponse = ValidationResponse & {
/**
* 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: ValidationResponse;
};
};
/**
* Contains response data for the validateInputs operation.
*/
export type ServiceValidateInputsResponse = ValidationResponse & {
/**
* 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: ValidationResponse;
};
};
/**
* Contains response data for the regionConfiguration operation.
*/
export type ServiceRegionConfigurationResponse = RegionConfigurationResponse & {
/**
* 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: RegionConfigurationResponse;
};
};
/**
* Contains response data for the listAvailableSkusNext operation.
*/
export type ServiceListAvailableSkusNextResponse = AvailableSkusResult & {
/**
* 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: AvailableSkusResult;
};
};
/**
* Contains response data for the listAvailableSkusByResourceGroupNext operation.
*/
export type ServiceListAvailableSkusByResourceGroupNextResponse = AvailableSkusResult & {
/**
* 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: AvailableSkusResult;
};
}; | the_stack |
import express from 'express'
import fileUpload from 'express-fileupload';
import util from 'util';
import Logger from '../../loaders/logger';
// Config
import { FEATURES } from '../../config';
// Types
import { IFeatures, IDeviceInfo } from '../../types';
const exec = util.promisify(require('child_process').exec);
const api = express.Router(); //Define Express Router
// Define default error message
const DEFAULT_ERROR_MESSAGE = "Error while processing request";
// Define middlewares to use in different endpoints
const defaultMiddlewares = [
express.json(),
express.urlencoded({extended: true})
]
const fileUploadMiddlewares = [
fileUpload()
]
// Define middleware to check if the feature is available
const featureAvailableMiddleware = (featureName: string) => {
return (req: any, res: any, next: any) => {
if (!FEATURES[featureName]){
res.status(400).send(DEFAULT_ERROR_MESSAGE);
}
else {
next();
}
}
}
// Define middleware to check if a feature should be available only for some kind (emulator or real device)
const deviceTypeMiddleware = (allowedType: "REAL_DEVIC" | "EMULATOR") => {
return (req: any, res: any, next: any) => {
const deviceType: "REAL_DEVICE" | "EMULATOR" = process.env.REAL_DEVICE !== undefined ? "REAL_DEVICE" : "EMULATOR";
if (deviceType !== allowedType){
res.status(400).send(DEFAULT_ERROR_MESSAGE);
}
else {
next();
}
}
}
// Helper function to get the adb option to address the right device in adb
const getAdbOption = (): string => {
const type: "Real Device" | "Emulator" = process.env.REAL_DEVICE !== undefined ? "Real Device" : "Emulator";
if (type === "Emulator"){
return "-e"
}
else if (type === "Real Device" && process.env.REAL_DEVICE_SERIAL){
return `-s ${process.env.REAL_DEVICE_SERIAL}`;
}
else {
//If there is more than a device attached it won't work unless SERIAL is specified
return "-d";
}
}
// API
export default (app: express.Router) => {
app.use('/api', api)
/**
* Endpoint for getting info about the available features
*/
api.get('/features', defaultMiddlewares, (req: any, res: any) => {
Logger.info("Received request on /api/features");
const availableFeatures: IFeatures = {
DEVICEINFO: FEATURES.DEVICEINFO,
TERMINAL: FEATURES.TERMINAL,
APK: FEATURES.APK,
SMS: process.env.REAL_DEVICE !== undefined ? false : FEATURES.SMS,
FORWARD: process.env.REAL_DEVICE !== undefined ? false : FEATURES.FORWARD,
REBOOT: process.env.REAL_DEVICE !== undefined ? false : FEATURES.REBOOT,
}
res.send(availableFeatures);
})
/**
* Endpoint for getting device info
*/
api.get('/device', defaultMiddlewares, async (req: any, res: any) => {
Logger.info("Received request on /api/device");
try{
const type = process.env.REAL_DEVICE !== undefined ? "Real Device" : "Emulator";
//Get adb option to address right device when working with more than one
const adbOption = getAdbOption();
const androidVersion = await exec(`adb ${adbOption} shell getprop ro.build.version.release`);
const processor = await exec(`adb ${adbOption} shell getprop ro.product.cpu.abi`);
const device = await exec(`adb ${adbOption} shell getprop ro.product.model`);
const deviceInfo: IDeviceInfo = {
type: FEATURES.DEVICEINFO ? type: "NA",
androidVersion: FEATURES.DEVICEINFO ? androidVersion["stdout"].replace("\r\n",""): "NA",
processor: FEATURES.DEVICEINFO ? processor["stdout"].replace("\r\n",""): "NA",
device: FEATURES.DEVICEINFO ? device["stdout"].replace("\r\n","") : "NA",
}
res.send(deviceInfo);
}
catch (err) {
Logger.error('Error in GET /api/device');
Logger.error(err);
res.status(400).send(DEFAULT_ERROR_MESSAGE);
}
})
/**
* Endpoint for rebooting the device
*/
api.get('/reboot', deviceTypeMiddleware('EMULATOR'), featureAvailableMiddleware('REBOOT'), defaultMiddlewares, async (req: any, res: any) => {
Logger.info("Received request on /api/reboot");
try{
//Get adb option to address right device when working with more than one
const adbOption = getAdbOption();
await exec(`adb ${adbOption} reboot`);
const defaultRes = {
'action': "reboot",
'status': "OK"
}
res.send(defaultRes);
}
catch (err) {
Logger.error('Error in GET /api/reboot');
Logger.error(err);
res.status(400).send(DEFAULT_ERROR_MESSAGE);
}
})
/**
* Endpoint for sending SMS
*/
api.post('/sms', deviceTypeMiddleware('EMULATOR'), featureAvailableMiddleware('SMS'), defaultMiddlewares, async (req: any, res: any) => {
Logger.info("Received request on /api/sms");
/* Get Docker container ID from within container (not needed)
const getDockerContainerIDCmd = "head -1 /proc/self/cgroup|cut -d/ -f3";
const {dockerID, dockerIDStderr} = await exec(getDockerContainerIDCmd);
*/
try{
//Get adb option to address right device when working with more than one
const adbOption = getAdbOption();
const sendSMSCmd = `adb ${adbOption} emu sms send ${req.body.phoneNumber} ${req.body.message}`;
exec(sendSMSCmd);
const defaultRes = {
'action': "sms",
'status': "OK"
}
res.send(defaultRes);
}
catch (err) {
Logger.error('Error in POST /api/sms');
Logger.error(err);
res.status(400).send(DEFAULT_ERROR_MESSAGE);
}
})
/**
* Endpoint for installing APK
*/
api.post('/apk', featureAvailableMiddleware('APK'), fileUploadMiddlewares, async (req: any, res: any) => {
Logger.info("Received request on /api/apk");
try{
const apk = req.files.file;
const mv = util.promisify(apk.mv);
await mv(`/tmp/app.apk`);
//Get adb option to address right device when working with more than one
const adbOption = getAdbOption();
const installAPKCmd = `adb ${adbOption} install /tmp/app.apk`;
await exec(installAPKCmd);
const defaultRes = {
'action': "apk",
'status': "OK"
}
res.send(defaultRes);
}
catch (err) {
Logger.error('Error in POST /api/apk');
Logger.error(err);
res.status(400).send(DEFAULT_ERROR_MESSAGE);
}
})
/**
* Endpoint for Port Forwarding
*/
api.post('/forward', featureAvailableMiddleware('FORWARD'), defaultMiddlewares, async (req: any, res: any) => {
Logger.info("Received request on /api/forward");
try{
const portNumber = req.body.portNumber;
//Get adb option to address right device when working with more than one
const adbOption = getAdbOption();
const adbForwardCmd = `adb ${adbOption} forward tcp:${portNumber} tcp:${portNumber}`;
exec(adbForwardCmd);
const rinetdForwardCmd = `/root/dockerized-android/utils/rinetd_forward.sh ${portNumber}`;
exec(rinetdForwardCmd);
const defaultRes = {
'action': "forward",
'status': "OK",
}
res.send(defaultRes);
}
catch (err) {
Logger.error('Error in POST /api/forward');
Logger.error(err);
res.status(400).send(DEFAULT_ERROR_MESSAGE);
}
})
/**
* Endpoint for Terminal
*/
api.get('/cwd', defaultMiddlewares, async (req: any, res: any) => {
Logger.info("Received request on /api/cwd");
const cwd = process.cwd();
res.send(cwd);
})
api.post('/terminal', featureAvailableMiddleware('TERMINAL'), defaultMiddlewares, async (req: any, res: any) => {
Logger.info("Received request on /api/terminal");
const defaultErrorResponse = {
'action': 'terminal',
'status': 'error',
'output': 'An error has occurred', //The most general error ever
'cwd': process.cwd(),
}
try {
const arg = req.body.arg;
switch(arg[0]){
case 'cd':
if(arg[1]){
process.chdir(arg[1]);
const response = {
'action': 'terminal',
'status': 'ok',
'output': '',
'cwd': process.cwd(),
}
res.send(response)
}
else {
res.send(defaultErrorResponse)
}
break;
default:
const terminalCmd = arg.reduce((acc: string, curr: string) => `${acc} ${curr}`);
const {stdout} = await exec(terminalCmd);
const response = {
'action': 'terminal',
'status': 'ok',
'output': stdout,
'cwd': process.cwd(),
}
res.send(response);
}
}
catch (err){
const errorResponse = {
'action': "terminal",
'status': "error",
'output': err.stderr,
'cwd': process.cwd(),
}
res.send(errorResponse);
}
})
} | the_stack |
import _platform from 'platform'
import cssEscape from 'css.escape'
// input may be undefined, selector-tring, Node, NodeList, HTMLCollection, array of Nodes
// yes, to some extent this is a bad replica of jQuery's constructor function
function nodeArray(input) {
if (!input) {
return []
}
if (Array.isArray(input)) {
return input
}
// instanceof Node - does not work with iframes
if (input.nodeType !== undefined) {
return [input]
}
if (typeof input === 'string') {
input = document.querySelectorAll(input)
}
if (input.length !== undefined) {
return [].slice.call(input, 0)
}
throw new TypeError('unexpected input ' + String(input))
}
function contextToElement(_ref) {
var context = _ref.context,
_ref$label = _ref.label,
label = _ref$label === undefined ? 'context-to-element' : _ref$label,
resolveDocument = _ref.resolveDocument,
defaultToDocument = _ref.defaultToDocument
var element = nodeArray(context)[0]
if (resolveDocument && element && element.nodeType === Node.DOCUMENT_NODE) {
element = element.documentElement
}
if (!element && defaultToDocument) {
return document.documentElement
}
if (!element) {
throw new TypeError(label + ' requires valid options.context')
}
if (
element.nodeType !== Node.ELEMENT_NODE &&
element.nodeType !== Node.DOCUMENT_FRAGMENT_NODE
) {
throw new TypeError(label + ' requires options.context to be an Element')
}
return element
}
function getShadowHost() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context
var element = contextToElement({
label: 'get/shadow-host',
context: context,
})
// walk up to the root
var container = null
while (element) {
container = element
element = element.parentNode
}
// https://developer.mozilla.org/en-US/docs/Web/API/Node.nodeType
// NOTE: Firefox 34 does not expose ShadowRoot.host (but 37 does)
if (
container.nodeType === container.DOCUMENT_FRAGMENT_NODE &&
container.host
) {
// the root is attached to a fragment node that has a host
return container.host
}
return null
}
function getDocument(node) {
if (!node) {
return document
}
if (node.nodeType === Node.DOCUMENT_NODE) {
return node
}
return node.ownerDocument || document
}
function isActiveElement(context) {
var element = contextToElement({
label: 'is/active-element',
resolveDocument: true,
context: context,
})
var _document = getDocument(element)
if (_document.activeElement === element) {
return true
}
var shadowHost = getShadowHost({ context: element })
if (shadowHost && shadowHost.shadowRoot.activeElement === element) {
return true
}
return false
}
// [elem, elem.parent, elem.parent.parent, …, html]
// will not contain the shadowRoot (DOCUMENT_FRAGMENT_NODE) and shadowHost
function getParents() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context
var list = []
var element = contextToElement({
label: 'get/parents',
context: context,
})
while (element) {
list.push(element)
// IE does know support parentElement on SVGElement
element = element.parentNode
if (element && element.nodeType !== Node.ELEMENT_NODE) {
element = null
}
}
return list
}
// Element.prototype.matches may be available at a different name
// https://developer.mozilla.org/en/docs/Web/API/Element/matches
var names = [
'matches',
'webkitMatchesSelector',
'mozMatchesSelector',
'msMatchesSelector',
]
var name = null
function findMethodName(element) {
names.some(function (_name) {
if (!element[_name]) {
return false
}
name = _name
return true
})
}
function elementMatches(element, selector) {
if (!name) {
findMethodName(element)
}
return element[name](selector)
}
// deep clone of original platform
var platform = JSON.parse(JSON.stringify(_platform))
// operating system
var os = platform.os.family || ''
var ANDROID = os === 'Android'
var WINDOWS = os.slice(0, 7) === 'Windows'
var OSX = os === 'OS X'
var IOS = os === 'iOS'
// layout
var BLINK = platform.layout === 'Blink'
var GECKO = platform.layout === 'Gecko'
var TRIDENT = platform.layout === 'Trident'
var EDGE = platform.layout === 'EdgeHTML'
var WEBKIT = platform.layout === 'WebKit'
// browser version (not layout engine version!)
var version = parseFloat(platform.version)
var majorVersion = Math.floor(version)
platform.majorVersion = majorVersion
platform.is = {
// operating system
ANDROID: ANDROID,
WINDOWS: WINDOWS,
OSX: OSX,
IOS: IOS,
// layout
BLINK: BLINK, // "Chrome", "Chrome Mobile", "Opera"
GECKO: GECKO, // "Firefox"
TRIDENT: TRIDENT, // "Internet Explorer"
EDGE: EDGE, // "Microsoft Edge"
WEBKIT: WEBKIT, // "Safari"
// INTERNET EXPLORERS
IE9: TRIDENT && majorVersion === 9,
IE10: TRIDENT && majorVersion === 10,
IE11: TRIDENT && majorVersion === 11,
}
function before() {
var data = {
// remember what had focus to restore after test
activeElement: document.activeElement,
// remember scroll positions to restore after test
windowScrollTop: window.scrollTop,
windowScrollLeft: window.scrollLeft,
bodyScrollTop: document.body.scrollTop,
bodyScrollLeft: document.body.scrollLeft,
}
// wrap tests in an element hidden from screen readers to prevent them
// from announcing focus, which can be quite irritating to the user
var iframe = document.createElement('iframe')
iframe.setAttribute(
'style',
'position:absolute; position:fixed; top:0; left:-2px; width:1px; height:1px; overflow:hidden;'
)
iframe.setAttribute('aria-live', 'off')
iframe.setAttribute('aria-busy', 'true')
iframe.setAttribute('aria-hidden', 'true')
document.body.appendChild(iframe)
var _window = iframe.contentWindow
var _document = _window.document
_document.open()
_document.close()
var wrapper = _document.createElement('div')
_document.body.appendChild(wrapper)
data.iframe = iframe
data.wrapper = wrapper
data.window = _window
data.document = _document
return data
}
// options.element:
// {string} element name
// {function} callback(wrapper, document) to generate an element
// options.mutate: (optional)
// {function} callback(element, wrapper, document) to manipulate element prior to focus-test.
// Can return DOMElement to define focus target (default: element)
// options.validate: (optional)
// {function} callback(element, focusTarget, document) to manipulate test-result
function test(data, options) {
// make sure we operate on a clean slate
data.wrapper.innerHTML = ''
// create dummy element to test focusability of
var element =
typeof options.element === 'string'
? data.document.createElement(options.element)
: options.element(data.wrapper, data.document)
// allow callback to further specify dummy element
// and optionally define element to focus
var focus =
options.mutate && options.mutate(element, data.wrapper, data.document)
if (!focus && focus !== false) {
focus = element
}
// element needs to be part of the DOM to be focusable
!element.parentNode && data.wrapper.appendChild(element)
// test if the element with invalid tabindex can be focused
focus && focus.focus && focus.focus()
// validate test's result
return options.validate
? options.validate(element, focus, data.document)
: data.document.activeElement === focus
}
function after(data) {
// restore focus to what it was before test and cleanup
if (data.activeElement === document.body) {
document.activeElement &&
document.activeElement.blur &&
document.activeElement.blur()
if (platform.is.IE10) {
// IE10 does not redirect focus to <body> when the activeElement is removed
document.body.focus()
}
} else {
data.activeElement && data.activeElement.focus && data.activeElement.focus()
}
document.body.removeChild(data.iframe)
// restore scroll position
window.scrollTop = data.windowScrollTop
window.scrollLeft = data.windowScrollLeft
document.body.scrollTop = data.bodyScrollTop
document.body.scrollLeft = data.bodyScrollLeft
}
function detectFocus(tests) {
var data = before()
var results = {}
Object.keys(tests).map(function (key) {
results[key] = test(data, tests[key])
})
after(data)
return results
}
// this file is overwritten by `npm run build:pre`
var version$1 = '1.4.1'
/*
Facility to cache test results in localStorage.
USAGE:
cache.get('key');
cache.set('key', 'value');
*/
function readLocalStorage(key) {
// allow reading from storage to retrieve previous support results
// even while the document does not have focus
var data = void 0
try {
data = window.localStorage && window.localStorage.getItem(key)
data = data ? JSON.parse(data) : {}
} catch (e) {
data = {}
}
return data
}
function writeLocalStorage(key, value) {
if (!document.hasFocus()) {
// if the document does not have focus when tests are executed, focus() may
// not be handled properly and events may not be dispatched immediately.
// This can happen when a document is reloaded while Developer Tools have focus.
try {
window.localStorage && window.localStorage.removeItem(key)
} catch (e) {
// ignore
}
return
}
try {
window.localStorage &&
window.localStorage.setItem(key, JSON.stringify(value))
} catch (e) {
// ignore
}
}
var userAgent =
(typeof window !== 'undefined' && window.navigator.userAgent) || ''
var cacheKey = 'ally-supports-cache'
var cache = readLocalStorage(cacheKey)
// update the cache if ally or the user agent changed (newer version, etc)
if (cache.userAgent !== userAgent || cache.version !== version$1) {
cache = {}
}
cache.userAgent = userAgent
cache.version = version$1
var cache$1 = {
get: function get() {
return cache
},
set: function set(values) {
Object.keys(values).forEach(function (key) {
cache[key] = values[key]
})
cache.time = new Date().toISOString()
writeLocalStorage(cacheKey, cache)
},
}
function cssShadowPiercingDeepCombinator() {
var combinator = void 0
// see https://dev.w3.org/csswg/css-scoping-1/#deep-combinator
// https://bugzilla.mozilla.org/show_bug.cgi?id=1117572
// https://code.google.com/p/chromium/issues/detail?id=446051
try {
document.querySelector('html >>> :first-child')
combinator = '>>>'
} catch (noArrowArrowArrow) {
try {
// old syntax supported at least up to Chrome 41
// https://code.google.com/p/chromium/issues/detail?id=446051
document.querySelector('html /deep/ :first-child')
combinator = '/deep/'
} catch (noDeep) {
combinator = ''
}
}
return combinator
}
var gif =
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-usemap
var focusAreaImgTabindex = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML =
'<map name="image-map-tabindex-test">' +
'<area shape="rect" coords="63,19,144,45"></map>' +
'<img usemap="#image-map-tabindex-test" tabindex="-1" alt="" src="' +
gif +
'">'
return element.querySelector('area')
},
}
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-usemap
var focusAreaTabindex = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML =
'<map name="image-map-tabindex-test">' +
'<area href="#void" tabindex="-1" shape="rect" coords="63,19,144,45"></map>' +
'<img usemap="#image-map-tabindex-test" alt="" src="' +
gif +
'">'
return false
},
validate: function validate(element, focusTarget, _document) {
if (platform.is.GECKO) {
// fixes https://github.com/medialize/ally.js/issues/35
// Firefox loads the DataURI asynchronously, causing a false-negative
return true
}
var focus = element.querySelector('area')
focus.focus()
return _document.activeElement === focus
},
}
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-usemap
var focusAreaWithoutHref = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML =
'<map name="image-map-area-href-test">' +
'<area shape="rect" coords="63,19,144,45"></map>' +
'<img usemap="#image-map-area-href-test" alt="" src="' +
gif +
'">'
return element.querySelector('area')
},
validate: function validate(element, focusTarget, _document) {
if (platform.is.GECKO) {
// fixes https://github.com/medialize/ally.js/issues/35
// Firefox loads the DataURI asynchronously, causing a false-negative
return true
}
return _document.activeElement === focusTarget
},
}
var focusAudioWithoutControls = {
name: 'can-focus-audio-without-controls',
element: 'audio',
mutate: function mutate(element) {
try {
// invalid media file can trigger warning in console, data-uri to prevent HTTP request
element.setAttribute('src', gif)
} catch (e) {
// IE9 may throw "Error: Not implemented"
}
},
}
var invalidGif =
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ'
// NOTE: https://github.com/medialize/ally.js/issues/35
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-usemap
var focusBrokenImageMap = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML =
'<map name="broken-image-map-test"><area href="#void" shape="rect" coords="63,19,144,45"></map>' +
'<img usemap="#broken-image-map-test" alt="" src="' +
invalidGif +
'">'
return element.querySelector('area')
},
}
// Children of focusable elements with display:flex are focusable in IE10-11
var focusChildrenOfFocusableFlexbox = {
element: 'div',
mutate: function mutate(element) {
element.setAttribute('tabindex', '-1')
element.setAttribute(
'style',
'display: -webkit-flex; display: -ms-flexbox; display: flex;'
)
element.innerHTML = '<span style="display: block;">hello</span>'
return element.querySelector('span')
},
}
// fieldset[tabindex=0][disabled] should not be focusable, but Blink and WebKit disagree
// @specification https://www.w3.org/TR/html5/disabled-elements.html#concept-element-disabled
// @browser-issue Chromium https://crbug.com/453847
// @browser-issue WebKit https://bugs.webkit.org/show_bug.cgi?id=141086
var focusFieldsetDisabled = {
element: 'fieldset',
mutate: function mutate(element) {
element.setAttribute('tabindex', 0)
element.setAttribute('disabled', 'disabled')
},
}
var focusFieldset = {
element: 'fieldset',
mutate: function mutate(element) {
element.innerHTML = '<legend>legend</legend><p>content</p>'
},
}
// elements with display:flex are focusable in IE10-11
var focusFlexboxContainer = {
element: 'span',
mutate: function mutate(element) {
element.setAttribute(
'style',
'display: -webkit-flex; display: -ms-flexbox; display: flex;'
)
element.innerHTML = '<span style="display: block;">hello</span>'
},
}
// form[tabindex=0][disabled] should be focusable as the
// specification doesn't know the disabled attribute on the form element
// @specification https://www.w3.org/TR/html5/forms.html#the-form-element
var focusFormDisabled = {
element: 'form',
mutate: function mutate(element) {
element.setAttribute('tabindex', 0)
element.setAttribute('disabled', 'disabled')
},
}
// NOTE: https://github.com/medialize/ally.js/issues/35
// fixes https://github.com/medialize/ally.js/issues/20
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-ismap
var focusImgIsmap = {
element: 'a',
mutate: function mutate(element) {
element.href = '#void'
element.innerHTML = '<img ismap src="' + gif + '" alt="">'
return element.querySelector('img')
},
}
// NOTE: https://github.com/medialize/ally.js/issues/35
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-usemap
var focusImgUsemapTabindex = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML =
'<map name="image-map-tabindex-test"><area href="#void" shape="rect" coords="63,19,144,45"></map>' +
'<img usemap="#image-map-tabindex-test" tabindex="-1" alt="" ' +
'src="' +
gif +
'">'
return element.querySelector('img')
},
}
var focusInHiddenIframe = {
element: function element(wrapper, _document) {
var iframe = _document.createElement('iframe')
// iframe must be part of the DOM before accessing the contentWindow is possible
wrapper.appendChild(iframe)
// create the iframe's default document (<html><head></head><body></body></html>)
var iframeDocument = iframe.contentWindow.document
iframeDocument.open()
iframeDocument.close()
return iframe
},
mutate: function mutate(iframe) {
iframe.style.visibility = 'hidden'
var iframeDocument = iframe.contentWindow.document
var input = iframeDocument.createElement('input')
iframeDocument.body.appendChild(input)
return input
},
validate: function validate(iframe) {
var iframeDocument = iframe.contentWindow.document
var focus = iframeDocument.querySelector('input')
return iframeDocument.activeElement === focus
},
}
var result = !platform.is.WEBKIT
function focusInZeroDimensionObject() {
return result
}
// Firefox allows *any* value and treats invalid values like tabindex="-1"
// @browser-issue Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054
var focusInvalidTabindex = {
element: 'div',
mutate: function mutate(element) {
element.setAttribute('tabindex', 'invalid-value')
},
}
var focusLabelTabindex = {
element: 'label',
mutate: function mutate(element) {
element.setAttribute('tabindex', '-1')
},
validate: function validate(element, focusTarget, _document) {
// force layout in Chrome 49, otherwise the element won't be focusable
/* eslint-disable no-unused-vars */
var variableToPreventDeadCodeElimination = element.offsetHeight
/* eslint-enable no-unused-vars */
element.focus()
return _document.activeElement === element
},
}
var svg =
'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtb' +
'G5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiBpZD0ic3ZnIj48dGV4dCB4PSIxMCIgeT0iMjAiIGlkPSJ' +
'zdmctbGluay10ZXh0Ij50ZXh0PC90ZXh0Pjwvc3ZnPg=='
// Note: IE10 on BrowserStack does not like this test
var focusObjectSvgHidden = {
element: 'object',
mutate: function mutate(element) {
element.setAttribute('type', 'image/svg+xml')
element.setAttribute('data', svg)
element.setAttribute('width', '200')
element.setAttribute('height', '50')
element.style.visibility = 'hidden'
},
}
// Note: IE10 on BrowserStack does not like this test
var focusObjectSvg = {
name: 'can-focus-object-svg',
element: 'object',
mutate: function mutate(element) {
element.setAttribute('type', 'image/svg+xml')
element.setAttribute('data', svg)
element.setAttribute('width', '200')
element.setAttribute('height', '50')
},
validate: function validate(element, focusTarget, _document) {
if (platform.is.GECKO) {
// Firefox seems to be handling the object creation asynchronously and thereby produces a false negative test result.
// Because we know Firefox is able to focus object elements referencing SVGs, we simply cheat by sniffing the user agent string
return true
}
return _document.activeElement === element
},
}
// Every Environment except IE9 considers SWF objects focusable
var result$1 = !platform.is.IE9
function focusObjectSwf() {
return result$1
}
var focusRedirectImgUsemap = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML =
'<map name="focus-redirect-img-usemap"><area href="#void" shape="rect" coords="63,19,144,45"></map>' +
'<img usemap="#focus-redirect-img-usemap" alt="" ' +
'src="' +
gif +
'">'
// focus the <img>, not the <div>
return element.querySelector('img')
},
validate: function validate(element, focusTarget, _document) {
var target = element.querySelector('area')
return _document.activeElement === target
},
}
// see https://jsbin.com/nenirisage/edit?html,js,console,output
var focusRedirectLegend = {
element: 'fieldset',
mutate: function mutate(element) {
element.innerHTML =
'<legend>legend</legend><input tabindex="-1"><input tabindex="0">'
// take care of focus in validate();
return false
},
validate: function validate(element, focusTarget, _document) {
var focusable = element.querySelector('input[tabindex="-1"]')
var tabbable = element.querySelector('input[tabindex="0"]')
// Firefox requires this test to focus the <fieldset> first, while this is not necessary in
// https://jsbin.com/nenirisage/edit?html,js,console,output
element.focus()
element.querySelector('legend').focus()
return (
(_document.activeElement === focusable && 'focusable') ||
(_document.activeElement === tabbable && 'tabbable') ||
''
)
},
}
// https://github.com/medialize/ally.js/issues/21
var focusScrollBody = {
element: 'div',
mutate: function mutate(element) {
element.setAttribute('style', 'width: 100px; height: 50px; overflow: auto;')
element.innerHTML =
'<div style="width: 500px; height: 40px;">scrollable content</div>'
return element.querySelector('div')
},
}
// https://github.com/medialize/ally.js/issues/21
var focusScrollContainerWithoutOverflow = {
element: 'div',
mutate: function mutate(element) {
element.setAttribute('style', 'width: 100px; height: 50px;')
element.innerHTML =
'<div style="width: 500px; height: 40px;">scrollable content</div>'
},
}
// https://github.com/medialize/ally.js/issues/21
var focusScrollContainer = {
element: 'div',
mutate: function mutate(element) {
element.setAttribute('style', 'width: 100px; height: 50px; overflow: auto;')
element.innerHTML =
'<div style="width: 500px; height: 40px;">scrollable content</div>'
},
}
var focusSummary = {
element: 'details',
mutate: function mutate(element) {
element.innerHTML = '<summary>foo</summary><p>content</p>'
return element.firstElementChild
},
}
function makeFocusableForeignObject() {
var fragment = document.createElement('div')
fragment.innerHTML =
'<svg><foreignObject width="30" height="30">\n <input type="text"/>\n </foreignObject></svg>'
return fragment.firstChild.firstChild
}
function focusSvgForeignObjectHack(element) {
// Edge13, Edge14: foreignObject focus hack
// https://jsbin.com/kunehinugi/edit?html,js,output
// https://jsbin.com/fajagi/3/edit?html,js,output
var isSvgElement =
element.ownerSVGElement || element.nodeName.toLowerCase() === 'svg'
if (!isSvgElement) {
return false
}
// inject and focus an <input> element into the SVG element to receive focus
var foreignObject = makeFocusableForeignObject()
element.appendChild(foreignObject)
var input = foreignObject.querySelector('input')
input.focus()
// upon disabling the activeElement, IE and Edge
// will not shift focus to <body> like all the other
// browsers, but instead find the first focusable
// ancestor and shift focus to that
input.disabled = true
// clean up
element.removeChild(foreignObject)
return true
}
function generate(element) {
return (
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">' +
element +
'</svg>'
)
}
function focus(element) {
if (element.focus) {
return
}
try {
HTMLElement.prototype.focus.call(element)
} catch (e) {
focusSvgForeignObjectHack(element)
}
}
function validate(element, focusTarget, _document) {
focus(focusTarget)
return _document.activeElement === focusTarget
}
var focusSvgFocusableAttribute = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML = generate('<text focusable="true">a</text>')
return element.querySelector('text')
},
validate: validate,
}
var focusSvgTabindexAttribute = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML = generate('<text tabindex="0">a</text>')
return element.querySelector('text')
},
validate: validate,
}
var focusSvgNegativeTabindexAttribute = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML = generate('<text tabindex="-1">a</text>')
return element.querySelector('text')
},
validate: validate,
}
var focusSvgUseTabindex = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML = generate(
[
'<g id="ally-test-target"><a xlink:href="#void"><text>link</text></a></g>',
'<use xlink:href="#ally-test-target" x="0" y="0" tabindex="-1" />',
].join('')
)
return element.querySelector('use')
},
validate: validate,
}
var focusSvgForeignobjectTabindex = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML = generate(
'<foreignObject tabindex="-1"><input type="text" /></foreignObject>'
)
// Safari 8's quersSelector() can't identify foreignObject, but getElementyByTagName() can
return (
element.querySelector('foreignObject') ||
element.getElementsByTagName('foreignObject')[0]
)
},
validate: validate,
}
// Firefox seems to be handling the SVG-document-in-iframe creation asynchronously
// and thereby produces a false negative test result. Thus the test is pointless
// and we resort to UA sniffing once again.
// see http://jsbin.com/vunadohoko/1/edit?js,console,output
var result$2 = Boolean(
platform.is.GECKO &&
typeof SVGElement !== 'undefined' &&
SVGElement.prototype.focus
)
function focusSvgInIframe() {
return result$2
}
var focusSvg = {
element: 'div',
mutate: function mutate(element) {
element.innerHTML = generate('')
return element.firstChild
},
validate: validate,
}
// Firefox allows *any* value and treats invalid values like tabindex="-1"
// @browser-issue Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054
var focusTabindexTrailingCharacters = {
element: 'div',
mutate: function mutate(element) {
element.setAttribute('tabindex', '3x')
},
}
var focusTable = {
element: 'table',
mutate: function mutate(element, wrapper, _document) {
// IE9 has a problem replacing TBODY contents with innerHTML.
// https://stackoverflow.com/a/8097055/515124
// element.innerHTML = '<tr><td>cell</td></tr>';
var fragment = _document.createDocumentFragment()
fragment.innerHTML = '<tr><td>cell</td></tr>'
element.appendChild(fragment)
},
}
var focusVideoWithoutControls = {
element: 'video',
mutate: function mutate(element) {
try {
// invalid media file can trigger warning in console, data-uri to prevent HTTP request
element.setAttribute('src', gif)
} catch (e) {
// IE9 may throw "Error: Not implemented"
}
},
}
// https://jsbin.com/vafaba/3/edit?html,js,console,output
var result$3 = platform.is.GECKO || platform.is.TRIDENT || platform.is.EDGE
function tabsequenceAreaAtImgPosition() {
return result$3
}
var testCallbacks = {
cssShadowPiercingDeepCombinator: cssShadowPiercingDeepCombinator,
focusInZeroDimensionObject: focusInZeroDimensionObject,
focusObjectSwf: focusObjectSwf,
focusSvgInIframe: focusSvgInIframe,
tabsequenceAreaAtImgPosition: tabsequenceAreaAtImgPosition,
}
var testDescriptions = {
focusAreaImgTabindex: focusAreaImgTabindex,
focusAreaTabindex: focusAreaTabindex,
focusAreaWithoutHref: focusAreaWithoutHref,
focusAudioWithoutControls: focusAudioWithoutControls,
focusBrokenImageMap: focusBrokenImageMap,
focusChildrenOfFocusableFlexbox: focusChildrenOfFocusableFlexbox,
focusFieldsetDisabled: focusFieldsetDisabled,
focusFieldset: focusFieldset,
focusFlexboxContainer: focusFlexboxContainer,
focusFormDisabled: focusFormDisabled,
focusImgIsmap: focusImgIsmap,
focusImgUsemapTabindex: focusImgUsemapTabindex,
focusInHiddenIframe: focusInHiddenIframe,
focusInvalidTabindex: focusInvalidTabindex,
focusLabelTabindex: focusLabelTabindex,
focusObjectSvg: focusObjectSvg,
focusObjectSvgHidden: focusObjectSvgHidden,
focusRedirectImgUsemap: focusRedirectImgUsemap,
focusRedirectLegend: focusRedirectLegend,
focusScrollBody: focusScrollBody,
focusScrollContainerWithoutOverflow: focusScrollContainerWithoutOverflow,
focusScrollContainer: focusScrollContainer,
focusSummary: focusSummary,
focusSvgFocusableAttribute: focusSvgFocusableAttribute,
focusSvgTabindexAttribute: focusSvgTabindexAttribute,
focusSvgNegativeTabindexAttribute: focusSvgNegativeTabindexAttribute,
focusSvgUseTabindex: focusSvgUseTabindex,
focusSvgForeignobjectTabindex: focusSvgForeignobjectTabindex,
focusSvg: focusSvg,
focusTabindexTrailingCharacters: focusTabindexTrailingCharacters,
focusTable: focusTable,
focusVideoWithoutControls: focusVideoWithoutControls,
}
function executeTests() {
var results = detectFocus(testDescriptions)
Object.keys(testCallbacks).forEach(function (key) {
results[key] = testCallbacks[key]()
})
return results
}
var supportsCache = null
function _supports() {
if (supportsCache) {
return supportsCache
}
supportsCache = cache$1.get()
if (!supportsCache.time) {
cache$1.set(executeTests())
supportsCache = cache$1.get()
}
return supportsCache
}
var supports = void 0
// https://www.w3.org/TR/html5/infrastructure.html#rules-for-parsing-integers
// NOTE: all browsers agree to allow trailing spaces as well
var validIntegerPatternNoTrailing = /^\s*(-|\+)?[0-9]+\s*$/
var validIntegerPatternWithTrailing = /^\s*(-|\+)?[0-9]+.*$/
function isValidTabindex(context) {
if (!supports) {
supports = _supports()
}
var validIntegerPattern = supports.focusTabindexTrailingCharacters
? validIntegerPatternWithTrailing
: validIntegerPatternNoTrailing
var element = contextToElement({
label: 'is/valid-tabindex',
resolveDocument: true,
context: context,
})
// Edge 14 has a capitalization problem on SVG elements,
// see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9282058/
var hasTabindex = element.hasAttribute('tabindex')
var hasTabIndex = element.hasAttribute('tabIndex')
if (!hasTabindex && !hasTabIndex) {
return false
}
// older Firefox and Internet Explorer don't support tabindex on SVG elements
var isSvgElement =
element.ownerSVGElement || element.nodeName.toLowerCase() === 'svg'
if (isSvgElement && !supports.focusSvgTabindexAttribute) {
return false
}
// @browser-issue Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054
if (supports.focusInvalidTabindex) {
return true
}
// an element matches the tabindex selector even if its value is invalid
var tabindex = element.getAttribute(hasTabindex ? 'tabindex' : 'tabIndex')
// IE11 parses tabindex="" as the value "-32768"
// @browser-issue Trident https://connect.microsoft.com/IE/feedback/details/1072965
if (tabindex === '-32768') {
return false
}
return Boolean(tabindex && validIntegerPattern.test(tabindex))
}
function tabindexValue(element) {
if (!isValidTabindex(element)) {
return null
}
// Edge 14 has a capitalization problem on SVG elements,
// see https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/9282058/
var hasTabindex = element.hasAttribute('tabindex')
var attributeName = hasTabindex ? 'tabindex' : 'tabIndex'
// @browser-issue Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054
var tabindex = parseInt(element.getAttribute(attributeName), 10)
return isNaN(tabindex) ? -1 : tabindex
}
// this is a shared utility file for focus-relevant.js and tabbable.js
// separate testing of this file's functions is not necessary,
// as they're implicitly tested by way of the consumers
function isUserModifyWritable(style) {
// https://www.w3.org/TR/1999/WD-css3-userint-19990916#user-modify
// https://github.com/medialize/ally.js/issues/17
var userModify = style.webkitUserModify || ''
return Boolean(userModify && userModify.indexOf('write') !== -1)
}
function hasCssOverflowScroll(style) {
return [
style.getPropertyValue('overflow'),
style.getPropertyValue('overflow-x'),
style.getPropertyValue('overflow-y'),
].some(function (overflow) {
return overflow === 'auto' || overflow === 'scroll'
})
}
function hasCssDisplayFlex(style) {
return style.display.indexOf('flex') > -1
}
function isScrollableContainer(element, nodeName, parentNodeName, parentStyle) {
if (nodeName !== 'div' && nodeName !== 'span') {
// Internet Explorer advances scrollable containers and bodies to focusable
// only if the scrollable container is <div> or <span> - this does *not*
// happen for <section>, <article>, …
return false
}
if (
parentNodeName &&
parentNodeName !== 'div' &&
parentNodeName !== 'span' &&
!hasCssOverflowScroll(parentStyle)
) {
return false
}
return (
element.offsetHeight < element.scrollHeight ||
element.offsetWidth < element.scrollWidth
)
}
var supports$1 = void 0
function isFocusRelevantRules() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context,
_ref$except = _ref.except,
except =
_ref$except === undefined
? {
flexbox: false,
scrollable: false,
shadow: false,
}
: _ref$except
if (!supports$1) {
supports$1 = _supports()
}
var element = contextToElement({
label: 'is/focus-relevant',
resolveDocument: true,
context: context,
})
if (!except.shadow && element.shadowRoot) {
// a ShadowDOM host receives focus when the focus moves to its content
return true
}
var nodeName = element.nodeName.toLowerCase()
if (nodeName === 'input' && element.type === 'hidden') {
// input[type="hidden"] supports.cannot be focused
return false
}
if (
nodeName === 'input' ||
nodeName === 'select' ||
nodeName === 'button' ||
nodeName === 'textarea'
) {
return true
}
if (nodeName === 'legend' && supports$1.focusRedirectLegend) {
// specifics filtered in is/focusable
return true
}
if (nodeName === 'label') {
// specifics filtered in is/focusable
return true
}
if (nodeName === 'area') {
// specifics filtered in is/focusable
return true
}
if (nodeName === 'a' && element.hasAttribute('href')) {
return true
}
if (nodeName === 'object' && element.hasAttribute('usemap')) {
// object[usemap] is not focusable in any browser
return false
}
if (nodeName === 'object') {
var svgType = element.getAttribute('type')
if (!supports$1.focusObjectSvg && svgType === 'image/svg+xml') {
// object[type="image/svg+xml"] is not focusable in Internet Explorer
return false
} else if (
!supports$1.focusObjectSwf &&
svgType === 'application/x-shockwave-flash'
) {
// object[type="application/x-shockwave-flash"] is not focusable in Internet Explorer 9
return false
}
}
if (nodeName === 'iframe' || nodeName === 'object') {
// browsing context containers
return true
}
if (nodeName === 'embed' || nodeName === 'keygen') {
// embed is considered focus-relevant but not focusable
// see https://github.com/medialize/ally.js/issues/82
return true
}
if (element.hasAttribute('contenteditable')) {
// also see CSS property user-modify below
return true
}
if (
nodeName === 'audio' &&
(supports$1.focusAudioWithoutControls || element.hasAttribute('controls'))
) {
return true
}
if (
nodeName === 'video' &&
(supports$1.focusVideoWithoutControls || element.hasAttribute('controls'))
) {
return true
}
if (supports$1.focusSummary && nodeName === 'summary') {
return true
}
var validTabindex = isValidTabindex(element)
if (nodeName === 'img' && element.hasAttribute('usemap')) {
// Gecko, Trident and Edge do not allow an image with an image map and tabindex to be focused,
// it appears the tabindex is overruled so focus is still forwarded to the <map>
return (
(validTabindex && supports$1.focusImgUsemapTabindex) ||
supports$1.focusRedirectImgUsemap
)
}
if (supports$1.focusTable && (nodeName === 'table' || nodeName === 'td')) {
// IE10-11 supports.can focus <table> and <td>
return true
}
if (supports$1.focusFieldset && nodeName === 'fieldset') {
// IE10-11 supports.can focus <fieldset>
return true
}
var isSvgElement = nodeName === 'svg'
var isSvgContent = element.ownerSVGElement
var focusableAttribute = element.getAttribute('focusable')
var tabindex = tabindexValue(element)
if (
nodeName === 'use' &&
tabindex !== null &&
!supports$1.focusSvgUseTabindex
) {
// <use> cannot be made focusable by adding a tabindex attribute anywhere but Blink and WebKit
return false
}
if (nodeName === 'foreignobject') {
// <use> can only be made focusable in Blink and WebKit
return tabindex !== null && supports$1.focusSvgForeignobjectTabindex
}
if (elementMatches(element, 'svg a') && element.hasAttribute('xlink:href')) {
return true
}
if (
(isSvgElement || isSvgContent) &&
element.focus &&
!supports$1.focusSvgNegativeTabindexAttribute &&
tabindex < 0
) {
// Firefox 51 and 52 treat any natively tabbable SVG element with
// tabindex="-1" as tabbable and everything else as inert
// see https://bugzilla.mozilla.org/show_bug.cgi?id=1302340
return false
}
if (isSvgElement) {
return (
validTabindex ||
supports$1.focusSvg ||
supports$1.focusSvgInIframe ||
// Internet Explorer understands the focusable attribute introduced in SVG Tiny 1.2
Boolean(
supports$1.focusSvgFocusableAttribute &&
focusableAttribute &&
focusableAttribute === 'true'
)
)
}
if (isSvgContent) {
if (supports$1.focusSvgTabindexAttribute && validTabindex) {
return true
}
if (supports$1.focusSvgFocusableAttribute) {
// Internet Explorer understands the focusable attribute introduced in SVG Tiny 1.2
return focusableAttribute === 'true'
}
}
// https://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute
if (validTabindex) {
return true
}
var style = window.getComputedStyle(element, null)
if (isUserModifyWritable(style)) {
return true
}
if (
supports$1.focusImgIsmap &&
nodeName === 'img' &&
element.hasAttribute('ismap')
) {
// IE10-11 considers the <img> in <a href><img ismap> focusable
// https://github.com/medialize/ally.js/issues/20
var hasLinkParent = getParents({ context: element }).some(function (
parent
) {
return (
parent.nodeName.toLowerCase() === 'a' && parent.hasAttribute('href')
)
})
if (hasLinkParent) {
return true
}
}
// https://github.com/medialize/ally.js/issues/21
if (!except.scrollable && supports$1.focusScrollContainer) {
if (supports$1.focusScrollContainerWithoutOverflow) {
// Internet Explorer does will consider the scrollable area focusable
// if the element is a <div> or a <span> and it is in fact scrollable,
// regardless of the CSS overflow property
if (isScrollableContainer(element, nodeName)) {
return true
}
} else if (hasCssOverflowScroll(style)) {
// Firefox requires proper overflow setting, IE does not necessarily
// https://developer.mozilla.org/en-US/docs/Web/CSS/overflow
return true
}
}
if (
!except.flexbox &&
supports$1.focusFlexboxContainer &&
hasCssDisplayFlex(style)
) {
// elements with display:flex are focusable in IE10-11
return true
}
var parent = element.parentElement
if (!except.scrollable && parent) {
var parentNodeName = parent.nodeName.toLowerCase()
var parentStyle = window.getComputedStyle(parent, null)
if (
supports$1.focusScrollBody &&
isScrollableContainer(parent, nodeName, parentNodeName, parentStyle)
) {
// scrollable bodies are focusable Internet Explorer
// https://github.com/medialize/ally.js/issues/21
return true
}
// Children of focusable elements with display:flex are focusable in IE10-11
if (supports$1.focusChildrenOfFocusableFlexbox) {
if (hasCssDisplayFlex(parentStyle)) {
return true
}
}
}
// NOTE: elements marked as inert are not focusable,
// but that property is not exposed to the DOM
// https://www.w3.org/TR/html5/editing.html#inert
return false
}
// bind exceptions to an iterator callback
isFocusRelevantRules.except = function () {
var except =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}
var isFocusRelevant = function isFocusRelevant(context) {
return isFocusRelevantRules({
context: context,
except: except,
})
}
isFocusRelevant.rules = isFocusRelevantRules
return isFocusRelevant
}
// provide isFocusRelevant(context) as default iterator callback
var isFocusRelevant = isFocusRelevantRules.except({})
function findIndex(array, callback) {
// attempt to use native or polyfilled Array#findIndex first
if (array.findIndex) {
return array.findIndex(callback)
}
var length = array.length
// shortcut if the array is empty
if (length === 0) {
return -1
}
// otherwise loop over array
for (var i = 0; i < length; i++) {
if (callback(array[i], i, array)) {
return i
}
}
return -1
}
function getContentDocument(node) {
try {
// works on <object> and <iframe>
return (
node.contentDocument ||
// works on <object> and <iframe>
(node.contentWindow && node.contentWindow.document) ||
// works on <object> and <iframe> that contain SVG
(node.getSVGDocument && node.getSVGDocument()) ||
null
)
} catch (e) {
// SecurityError: Failed to read the 'contentDocument' property from 'HTMLObjectElement'
// also IE may throw member not found exception e.g. on <object type="image/png">
return null
}
}
function getWindow(node) {
var _document = getDocument(node)
return _document.defaultView || window
}
var shadowPrefix = void 0
function selectInShadows(selector) {
if (typeof shadowPrefix !== 'string') {
var operator = cssShadowPiercingDeepCombinator()
if (operator) {
shadowPrefix = ', html ' + operator + ' '
}
}
if (!shadowPrefix) {
return selector
}
return (
selector +
shadowPrefix +
selector
.replace(/\s*,\s*/g, ',')
.split(',')
.join(shadowPrefix)
)
}
var selector = void 0
function findDocumentHostElement(_window) {
if (!selector) {
selector = selectInShadows('object, iframe')
}
if (_window._frameElement !== undefined) {
return _window._frameElement
}
_window._frameElement = null
var potentialHosts = _window.parent.document.querySelectorAll(selector)
;[].some.call(potentialHosts, function (element) {
var _document = getContentDocument(element)
if (_document !== _window.document) {
return false
}
_window._frameElement = element
return true
})
return _window._frameElement
}
function getFrameElement(element) {
var _window = getWindow(element)
if (!_window.parent || _window.parent === _window) {
// if there is no parent browsing context,
// we're not going to get a frameElement either way
return null
}
try {
// see https://developer.mozilla.org/en-US/docs/Web/API/Window/frameElement
// does not work within <embed> anywhere, and not within in <object> in IE
return _window.frameElement || findDocumentHostElement(_window)
} catch (e) {
return null
}
}
// https://www.w3.org/TR/html5/rendering.html#being-rendered
// <area> is not rendered, but we *consider* it visible to simplfiy this function's usage
var notRenderedElementsPattern = /^(area)$/
function computedStyle(element, property) {
return window.getComputedStyle(element, null).getPropertyValue(property)
}
function notDisplayed(_path) {
return _path.some(function (element) {
// display:none is not visible (optimized away at layout)
return computedStyle(element, 'display') === 'none'
})
}
function notVisible(_path) {
// https://github.com/jquery/jquery-ui/blob/master/ui/core.js#L109-L114
// NOTE: a nested element can reverse visibility:hidden|collapse by explicitly setting visibility:visible
// NOTE: visibility can be ["", "visible", "hidden", "collapse"]
var hidden = findIndex(_path, function (element) {
var visibility = computedStyle(element, 'visibility')
return visibility === 'hidden' || visibility === 'collapse'
})
if (hidden === -1) {
// there is no hidden element
return false
}
var visible = findIndex(_path, function (element) {
return computedStyle(element, 'visibility') === 'visible'
})
if (visible === -1) {
// there is no visible element (but a hidden element)
return true
}
if (hidden < visible) {
// there is a hidden element and it's closer than the first visible element
return true
}
// there may be a hidden element, but the closest element is visible
return false
}
function collapsedParent(_path) {
var offset = 1
if (_path[0].nodeName.toLowerCase() === 'summary') {
offset = 2
}
return _path.slice(offset).some(function (element) {
// "content children" of a closed details element are not visible
return (
element.nodeName.toLowerCase() === 'details' && element.open === false
)
})
}
function isVisibleRules() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context,
_ref$except = _ref.except,
except =
_ref$except === undefined
? {
notRendered: false,
cssDisplay: false,
cssVisibility: false,
detailsElement: false,
browsingContext: false,
}
: _ref$except
var element = contextToElement({
label: 'is/visible',
resolveDocument: true,
context: context,
})
var nodeName = element.nodeName.toLowerCase()
if (!except.notRendered && notRenderedElementsPattern.test(nodeName)) {
return true
}
var _path = getParents({ context: element })
// in Internet Explorer <audio> has a default display: none, where others have display: inline
// but IE allows focusing <audio style="display:none">, but not <div display:none><audio>
// this is irrelevant to other browsers, as the controls attribute is required to make <audio> focusable
var isAudioWithoutControls =
nodeName === 'audio' && !element.hasAttribute('controls')
if (
!except.cssDisplay &&
notDisplayed(isAudioWithoutControls ? _path.slice(1) : _path)
) {
return false
}
if (!except.cssVisibility && notVisible(_path)) {
return false
}
if (!except.detailsElement && collapsedParent(_path)) {
return false
}
if (!except.browsingContext) {
// elements within a browsing context are affected by the
// browsing context host element's visibility and tabindex
var frameElement = getFrameElement(element)
var _isVisible = isVisibleRules.except(except)
if (frameElement && !_isVisible(frameElement)) {
return false
}
}
return true
}
// bind exceptions to an iterator callback
isVisibleRules.except = function () {
var except =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}
var isVisible = function isVisible(context) {
return isVisibleRules({
context: context,
except: except,
})
}
isVisible.rules = isVisibleRules
return isVisible
}
// provide isVisible(context) as default iterator callback
var isVisible = isVisibleRules.except({})
function getMapByName(name, _document) {
// apparently getElementsByName() also considers id attribute in IE & opera
// https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName
var map = _document.querySelector('map[name="' + cssEscape(name) + '"]')
return map || null
}
function getImageOfArea(element) {
var map = element.parentElement
if (!map.name || map.nodeName.toLowerCase() !== 'map') {
return null
}
// NOTE: image maps can also be applied to <object> with image content,
// but no browser supports this at the moment
// HTML5 specifies HTMLMapElement.images to be an HTMLCollection of all
// <img> and <object> referencing the <map> element, but no browser implements this
// https://www.w3.org/TR/html5/embedded-content-0.html#the-map-element
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLMapElement
// the image must be valid and loaded for the map to take effect
var _document = getDocument(element)
return (
_document.querySelector('img[usemap="#' + cssEscape(map.name) + '"]') ||
null
)
}
var supports$2 = void 0
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/map
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-usemap
// https://github.com/jquery/jquery-ui/blob/master/ui/core.js#L88-L107
function isValidArea(context) {
if (!supports$2) {
supports$2 = _supports()
}
var element = contextToElement({
label: 'is/valid-area',
context: context,
})
var nodeName = element.nodeName.toLowerCase()
if (nodeName !== 'area') {
return false
}
var hasTabindex = element.hasAttribute('tabindex')
if (!supports$2.focusAreaTabindex && hasTabindex) {
// Blink and WebKit do not consider <area tabindex="-1" href="#void"> focusable
return false
}
var img = getImageOfArea(element)
if (!img || !isVisible(img)) {
return false
}
// Firefox only allows fully loaded images to reference image maps
// https://stereochro.me/ideas/detecting-broken-images-js
if (
!supports$2.focusBrokenImageMap &&
(!img.complete ||
!img.naturalHeight ||
img.offsetWidth <= 0 ||
img.offsetHeight <= 0)
) {
return false
}
// Firefox supports.can focus area elements even if they don't have an href attribute
if (!supports$2.focusAreaWithoutHref && !element.href) {
// Internet explorer supports.can focus area elements without href if either
// the area element or the image element has a tabindex attribute
return (
(supports$2.focusAreaTabindex && hasTabindex) ||
(supports$2.focusAreaImgTabindex && img.hasAttribute('tabindex'))
)
}
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-usemap
var childOfInteractive = getParents({ context: img })
.slice(1)
.some(function (_element) {
var name = _element.nodeName.toLowerCase()
return name === 'button' || name === 'a'
})
if (childOfInteractive) {
return false
}
return true
}
var supports$3 = void 0
// https://www.w3.org/TR/html5/disabled-elements.html#concept-element-disabled
var disabledElementsPattern = void 0
var disabledElements = {
input: true,
select: true,
textarea: true,
button: true,
fieldset: true,
form: true,
}
function isNativeDisabledSupported(context) {
if (!supports$3) {
supports$3 = _supports()
if (supports$3.focusFieldsetDisabled) {
delete disabledElements.fieldset
}
if (supports$3.focusFormDisabled) {
delete disabledElements.form
}
disabledElementsPattern = new RegExp(
'^(' + Object.keys(disabledElements).join('|') + ')$'
)
}
var element = contextToElement({
label: 'is/native-disabled-supported',
context: context,
})
var nodeName = element.nodeName.toLowerCase()
return Boolean(disabledElementsPattern.test(nodeName))
}
var supports$4 = void 0
function isDisabledFieldset(element) {
var nodeName = element.nodeName.toLowerCase()
return nodeName === 'fieldset' && element.disabled
}
function isDisabledForm(element) {
var nodeName = element.nodeName.toLowerCase()
return nodeName === 'form' && element.disabled
}
function isDisabled(context) {
if (!supports$4) {
supports$4 = _supports()
}
var element = contextToElement({
label: 'is/disabled',
context: context,
})
if (element.hasAttribute('data-ally-disabled')) {
// treat ally's element/disabled like the DOM native element.disabled
return true
}
if (!isNativeDisabledSupported(element)) {
// non-form elements do not support the disabled attribute
return false
}
if (element.disabled) {
// the element itself is disabled
return true
}
var parents = getParents({ context: element })
if (parents.some(isDisabledFieldset)) {
// a parental <fieldset> is disabld and inherits the state onto this element
return true
}
if (!supports$4.focusFormDisabled && parents.some(isDisabledForm)) {
// a parental <form> is disabld and inherits the state onto this element
return true
}
return false
}
function isOnlyTabbableRules() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context,
_ref$except = _ref.except,
except =
_ref$except === undefined
? {
onlyFocusableBrowsingContext: false,
visible: false,
}
: _ref$except
var element = contextToElement({
label: 'is/only-tabbable',
resolveDocument: true,
context: context,
})
if (!except.visible && !isVisible(element)) {
return false
}
if (
!except.onlyFocusableBrowsingContext &&
(platform.is.GECKO || platform.is.TRIDENT || platform.is.EDGE)
) {
var frameElement = getFrameElement(element)
if (frameElement) {
if (tabindexValue(frameElement) < 0) {
// iframe[tabindex="-1"] and object[tabindex="-1"] inherit the
// tabbable demotion onto elements of their browsing contexts
return false
}
}
}
var nodeName = element.nodeName.toLowerCase()
var tabindex = tabindexValue(element)
if (nodeName === 'label' && platform.is.GECKO) {
// Firefox cannot focus, but tab to: label[tabindex=0]
return tabindex !== null && tabindex >= 0
}
// SVG Elements were keyboard focusable but not script focusable before Firefox 51.
// Firefox 51 added the focus management DOM API (.focus and .blur) to SVGElement,
// see https://bugzilla.mozilla.org/show_bug.cgi?id=778654
if (platform.is.GECKO && element.ownerSVGElement && !element.focus) {
if (nodeName === 'a' && element.hasAttribute('xlink:href')) {
// any focusable child of <svg> cannot be focused, but tabbed to
if (platform.is.GECKO) {
return true
}
}
}
return false
}
// bind exceptions to an iterator callback
isOnlyTabbableRules.except = function () {
var except =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}
var isOnlyTabbable = function isOnlyTabbable(context) {
return isOnlyTabbableRules({
context: context,
except: except,
})
}
isOnlyTabbable.rules = isOnlyTabbableRules
return isOnlyTabbable
}
// provide isOnlyTabbable(context) as default iterator callback
var isOnlyTabbable = isOnlyTabbableRules.except({})
var supports$5 = void 0
function isOnlyFocusRelevant(element) {
var nodeName = element.nodeName.toLowerCase()
if (nodeName === 'embed' || nodeName === 'keygen') {
// embed is considered focus-relevant but not focusable
// see https://github.com/medialize/ally.js/issues/82
return true
}
var _tabindex = tabindexValue(element)
if (element.shadowRoot && _tabindex === null) {
// ShadowDOM host elements *may* receive focus
// even though they are not considered focuable
return true
}
if (nodeName === 'label') {
// <label tabindex="0"> is only tabbable in Firefox, not script-focusable
// there's no way to make an element focusable other than by adding a tabindex,
// and focus behavior of the label element seems hard-wired to ignore tabindex
// in some browsers (like Gecko, Blink and WebKit)
return !supports$5.focusLabelTabindex || _tabindex === null
}
if (nodeName === 'legend') {
return _tabindex === null
}
if (
supports$5.focusSvgFocusableAttribute &&
(element.ownerSVGElement || nodeName === 'svg')
) {
// Internet Explorer understands the focusable attribute introduced in SVG Tiny 1.2
var focusableAttribute = element.getAttribute('focusable')
return focusableAttribute && focusableAttribute === 'false'
}
if (nodeName === 'img' && element.hasAttribute('usemap')) {
// Gecko, Trident and Edge do not allow an image with an image map and tabindex to be focused,
// it appears the tabindex is overruled so focus is still forwarded to the <map>
return _tabindex === null || !supports$5.focusImgUsemapTabindex
}
if (nodeName === 'area') {
// all <area>s are considered relevant,
// but only the valid <area>s are focusable
return !isValidArea(element)
}
return false
}
function isFocusableRules() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context,
_ref$except = _ref.except,
except =
_ref$except === undefined
? {
disabled: false,
visible: false,
onlyTabbable: false,
}
: _ref$except
if (!supports$5) {
supports$5 = _supports()
}
var _isOnlyTabbable = isOnlyTabbable.rules.except({
onlyFocusableBrowsingContext: true,
visible: except.visible,
})
var element = contextToElement({
label: 'is/focusable',
resolveDocument: true,
context: context,
})
var focusRelevant = isFocusRelevant.rules({
context: element,
except: except,
})
if (!focusRelevant || isOnlyFocusRelevant(element)) {
return false
}
if (!except.disabled && isDisabled(element)) {
return false
}
if (!except.onlyTabbable && _isOnlyTabbable(element)) {
// some elements may be keyboard focusable, but not script focusable
return false
}
// elements that are not rendered, cannot be focused
if (!except.visible) {
var visibilityOptions = {
context: element,
except: {},
}
if (supports$5.focusInHiddenIframe) {
// WebKit and Blink can focus content in hidden <iframe> and <object>
visibilityOptions.except.browsingContext = true
}
if (supports$5.focusObjectSvgHidden) {
// Blink allows focusing the object element, even if it has visibility: hidden;
// @browser-issue Blink https://code.google.com/p/chromium/issues/detail?id=586191
var _nodeName2 = element.nodeName.toLowerCase()
if (_nodeName2 === 'object') {
visibilityOptions.except.cssVisibility = true
}
}
if (!isVisible.rules(visibilityOptions)) {
return false
}
}
var frameElement = getFrameElement(element)
if (frameElement) {
var _nodeName = frameElement.nodeName.toLowerCase()
if (_nodeName === 'object' && !supports$5.focusInZeroDimensionObject) {
if (!frameElement.offsetWidth || !frameElement.offsetHeight) {
// WebKit can not focus content in <object> if it doesn't have dimensions
return false
}
}
}
var nodeName = element.nodeName.toLowerCase()
if (
nodeName === 'svg' &&
supports$5.focusSvgInIframe &&
!frameElement &&
element.getAttribute('tabindex') === null
) {
return false
}
return true
}
// bind exceptions to an iterator callback
isFocusableRules.except = function () {
var except =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}
var isFocusable = function isFocusable(context) {
return isFocusableRules({
context: context,
except: except,
})
}
isFocusable.rules = isFocusableRules
return isFocusable
}
// provide isFocusRelevant(context) as default iterator callback
var isFocusable = isFocusableRules.except({})
function createFilter(condition) {
// see https://developer.mozilla.org/en-US/docs/Web/API/NodeFilter
var filter = function filter(node) {
if (node.shadowRoot) {
// return ShadowRoot elements regardless of them being focusable,
// so they can be walked recursively later
return NodeFilter.FILTER_ACCEPT
}
if (condition(node)) {
// finds elements that could have been found by document.querySelectorAll()
return NodeFilter.FILTER_ACCEPT
}
return NodeFilter.FILTER_SKIP
}
// IE requires a function, Browsers require {acceptNode: function}
// see http://www.bennadel.com/blog/2607-finding-html-comment-nodes-in-the-dom-using-treewalker.htm
filter.acceptNode = filter
return filter
}
var PossiblyFocusableFilter = createFilter(isFocusRelevant)
function queryFocusableStrict() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context,
includeContext = _ref.includeContext,
includeOnlyTabbable = _ref.includeOnlyTabbable,
strategy = _ref.strategy
if (!context) {
context = document.documentElement
}
var _isFocusable = isFocusable.rules.except({
onlyTabbable: includeOnlyTabbable,
})
var _document = getDocument(context)
// see https://developer.mozilla.org/en-US/docs/Web/API/Document/createTreeWalker
var walker = _document.createTreeWalker(
// root element to start search in
context,
// element type filter
NodeFilter.SHOW_ELEMENT,
// custom NodeFilter filter
strategy === 'all' ? PossiblyFocusableFilter : createFilter(_isFocusable),
// deprecated, but IE requires it
false
)
var list = []
while (walker.nextNode()) {
if (walker.currentNode.shadowRoot) {
if (_isFocusable(walker.currentNode)) {
list.push(walker.currentNode)
}
list = list.concat(
queryFocusableStrict({
context: walker.currentNode.shadowRoot,
includeOnlyTabbable: includeOnlyTabbable,
strategy: strategy,
})
)
} else {
list.push(walker.currentNode)
}
}
// add context if requested and focusable
if (includeContext) {
if (strategy === 'all') {
if (isFocusRelevant(context)) {
list.unshift(context)
}
} else if (_isFocusable(context)) {
list.unshift(context)
}
}
return list
}
// NOTE: this selector MUST *never* be used directly,
var supports$6 = void 0
var selector$1 = void 0
function selector$2() {
if (!supports$6) {
supports$6 = _supports()
}
if (typeof selector$1 === 'string') {
return selector$1
}
// https://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute
selector$1 =
'' +
// IE11 supports.can focus <table> and <td>
(supports$6.focusTable ? 'table, td,' : '') +
// IE11 supports.can focus <fieldset>
(supports$6.focusFieldset ? 'fieldset,' : '') +
// Namespace problems of [xlink:href] explained in https://stackoverflow.com/a/23047888/515124
// svg a[*|href] does not match in IE9, but since we're filtering
// through is/focusable we can include all <a> from SVG
'svg a,' +
// may behave as 'svg, svg *,' in chrome as *every* svg element with a focus event listener is focusable
// navigational elements
'a[href],' +
// validity determined by is/valid-area.js
'area[href],' +
// validity determined by is/disabled.js
'input, select, textarea, button,' +
// browsing context containers
'iframe, object, embed,' +
// interactive content
'keygen,' +
(supports$6.focusAudioWithoutControls ? 'audio,' : 'audio[controls],') +
(supports$6.focusVideoWithoutControls ? 'video,' : 'video[controls],') +
(supports$6.focusSummary ? 'summary,' : '') +
// validity determined by is/valid-tabindex.js
'[tabindex],' +
// editing hosts
'[contenteditable]'
// where ShadowDOM is supported, we also want the shadowed focusable elements (via ">>>" or "/deep/")
selector$1 = selectInShadows(selector$1)
return selector$1
}
function queryFocusableQuick() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context,
includeContext = _ref.includeContext,
includeOnlyTabbable = _ref.includeOnlyTabbable
var _selector = selector$2()
var elements = context.querySelectorAll(_selector)
// the selector potentially matches more than really is focusable
var _isFocusable = isFocusable.rules.except({
onlyTabbable: includeOnlyTabbable,
})
var result = [].filter.call(elements, _isFocusable)
// add context if requested and focusable
if (includeContext && _isFocusable(context)) {
result.unshift(context)
}
return result
}
function queryFocusable() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context,
includeContext = _ref.includeContext,
includeOnlyTabbable = _ref.includeOnlyTabbable,
_ref$strategy = _ref.strategy,
strategy = _ref$strategy === undefined ? 'quick' : _ref$strategy
var element = contextToElement({
label: 'query/focusable',
resolveDocument: true,
defaultToDocument: true,
context: context,
})
var options = {
context: element,
includeContext: includeContext,
includeOnlyTabbable: includeOnlyTabbable,
strategy: strategy,
}
if (strategy === 'quick') {
return queryFocusableQuick(options)
} else if (strategy === 'strict' || strategy === 'all') {
return queryFocusableStrict(options)
}
throw new TypeError(
'query/focusable requires option.strategy to be one of ["quick", "strict", "all"]'
)
}
var supports$7 = void 0
// Internet Explorer 11 considers fieldset, table, td focusable, but not tabbable
// Internet Explorer 11 considers body to have [tabindex=0], but does not allow tabbing to it
var focusableElementsPattern = /^(fieldset|table|td|body)$/
function isTabbableRules() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context,
_ref$except = _ref.except,
except =
_ref$except === undefined
? {
flexbox: false,
scrollable: false,
shadow: false,
visible: false,
onlyTabbable: false,
}
: _ref$except
if (!supports$7) {
supports$7 = _supports()
}
var element = contextToElement({
label: 'is/tabbable',
resolveDocument: true,
context: context,
})
if (platform.is.BLINK && platform.is.ANDROID && platform.majorVersion > 42) {
// External keyboard support worked fine in CHrome 42, but stopped working in Chrome 45.
// The on-screen keyboard does not provide a way to focus the next input element (like iOS does).
// That leaves us with no option to advance focus by keyboard, ergo nothing is tabbable (keyboard focusable).
return false
}
var frameElement = getFrameElement(element)
if (frameElement) {
if (platform.is.WEBKIT && platform.is.IOS) {
// iOS only does not consider anything from another browsing context keyboard focusable
return false
}
// iframe[tabindex="-1"] and object[tabindex="-1"] inherit the
// tabbable demotion onto elements of their browsing contexts
if (tabindexValue(frameElement) < 0) {
return false
}
if (
!except.visible &&
(platform.is.BLINK || platform.is.WEBKIT) &&
!isVisible(frameElement)
) {
// Blink and WebKit consider elements in hidden browsing contexts focusable, but not tabbable
return false
}
// Webkit and Blink don't consider anything in <object> tabbable
// Blink fixed that fixed in Chrome 54, Opera 41
var frameNodeName = frameElement.nodeName.toLowerCase()
if (frameNodeName === 'object') {
var isFixedBlink =
(platform.name === 'Chrome' && platform.majorVersion >= 54) ||
(platform.name === 'Opera' && platform.majorVersion >= 41)
if (platform.is.WEBKIT || (platform.is.BLINK && !isFixedBlink)) {
return false
}
}
}
var nodeName = element.nodeName.toLowerCase()
var _tabindex = tabindexValue(element)
var tabindex = _tabindex === null ? null : _tabindex >= 0
if (
platform.is.EDGE &&
platform.majorVersion >= 14 &&
frameElement &&
element.ownerSVGElement &&
_tabindex < 0
) {
// Edge 14+ considers <a xlink:href="…" tabindex="-1"> keyboard focusable
// if the element is in a nested browsing context
return true
}
var hasTabbableTabindexOrNone = tabindex !== false
var hasTabbableTabindex = _tabindex !== null && _tabindex >= 0
// NOTE: Firefox 31 considers [contenteditable] to have [tabindex=-1], but allows tabbing to it
// fixed in Firefox 40 the latest - https://bugzilla.mozilla.org/show_bug.cgi?id=1185657
if (element.hasAttribute('contenteditable')) {
// tabbing can still be disabled by explicitly providing [tabindex="-1"]
return hasTabbableTabindexOrNone
}
if (focusableElementsPattern.test(nodeName) && tabindex !== true) {
return false
}
if (platform.is.WEBKIT && platform.is.IOS) {
// iOS only considers a hand full of elements tabbable (keyboard focusable)
// this holds true even with external keyboards
var potentiallyTabbable =
(nodeName === 'input' && element.type === 'text') ||
element.type === 'password' ||
nodeName === 'select' ||
nodeName === 'textarea' ||
element.hasAttribute('contenteditable')
if (!potentiallyTabbable) {
var style = window.getComputedStyle(element, null)
potentiallyTabbable = isUserModifyWritable(style)
}
if (!potentiallyTabbable) {
return false
}
}
if (nodeName === 'use' && _tabindex !== null) {
if (
platform.is.BLINK ||
(platform.is.WEBKIT && platform.majorVersion === 9)
) {
// In Chrome and Safari 9 the <use> element is keyboard focusable even for tabindex="-1"
return true
}
}
if (elementMatches(element, 'svg a') && element.hasAttribute('xlink:href')) {
if (hasTabbableTabindexOrNone) {
// in Trident and Gecko SVGElement does not handle the tabIndex property properly
return true
}
if (element.focus && !supports$7.focusSvgNegativeTabindexAttribute) {
// Firefox 51 and 52 treat any natively tabbable SVG element with
// tabindex="-1" as tabbable and everything else as inert
// see https://bugzilla.mozilla.org/show_bug.cgi?id=1302340
return true
}
}
if (
nodeName === 'svg' &&
supports$7.focusSvgInIframe &&
hasTabbableTabindexOrNone
) {
return true
}
if (platform.is.TRIDENT || platform.is.EDGE) {
if (nodeName === 'svg') {
if (supports$7.focusSvg) {
// older Internet Explorers consider <svg> keyboard focusable
// unless they have focsable="false", but then they wouldn't
// be focusable and thus not even reach this filter
return true
}
// elements that have [focusable] are automatically keyboard focusable regardless of the attribute's value
return element.hasAttribute('focusable') || hasTabbableTabindex
}
if (element.ownerSVGElement) {
if (supports$7.focusSvgTabindexAttribute && hasTabbableTabindex) {
return true
}
// elements that have [focusable] are automatically keyboard focusable regardless of the attribute's value
return element.hasAttribute('focusable')
}
}
if (element.tabIndex === undefined) {
return Boolean(except.onlyTabbable)
}
if (nodeName === 'audio') {
if (!element.hasAttribute('controls')) {
// In Internet Explorer the <audio> element is focusable, but not tabbable, and tabIndex property is wrong
return false
} else if (platform.is.BLINK) {
// In Chrome <audio controls tabindex="-1"> remains keyboard focusable
return true
}
}
if (nodeName === 'video') {
if (!element.hasAttribute('controls')) {
if (platform.is.TRIDENT || platform.is.EDGE) {
// In Internet Explorer and Edge the <video> element is focusable, but not tabbable, and tabIndex property is wrong
return false
}
} else if (platform.is.BLINK || platform.is.GECKO) {
// In Chrome and Firefox <video controls tabindex="-1"> remains keyboard focusable
return true
}
}
if (nodeName === 'object') {
if (platform.is.BLINK || platform.is.WEBKIT) {
// In all Blink and WebKit based browsers <embed> and <object> are never keyboard focusable, even with tabindex="0" set
return false
}
}
if (nodeName === 'iframe') {
// In Internet Explorer all iframes are only focusable
// In WebKit, Blink and Gecko iframes may be tabbable depending on content.
// Since we can't reliably investigate iframe documents because of the
// SameOriginPolicy, we're declaring everything only focusable.
return false
}
if (!except.scrollable && platform.is.GECKO) {
// Firefox considers scrollable containers keyboard focusable,
// even though their tabIndex property is -1
var _style = window.getComputedStyle(element, null)
if (hasCssOverflowScroll(_style)) {
return hasTabbableTabindexOrNone
}
}
if (platform.is.TRIDENT || platform.is.EDGE) {
// IE and Edge degrade <area> to script focusable, if the image
// using the <map> has been given tabindex="-1"
if (nodeName === 'area') {
var img = getImageOfArea(element)
if (img && tabindexValue(img) < 0) {
return false
}
}
var _style2 = window.getComputedStyle(element, null)
if (isUserModifyWritable(_style2)) {
// prevent being swallowed by the overzealous isScrollableContainer() below
return element.tabIndex >= 0
}
if (!except.flexbox && hasCssDisplayFlex(_style2)) {
if (_tabindex !== null) {
return hasTabbableTabindex
}
return (
isFocusRelevantWithoutFlexbox(element) &&
isTabbableWithoutFlexbox(element)
)
}
// IE considers scrollable containers script focusable only,
// even though their tabIndex property is 0
if (isScrollableContainer(element, nodeName)) {
return false
}
var parent = element.parentElement
if (parent) {
var parentNodeName = parent.nodeName.toLowerCase()
var parentStyle = window.getComputedStyle(parent, null)
// IE considers scrollable bodies script focusable only,
if (
isScrollableContainer(parent, nodeName, parentNodeName, parentStyle)
) {
return false
}
// Children of focusable elements with display:flex are focusable in IE10-11,
// even though their tabIndex property suggests otherwise
if (hasCssDisplayFlex(parentStyle)) {
// value of tabindex takes precedence
return hasTabbableTabindex
}
}
}
// https://www.w3.org/WAI/PF/aria-practices/#focus_tabindex
return element.tabIndex >= 0
}
// bind exceptions to an iterator callback
isTabbableRules.except = function () {
var except =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}
var isTabbable = function isTabbable(context) {
return isTabbableRules({
context: context,
except: except,
})
}
isTabbable.rules = isTabbableRules
return isTabbable
}
var isFocusRelevantWithoutFlexbox = isFocusRelevant.rules.except({
flexbox: true,
})
var isTabbableWithoutFlexbox = isTabbableRules.except({ flexbox: true })
// provide isTabbable(context) as default iterator callback
var isTabbable = isTabbableRules.except({})
function queryTabbable() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context,
includeContext = _ref.includeContext,
includeOnlyTabbable = _ref.includeOnlyTabbable,
strategy = _ref.strategy
var _isTabbable = isTabbable.rules.except({
onlyTabbable: includeOnlyTabbable,
})
return queryFocusable({
context: context,
includeContext: includeContext,
includeOnlyTabbable: includeOnlyTabbable,
strategy: strategy,
}).filter(_isTabbable)
}
// sorts a list of elements according to their order in the DOM
function compareDomPosition(a, b) {
return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING
? -1
: 1
}
function sortDomOrder(elements) {
return elements.sort(compareDomPosition)
}
function getFirstSuccessorOffset(list, target) {
// find the first element that comes AFTER the target element
return findIndex(list, function (element) {
return (
target.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_FOLLOWING
)
})
}
function findInsertionOffsets(list, elements, resolveElement) {
// instead of mutating the elements list directly, remember position and map
// to inject later, when we can do this more efficiently
var insertions = []
elements.forEach(function (element) {
var replace = true
var offset = list.indexOf(element)
if (offset === -1) {
// element is not in target list
offset = getFirstSuccessorOffset(list, element)
replace = false
}
if (offset === -1) {
// there is no successor in the tabsequence,
// meaning the image must be the last element
offset = list.length
}
// allow the consumer to replace the injected element
var injections = nodeArray(
resolveElement ? resolveElement(element) : element
)
if (!injections.length) {
// we can't inject zero elements
return
}
insertions.push({
offset: offset,
replace: replace,
elements: injections,
})
})
return insertions
}
function insertElementsAtOffsets(list, insertions) {
// remember the number of elements we have already injected
// so we account for the caused index offset
var inserted = 0
// make sure that we insert the elements in sequence,
// otherwise the offset compensation won't work
insertions.sort(function (a, b) {
return a.offset - b.offset
})
insertions.forEach(function (insertion) {
// array.splice has an annoying function signature :(
var remove = insertion.replace ? 1 : 0
var args = [insertion.offset + inserted, remove].concat(insertion.elements)
list.splice.apply(list, args)
inserted += insertion.elements.length - remove
})
}
function mergeInDomOrder() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
list = _ref.list,
elements = _ref.elements,
resolveElement = _ref.resolveElement
// operate on a copy so we don't mutate the original array
var _list = list.slice(0)
// make sure the elements we're injecting are provided in DOM order
var _elements = nodeArray(elements).slice(0)
sortDomOrder(_elements)
// find the offsets within the target array (list) at which to inject
// each individual element (from elements)
var insertions = findInsertionOffsets(_list, _elements, resolveElement)
// actually inject the elements into the target array at the identified positions
insertElementsAtOffsets(_list, insertions)
return _list
}
var _createClass = (function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i]
descriptor.enumerable = descriptor.enumerable || false
descriptor.configurable = true
if ('value' in descriptor) descriptor.writable = true
Object.defineProperty(target, descriptor.key, descriptor)
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps)
if (staticProps) defineProperties(Constructor, staticProps)
return Constructor
}
})()
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function')
}
}
var Maps = (function () {
function Maps(context) {
_classCallCheck(this, Maps)
this._document = getDocument(context)
this.maps = {}
}
_createClass(Maps, [
{
key: 'getAreasFor',
value: function getAreasFor(name) {
if (!this.maps[name]) {
// the map is not defined within the context, so we
// have to go find it elsewhere in the document
this.addMapByName(name)
}
return this.maps[name]
},
},
{
key: 'addMapByName',
value: function addMapByName(name) {
var map = getMapByName(name, this._document)
if (!map) {
// if there is no map, the img[usemap] wasn't doing anything anyway
return
}
this.maps[map.name] = queryTabbable({ context: map })
},
},
{
key: 'extractAreasFromList',
value: function extractAreasFromList(elements) {
// remove all <area> elements from the elements list,
// but put them the map for later retrieval
return elements.filter(function (element) {
var nodeName = element.nodeName.toLowerCase()
if (nodeName !== 'area') {
return true
}
var map = element.parentNode
if (!this.maps[map.name]) {
this.maps[map.name] = []
}
this.maps[map.name].push(element)
return false
}, this)
},
},
])
return Maps
})()
function sortArea(elements, context) {
// images - unless they are focusable themselves, likely not
// part of the elements list, so we'll have to find them and
// sort them into the elements list manually
var usemaps = context.querySelectorAll('img[usemap]')
var maps = new Maps(context)
// remove all <area> elements from the elements list,
// but put them the map for later retrieval
var _elements = maps.extractAreasFromList(elements)
if (!usemaps.length) {
// the context does not contain any <area>s so no need
// to replace anything, just remove any maps
return _elements
}
return mergeInDomOrder({
list: _elements,
elements: usemaps,
resolveElement: function resolveElement(image) {
var name = image.getAttribute('usemap').slice(1)
return maps.getAreasFor(name)
},
})
}
var _createClass$1 = (function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i]
descriptor.enumerable = descriptor.enumerable || false
descriptor.configurable = true
if ('value' in descriptor) descriptor.writable = true
Object.defineProperty(target, descriptor.key, descriptor)
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps)
if (staticProps) defineProperties(Constructor, staticProps)
return Constructor
}
})()
function _classCallCheck$1(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError('Cannot call a class as a function')
}
}
var Shadows = (function () {
function Shadows(context, sortElements) {
_classCallCheck$1(this, Shadows)
// document context we're working with
this.context = context
// callback that sorts an array of elements
this.sortElements = sortElements
// reference to create unique IDs for each ShadowHost
this.hostCounter = 1
// reference map for child-ShadowHosts of a ShadowHost
this.inHost = {}
// reference map for child-ShadowHost of the document
this.inDocument = []
// reference map for ShadowHosts
this.hosts = {}
// reference map for tabbable elements of a ShadowHost
this.elements = {}
}
// remember which hosts we have to sort within later
_createClass$1(Shadows, [
{
key: '_registerHost',
value: function _registerHost(host) {
if (host._sortingId) {
return
}
// make the ShadowHost identifiable (see cleanup() for undo)
host._sortingId = 'shadow-' + this.hostCounter++
this.hosts[host._sortingId] = host
// hosts may contain other hosts
var parentHost = getShadowHost({ context: host })
if (parentHost) {
this._registerHost(parentHost)
this._registerHostParent(host, parentHost)
} else {
this.inDocument.push(host)
}
},
// remember which host is the child of which other host
},
{
key: '_registerHostParent',
value: function _registerHostParent(host, parent) {
if (!this.inHost[parent._sortingId]) {
this.inHost[parent._sortingId] = []
}
this.inHost[parent._sortingId].push(host)
},
// remember which elements a host contains
},
{
key: '_registerElement',
value: function _registerElement(element, host) {
if (!this.elements[host._sortingId]) {
this.elements[host._sortingId] = []
}
this.elements[host._sortingId].push(element)
},
// remove shadowed elements from the sequence and register
// the ShadowHosts they belong to so we know what to sort
// later on
},
{
key: 'extractElements',
value: function extractElements(elements) {
return elements.filter(function (element) {
var host = getShadowHost({ context: element })
if (!host) {
return true
}
this._registerHost(host)
this._registerElement(element, host)
return false
}, this)
},
// inject hosts into the sequence, sort everything,
// and recoursively replace hosts by its descendants
},
{
key: 'sort',
value: function sort(elements) {
var _elements = this._injectHosts(elements)
_elements = this._replaceHosts(_elements)
this._cleanup()
return _elements
},
// merge ShadowHosts into the element lists of other ShadowHosts
// or the document, then sort the individual lists
},
{
key: '_injectHosts',
value: function _injectHosts(elements) {
Object.keys(this.hosts).forEach(function (_sortingId) {
var _list = this.elements[_sortingId]
var _elements = this.inHost[_sortingId]
var _context = this.hosts[_sortingId].shadowRoot
this.elements[_sortingId] = this._merge(_list, _elements, _context)
}, this)
return this._merge(elements, this.inDocument, this.context)
},
},
{
key: '_merge',
value: function _merge(list, elements, context) {
var merged = mergeInDomOrder({
list: list,
elements: elements,
})
return this.sortElements(merged, context)
},
},
{
key: '_replaceHosts',
value: function _replaceHosts(elements) {
return mergeInDomOrder({
list: elements,
elements: this.inDocument,
resolveElement: this._resolveHostElement.bind(this),
})
},
},
{
key: '_resolveHostElement',
value: function _resolveHostElement(host) {
var merged = mergeInDomOrder({
list: this.elements[host._sortingId],
elements: this.inHost[host._sortingId],
resolveElement: this._resolveHostElement.bind(this),
})
var _tabindex = tabindexValue(host)
if (_tabindex !== null && _tabindex > -1) {
return [host].concat(merged)
}
return merged
},
},
{
key: '_cleanup',
value: function _cleanup() {
// remove those identifers we put on the ShadowHost to avoid using Map()
Object.keys(this.hosts).forEach(function (key) {
delete this.hosts[key]._sortingId
}, this)
},
},
])
return Shadows
})()
function sortShadowed(elements, context, sortElements) {
var shadows = new Shadows(context, sortElements)
var _elements = shadows.extractElements(elements)
if (_elements.length === elements.length) {
// no shadowed content found, no need to continue
return sortElements(elements)
}
return shadows.sort(_elements)
}
function sortTabindex(elements) {
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.tabIndex
// elements with tabIndex "0" (including tabbableElements without tabIndex) should be navigated in the order they appear.
// elements with a positive tabIndex:
// Elements that have identical tabIndexes should be navigated in the order they appear.
// Navigation proceeds from the lowest tabIndex to the highest tabIndex.
// NOTE: sort implementation may be unstable and thus mess up DOM order,
// that's why we build a map that's being sorted instead. If we were able to rely
// on a stable sorting algorithm, sortTabindex() could be as simple as
// elements.sort(function(a, b) { return a.tabIndex - b.tabIndex; });
// at this time Chrome does not use a stable sorting algorithm
// see http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html#stability
// NOTE: compareDocumentPosition seemed like more overhead than just sorting this with buckets
// https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
var map = {}
var indexes = []
var normal = elements.filter(function (element) {
// in Trident and Gecko SVGElement does not know about the tabIndex property
var tabIndex = element.tabIndex
if (tabIndex === undefined) {
tabIndex = tabindexValue(element)
}
// extract elements that don't need sorting
if (tabIndex <= 0 || tabIndex === null || tabIndex === undefined) {
return true
}
if (!map[tabIndex]) {
// create sortable bucket for dom-order-preservation of elements with the same tabIndex
map[tabIndex] = []
// maintain a list of unique tabIndexes
indexes.push(tabIndex)
}
// sort element into the proper bucket
map[tabIndex].push(element)
// element moved to sorting map, so not "normal" anymore
return false
})
// sort the tabindex ascending,
// then resolve them to their appropriate buckets,
// then flatten the array of arrays to an array
var _elements = indexes
.sort()
.map(function (tabIndex) {
return map[tabIndex]
})
.reduceRight(function (previous, current) {
return current.concat(previous)
}, normal)
return _elements
}
var supports$8 = void 0
function moveContextToBeginning(elements, context) {
var pos = elements.indexOf(context)
if (pos > 0) {
var tmp = elements.splice(pos, 1)
return tmp.concat(elements)
}
return elements
}
function sortElements(elements, _context) {
if (supports$8.tabsequenceAreaAtImgPosition) {
// Some browsers sort <area> in DOM order, some place the <area>s
// where the <img> referecing them would've been in DOM order.
// https://github.com/medialize/ally.js/issues/5
elements = sortArea(elements, _context)
}
elements = sortTabindex(elements)
return elements
}
function queryTabsequence() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
context = _ref.context,
includeContext = _ref.includeContext,
includeOnlyTabbable = _ref.includeOnlyTabbable,
strategy = _ref.strategy
if (!supports$8) {
supports$8 = _supports()
}
var _context = nodeArray(context)[0] || document.documentElement
var elements = queryTabbable({
context: _context,
includeContext: includeContext,
includeOnlyTabbable: includeOnlyTabbable,
strategy: strategy,
})
if (document.body.createShadowRoot && platform.is.BLINK) {
// sort tabindex localized to shadow dom
// see https://github.com/medialize/ally.js/issues/6
elements = sortShadowed(elements, _context, sortElements)
} else {
elements = sortElements(elements, _context)
}
if (includeContext) {
// if we include the context itself, it has to be the first
// element of the sequence
elements = moveContextToBeginning(elements, _context)
}
return elements
}
// codes mostly cloned from https://github.com/keithamus/jwerty/blob/master/jwerty.js
// deliberately not exposing characters like <,.-#* because they vary *wildly*
// across keyboard layouts and may cause various problems
// (e.g. "*" is "Shift +" on a German Mac keyboard)
// (e.g. "@" is "Alt L" on a German Mac keyboard)
var keycode = {
// Element Focus
tab: 9,
// Navigation
left: 37,
up: 38,
right: 39,
down: 40,
pageUp: 33,
'page-up': 33,
pageDown: 34,
'page-down': 34,
end: 35,
home: 36,
// Action
enter: 13,
escape: 27,
space: 32,
// Modifier
shift: 16,
capsLock: 20,
'caps-lock': 20,
ctrl: 17,
alt: 18,
meta: 91,
// in firefox: 224
// on mac (chrome): meta-left=91, meta-right=93
// on win (IE11): meta-left=91, meta-right=92
pause: 19,
// Content Manipulation
insert: 45,
delete: 46,
backspace: 8,
// the same logical key may be identified through different keyCodes
_alias: {
91: [92, 93, 224],
},
}
// Function keys (112 - 137)
// NOTE: not every keyboard knows F13+
for (var n = 1; n < 26; n++) {
keycode['f' + n] = n + 111
}
// Number keys (48-57, numpad 96-105)
// NOTE: not every keyboard knows num-0+
for (var _n = 0; _n < 10; _n++) {
var code = _n + 48
var numCode = _n + 96
keycode[_n] = code
keycode['num-' + _n] = numCode
keycode._alias[code] = [numCode]
}
// Latin characters (65 - 90)
for (var _n2 = 0; _n2 < 26; _n2++) {
var _code = _n2 + 65
var name$1 = String.fromCharCode(_code).toLowerCase()
keycode[name$1] = _code
}
var modifier = {
alt: 'altKey',
ctrl: 'ctrlKey',
meta: 'metaKey',
shift: 'shiftKey',
}
var modifierSequence = Object.keys(modifier).map(function (name) {
return modifier[name]
})
function createExpectedModifiers(ignoreModifiers) {
var value = ignoreModifiers ? null : false
return {
altKey: value,
ctrlKey: value,
metaKey: value,
shiftKey: value,
}
}
function resolveModifiers(modifiers) {
var ignoreModifiers = modifiers.indexOf('*') !== -1
var expected = createExpectedModifiers(ignoreModifiers)
modifiers.forEach(function (token) {
if (token === '*') {
// we've already covered the all-in operator
return
}
// we want the modifier pressed
var value = true
var operator = token.slice(0, 1)
if (operator === '?') {
// we don't care if the modifier is pressed
value = null
} else if (operator === '!') {
// we do not want the modifier pressed
value = false
}
if (value !== true) {
// compensate for the modifier's operator
token = token.slice(1)
}
var propertyName = modifier[token]
if (!propertyName) {
throw new TypeError('Unknown modifier "' + token + '"')
}
expected[propertyName] = value
})
return expected
}
function resolveKey(key) {
var code = keycode[key] || parseInt(key, 10)
if (!code || typeof code !== 'number' || isNaN(code)) {
throw new TypeError('Unknown key "' + key + '"')
}
return [code].concat(keycode._alias[code] || [])
}
function matchModifiers(expected, event) {
// returns true on match
return !modifierSequence.some(function (prop) {
// returns true on mismatch
return (
typeof expected[prop] === 'boolean' &&
Boolean(event[prop]) !== expected[prop]
)
})
}
function keyBinding(text) {
return text.split(/\s+/).map(function (_text) {
var tokens = _text.split('+')
var _modifiers = resolveModifiers(tokens.slice(0, -1))
var _keyCodes = resolveKey(tokens.slice(-1))
return {
keyCodes: _keyCodes,
modifiers: _modifiers,
matchModifiers: matchModifiers.bind(null, _modifiers),
}
})
}
// Node.compareDocumentPosition is available since IE9
// see https://developer.mozilla.org/en-US/docs/Web/API/Node.compareDocumentPosition
// callback returns true when element is contained by parent or is the parent suited for use with Array.some()
/*
USAGE:
var isChildOf = getParentComparator({parent: someNode});
listOfElements.some(isChildOf)
*/
function getParentComparator() {
var _ref =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
parent = _ref.parent,
element = _ref.element,
includeSelf = _ref.includeSelf
if (parent) {
return function isChildOf(node) {
return Boolean(
(includeSelf && node === parent) ||
parent.compareDocumentPosition(node) &
Node.DOCUMENT_POSITION_CONTAINED_BY
)
}
} else if (element) {
return function isParentOf(node) {
return Boolean(
(includeSelf && element === node) ||
node.compareDocumentPosition(element) &
Node.DOCUMENT_POSITION_CONTAINED_BY
)
}
}
throw new TypeError(
'util/compare-position#getParentComparator required either options.parent or options.element'
)
}
// Bug 286933 - Key events in the autocomplete popup should be hidden from page scripts
// @browser-issue Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=286933
function whenKey() {
var map =
arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}
var bindings = {}
var context = nodeArray(map.context)[0] || document.documentElement
delete map.context
var filter = nodeArray(map.filter)
delete map.filter
var mapKeys = Object.keys(map)
if (!mapKeys.length) {
throw new TypeError('when/key requires at least one option key')
}
var registerBinding = function registerBinding(event) {
event.keyCodes.forEach(function (code) {
if (!bindings[code]) {
bindings[code] = []
}
bindings[code].push(event)
})
}
mapKeys.forEach(function (text) {
if (typeof map[text] !== 'function') {
throw new TypeError(
'when/key requires option["' + text + '"] to be a function'
)
}
var addCallback = function addCallback(event) {
event.callback = map[text]
return event
}
keyBinding(text).map(addCallback).forEach(registerBinding)
})
var handleKeyDown = function handleKeyDown(event) {
if (event.defaultPrevented) {
return
}
if (filter.length) {
// ignore elements within the exempted sub-trees
var isParentOfElement = getParentComparator({
element: event.target,
includeSelf: true,
})
if (filter.some(isParentOfElement)) {
return
}
}
var key = event.keyCode || event.which
if (!bindings[key]) {
return
}
bindings[key].forEach(function (_event) {
if (!_event.matchModifiers(event)) {
return
}
_event.callback.call(context, event, disengage)
})
}
context.addEventListener('keydown', handleKeyDown, false)
var disengage = function disengage() {
context.removeEventListener('keydown', handleKeyDown, false)
}
return { disengage: disengage }
}
export default function ({ context } = {}) {
if (!context) {
context = document.documentElement
}
// Make sure the supports tests are run before intercepting the Tab key,
// or IE10 and IE11 will fail to process the first Tab key event. Not
// limiting this warm-up to IE because it may be a problem elsewhere, too.
queryTabsequence()
return whenKey({
// Safari on OSX may require ALT+TAB to reach links,
// see https://github.com/medialize/ally.js/issues/146
'?alt+?shift+tab': function altShiftTab(event) {
// we're completely taking over the Tab key handling
event.preventDefault()
var sequence = queryTabsequence({
context: context,
})
var backward = event.shiftKey
var first = sequence[0]
var last = sequence[sequence.length - 1]
// wrap around first to last, last to first
var source = backward ? first : last
var target = backward ? last : first
if (isActiveElement(source)) {
target.focus()
return
}
// find current position in tabsequence
var currentIndex = void 0
var found = sequence.some(function (element, index) {
if (!isActiveElement(element)) {
return false
}
currentIndex = index
return true
})
if (!found) {
// redirect to first as we're not in our tabsequence
first.focus()
return
}
// shift focus to previous/next element in the sequence
var offset = backward ? -1 : 1
sequence[currentIndex + offset].focus()
},
})
} | the_stack |
import * as dom from 'vs/base/browser/dom';
import { MOUSE_CURSOR_TEXT_CSS_CLASS_NAME } from 'vs/base/browser/ui/mouseCursor/mouseCursor';
import { IAction } from 'vs/base/common/actions';
import { Disposable, IDisposable } from 'vs/base/common/lifecycle';
import { MarshalledId } from 'vs/base/common/marshallingIds';
import { URI } from 'vs/base/common/uri';
import { generateUuid } from 'vs/base/common/uuid';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { IRange } from 'vs/editor/common/core/range';
import * as languages from 'vs/editor/common/languages';
import { ILanguageService } from 'vs/editor/common/languages/language';
import { ITextModel } from 'vs/editor/common/model';
import { IModelService } from 'vs/editor/common/services/model';
import * as nls from 'vs/nls';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { editorForeground, resolveColorValue } from 'vs/platform/theme/common/colorRegistry';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { CommentFormActions } from 'vs/workbench/contrib/comments/browser/commentFormActions';
import { CommentMenus } from 'vs/workbench/contrib/comments/browser/commentMenus';
import { ICommentService } from 'vs/workbench/contrib/comments/browser/commentService';
import { CommentContextKeys } from 'vs/workbench/contrib/comments/common/commentContextKeys';
import { ICommentThreadWidget } from 'vs/workbench/contrib/comments/common/commentThreadWidget';
import { ICellRange } from 'vs/workbench/contrib/notebook/common/notebookRange';
import { SimpleCommentEditor } from './simpleCommentEditor';
const COMMENT_SCHEME = 'comment';
let INMEM_MODEL_ID = 0;
export const COMMENTEDITOR_DECORATION_KEY = 'commenteditordecoration';
export class CommentReply<T extends IRange | ICellRange> extends Disposable {
commentEditor: ICodeEditor;
form: HTMLElement;
commentEditorIsEmpty: IContextKey<boolean>;
private _error!: HTMLElement;
private _formActions: HTMLElement | null;
private _commentThreadDisposables: IDisposable[] = [];
private _commentFormActions!: CommentFormActions;
private _reviewThreadReplyButton!: HTMLElement;
constructor(
readonly owner: string,
container: HTMLElement,
private _commentThread: languages.CommentThread<T>,
private _scopedInstatiationService: IInstantiationService,
private _contextKeyService: IContextKeyService,
private _commentMenus: CommentMenus,
private _commentOptions: languages.CommentOptions | undefined,
private _pendingComment: string | null,
private _parentThread: ICommentThreadWidget,
private _actionRunDelegate: (() => void) | null,
@ICommentService private commentService: ICommentService,
@ILanguageService private languageService: ILanguageService,
@IModelService private modelService: IModelService,
@IThemeService private themeService: IThemeService,
) {
super();
this.form = dom.append(container, dom.$('.comment-form'));
this.commentEditor = this._register(this._scopedInstatiationService.createInstance(SimpleCommentEditor, this.form, SimpleCommentEditor.getEditorOptions(), this._parentThread));
this.commentEditorIsEmpty = CommentContextKeys.commentIsEmpty.bindTo(this._contextKeyService);
this.commentEditorIsEmpty.set(!this._pendingComment);
const hasExistingComments = this._commentThread.comments && this._commentThread.comments.length > 0;
const modeId = generateUuid() + '-' + (hasExistingComments ? this._commentThread.threadId : ++INMEM_MODEL_ID);
const params = JSON.stringify({
extensionId: this._commentThread.extensionId,
commentThreadId: this._commentThread.threadId
});
let resource = URI.parse(`${COMMENT_SCHEME}://${this._commentThread.extensionId}/commentinput-${modeId}.md?${params}`); // TODO. Remove params once extensions adopt authority.
const commentController = this.commentService.getCommentController(owner);
if (commentController) {
resource = resource.with({ authority: commentController.id });
}
const model = this.modelService.createModel(this._pendingComment || '', this.languageService.createByFilepathOrFirstLine(resource), resource, false);
this._register(model);
this.commentEditor.setModel(model);
this._register((this.commentEditor.getModel()!.onDidChangeContent(() => {
this.setCommentEditorDecorations();
this.commentEditorIsEmpty?.set(!this.commentEditor.getValue());
})));
this.createTextModelListener(this.commentEditor, this.form);
this.setCommentEditorDecorations();
// Only add the additional step of clicking a reply button to expand the textarea when there are existing comments
if (hasExistingComments) {
this.createReplyButton(this.commentEditor, this.form);
} else {
if (this._commentThread.comments && this._commentThread.comments.length === 0) {
this.expandReplyArea();
}
}
this._error = dom.append(this.form, dom.$('.validation-error.hidden'));
this._formActions = dom.append(this.form, dom.$('.form-actions'));
this.createCommentWidgetActions(this._formActions, model);
}
public updateCommentThread(commentThread: languages.CommentThread<IRange | ICellRange>) {
const isReplying = this.commentEditor.hasTextFocus();
if (!this._reviewThreadReplyButton) {
this.createReplyButton(this.commentEditor, this.form);
}
if (this._commentThread.comments && this._commentThread.comments.length === 0) {
this.expandReplyArea();
}
if (isReplying) {
this.commentEditor.focus();
}
}
public getPendingComment(): string | null {
const model = this.commentEditor.getModel();
if (model && model.getValueLength() > 0) { // checking length is cheap
return model.getValue();
}
return null;
}
public layout(widthInPixel: number) {
this.commentEditor.layout({ height: 5 * 18, width: widthInPixel - 54 /* margin 20px * 10 + scrollbar 14px*/ });
}
public focusIfNeeded() {
if (!this._commentThread.comments || !this._commentThread.comments.length) {
this.commentEditor.focus();
} else if (this.commentEditor.getModel()!.getValueLength() > 0) {
this.expandReplyArea();
}
}
public focusCommentEditor() {
this.commentEditor.focus();
}
public getCommentModel() {
return this.commentEditor.getModel()!;
}
public updateCanReply() {
if (!this._commentThread.canReply) {
this.form.style.display = 'none';
} else {
this.form.style.display = 'block';
}
}
async submitComment(): Promise<void> {
if (this._commentFormActions) {
this._commentFormActions.triggerDefaultAction();
}
}
setCommentEditorDecorations() {
const model = this.commentEditor.getModel();
if (model) {
const valueLength = model.getValueLength();
const hasExistingComments = this._commentThread.comments && this._commentThread.comments.length > 0;
const placeholder = valueLength > 0
? ''
: hasExistingComments
? (this._commentOptions?.placeHolder || nls.localize('reply', "Reply..."))
: (this._commentOptions?.placeHolder || nls.localize('newComment', "Type a new comment"));
const decorations = [{
range: {
startLineNumber: 0,
endLineNumber: 0,
startColumn: 0,
endColumn: 1
},
renderOptions: {
after: {
contentText: placeholder,
color: `${resolveColorValue(editorForeground, this.themeService.getColorTheme())?.transparent(0.4)}`
}
}
}];
this.commentEditor.setDecorations('review-zone-widget', COMMENTEDITOR_DECORATION_KEY, decorations);
}
}
private createTextModelListener(commentEditor: ICodeEditor, commentForm: HTMLElement) {
this._commentThreadDisposables.push(commentEditor.onDidFocusEditorWidget(() => {
this._commentThread.input = {
uri: commentEditor.getModel()!.uri,
value: commentEditor.getValue()
};
this.commentService.setActiveCommentThread(this._commentThread);
}));
this._commentThreadDisposables.push(commentEditor.getModel()!.onDidChangeContent(() => {
const modelContent = commentEditor.getValue();
if (this._commentThread.input && this._commentThread.input.uri === commentEditor.getModel()!.uri && this._commentThread.input.value !== modelContent) {
const newInput: languages.CommentInput = this._commentThread.input;
newInput.value = modelContent;
this._commentThread.input = newInput;
}
this.commentService.setActiveCommentThread(this._commentThread);
}));
this._commentThreadDisposables.push(this._commentThread.onDidChangeInput(input => {
const thread = this._commentThread;
if (thread.input && thread.input.uri !== commentEditor.getModel()!.uri) {
return;
}
if (!input) {
return;
}
if (commentEditor.getValue() !== input.value) {
commentEditor.setValue(input.value);
if (input.value === '') {
this._pendingComment = '';
commentForm.classList.remove('expand');
commentEditor.getDomNode()!.style.outline = '';
this._error.textContent = '';
this._error.classList.add('hidden');
}
}
}));
}
/**
* Command based actions.
*/
private createCommentWidgetActions(container: HTMLElement, model: ITextModel) {
const menu = this._commentMenus.getCommentThreadActions(this._contextKeyService);
this._register(menu);
this._register(menu.onDidChange(() => {
this._commentFormActions.setActions(menu);
}));
this._commentFormActions = new CommentFormActions(container, async (action: IAction) => {
this._actionRunDelegate?.();
action.run({
thread: this._commentThread,
text: this.commentEditor.getValue(),
$mid: MarshalledId.CommentThreadReply
});
this.hideReplyArea();
}, this.themeService);
this._commentFormActions.setActions(menu);
}
private get isReplyExpanded(): boolean {
return this.form.classList.contains('expand');
}
private expandReplyArea() {
if (!this.isReplyExpanded) {
this.form.classList.add('expand');
this.commentEditor.focus();
this.commentEditor.layout();
}
}
private clearAndExpandReplyArea() {
if (!this.isReplyExpanded) {
this.commentEditor.setValue('');
this.expandReplyArea();
}
}
private hideReplyArea() {
this.commentEditor.getDomNode()!.style.outline = '';
this._pendingComment = '';
this.form.classList.remove('expand');
this._error.textContent = '';
this._error.classList.add('hidden');
}
private createReplyButton(commentEditor: ICodeEditor, commentForm: HTMLElement) {
this._reviewThreadReplyButton = <HTMLButtonElement>dom.append(commentForm, dom.$(`button.review-thread-reply-button.${MOUSE_CURSOR_TEXT_CSS_CLASS_NAME}`));
this._reviewThreadReplyButton.title = this._commentOptions?.prompt || nls.localize('reply', "Reply...");
this._reviewThreadReplyButton.textContent = this._commentOptions?.prompt || nls.localize('reply', "Reply...");
// bind click/escape actions for reviewThreadReplyButton and textArea
this._register(dom.addDisposableListener(this._reviewThreadReplyButton, 'click', _ => this.clearAndExpandReplyArea()));
this._register(dom.addDisposableListener(this._reviewThreadReplyButton, 'focus', _ => this.clearAndExpandReplyArea()));
commentEditor.onDidBlurEditorWidget(() => {
if (commentEditor.getModel()!.getValueLength() === 0 && commentForm.classList.contains('expand')) {
commentForm.classList.remove('expand');
}
});
}
} | the_stack |
import { Component, Type, ViewChild, Directive } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { FormsModule, FormGroup, FormControl, ReactiveFormsModule } from '@angular/forms';
import { NxMaskModule } from './mask.module';
import { NxMaskDirective } from './mask.directive';
import { NxIbanMaskDirective } from './iban-mask.directive';
import { assertInputValue } from './mask.directive.spec';
@Directive()
abstract class IbanMaskTest {
@ViewChild(NxMaskDirective) maskInstance!: NxMaskDirective;
@ViewChild(NxIbanMaskDirective) ibanInstance!: NxIbanMaskDirective;
testForm: FormGroup = new FormGroup({
maskInput: new FormControl('', {})
});
validateMask = true;
}
describe('NxIbanMaskDirective', () => {
let fixture: ComponentFixture<IbanMaskTest>;
let testInstance: IbanMaskTest;
let maskInstance: NxMaskDirective;
let ibanInstance: NxIbanMaskDirective;
let nativeElement: HTMLInputElement;
function createTestComponent(component: Type<IbanMaskTest>) {
fixture = TestBed.createComponent(component);
fixture.detectChanges();
testInstance = fixture.componentInstance;
maskInstance = testInstance.maskInstance;
ibanInstance = testInstance.ibanInstance;
nativeElement = fixture.nativeElement.querySelector('input') as HTMLInputElement;
}
function testIban(inputValue: string, asserted: string) {
const countryCode = inputValue.substr(0, 2);
nativeElement.value = countryCode;
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(testInstance.testForm.valid).toBe(false);
nativeElement.value = inputValue;
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe(asserted);
expect(testInstance.testForm.valid).toBe(true);
}
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
BasicIbanMaskComponent,
FormIbanMaskComponent,
FormWithInitalIbanMaskComponent
],
imports: [
FormsModule,
ReactiveFormsModule,
NxMaskModule
]
}).compileComponents();
})
);
describe('basic', () => {
it('creates the input', () => {
createTestComponent(BasicIbanMaskComponent);
expect(ibanInstance).toBeTruthy();
});
});
describe('change masks', () => {
it('updates mask when first two letters were entered', () => {
createTestComponent(BasicIbanMaskComponent);
expect(maskInstance.mask).toBe('SS');
assertInputValue(nativeElement, 'DE', 'DE');
expect(maskInstance.mask).toBe('SS00 0000 0000 0000 0000 00');
assertInputValue(nativeElement, 'FR', 'FR');
expect(maskInstance.mask).toBe('SS00 0000 0000 00AA AAAA AAAA A00');
});
it('does not update mask on entering invalid country code', () => {
createTestComponent(BasicIbanMaskComponent);
expect(maskInstance.mask).toBe('SS');
assertInputValue(nativeElement, 'GD', 'GD');
expect(maskInstance.mask).toBe('SS');
});
it('sets mask to SS for invalid country code', () => {
createTestComponent(BasicIbanMaskComponent);
assertInputValue(nativeElement, 'DE', 'DE');
expect(maskInstance.mask).toBe('SS00 0000 0000 0000 0000 00');
assertInputValue(nativeElement, 'DI', 'DI');
expect(maskInstance.mask).toBe('SS');
});
it('accepts lowercase country codes', () => {
createTestComponent(BasicIbanMaskComponent);
assertInputValue(nativeElement, 'de89370400440532013001', 'DE89 3704 0044 0532 0130 01');
expect(maskInstance.mask).toBe('SS00 0000 0000 0000 0000 00');
assertInputValue(nativeElement, 'di', 'DI');
expect(maskInstance.mask).toBe('SS');
});
});
describe('form', () => {
it('should correctly fill in an initial form value', () => {
createTestComponent(FormWithInitalIbanMaskComponent);
expect(nativeElement.value).toBe('NL91 ABNA 0417 1643 00');
});
it('should correctly update on patchValue', () => {
createTestComponent(FormIbanMaskComponent);
testInstance.testForm.patchValue({ maskInput: 'NL91ABNA0417164300' });
expect(nativeElement.value).toBe('NL91 ABNA 0417 1643 00');
});
});
describe('pasting', () => {
it('paste without changing the country code', () => {
createTestComponent(BasicIbanMaskComponent);
assertInputValue(nativeElement, 'DE', 'DE');
let data = new DataTransfer();
data.items.add('DE89370400440532013000', 'text/plain');
let pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(0, 2);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = 'DE89370400440532013000';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('DE89 3704 0044 0532 0130 00');
expect(nativeElement.selectionStart).toBe(27);
expect(nativeElement.selectionEnd).toBe(27);
data = new DataTransfer();
data.items.add('DE27100777770209299700', 'text/plain');
pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(0, 27);
nativeElement.value = 'DE27100777770209299700';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('DE27 1007 7777 0209 2997 00');
expect(nativeElement.selectionStart).toBe(27);
expect(nativeElement.selectionEnd).toBe(27);
});
it('paste with changing the country code', () => {
createTestComponent(BasicIbanMaskComponent);
let data = new DataTransfer();
data.items.add('DE89370400440532013000', 'text/plain');
let pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(0, 2);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = 'DE89370400440532013000';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('DE89 3704 0044 0532 0130 00');
expect(nativeElement.selectionStart).toBe(27);
expect(nativeElement.selectionEnd).toBe(27);
data = new DataTransfer();
data.items.add('DK5750510001322617', 'text/plain');
pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(0, 27);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = 'DK5750510001322617';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('DK57 5051 0001 3226 17');
expect(nativeElement.selectionStart).toBe(22);
expect(nativeElement.selectionEnd).toBe(22);
data = new DataTransfer();
data.items.add('DE27100777770209299700', 'text/plain');
pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(0, 22);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = 'DE27100777770209299700';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(maskInstance.mask).toBe('SS00 0000 0000 0000 0000 00');
expect(nativeElement.value).toBe('DE27 1007 7777 0209 2997 00');
expect(nativeElement.selectionStart).toBe(27);
expect(nativeElement.selectionEnd).toBe(27);
});
it('pasting with lowercase', () => {
createTestComponent(BasicIbanMaskComponent);
let data = new DataTransfer();
data.items.add('de89370400440532013000', 'text/plain');
let pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(0, 2);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = 'de89370400440532013000';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('DE89 3704 0044 0532 0130 00');
expect(nativeElement.selectionStart).toBe(27);
expect(nativeElement.selectionEnd).toBe(27);
data = new DataTransfer();
data.items.add('mt84malt011000012345mtlcast001s', 'text/plain');
pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(0, 27);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = 'mt84malt011000012345mtlcast001s';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('MT84 MALT 0110 0001 2345 MTLC AST0 01S');
expect(maskInstance.mask).toBe('SS00 SSSS 0000 0AAA AAAA AAAA AAAA AAA');
expect(nativeElement.selectionStart).toBe(38);
expect(nativeElement.selectionEnd).toBe(38);
data = new DataTransfer();
data.items.add('de27100777770209299700', 'text/plain');
pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(0, 38);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = 'de27100777770209299700';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(maskInstance.mask).toBe('SS00 0000 0000 0000 0000 00');
expect(nativeElement.value).toBe('DE27 1007 7777 0209 2997 00');
expect(nativeElement.selectionStart).toBe(27);
expect(nativeElement.selectionEnd).toBe(27);
});
it('pasting with invalid country code', () => {
createTestComponent(BasicIbanMaskComponent);
let data = new DataTransfer();
data.items.add('DE89370400440532013000', 'text/plain');
let pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(0, 2);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = 'DE89370400440532013000';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(nativeElement.value).toBe('DE89 3704 0044 0532 0130 00');
expect(nativeElement.selectionStart).toBe(27);
expect(nativeElement.selectionEnd).toBe(27);
data = new DataTransfer();
data.items.add('DI27100777770209299700', 'text/plain');
pasteEvent = new ClipboardEvent('paste', {clipboardData: data} as ClipboardEventInit);
nativeElement.setSelectionRange(0, 27);
nativeElement.dispatchEvent(pasteEvent);
nativeElement.value = 'DI27100777770209299700';
nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
expect(maskInstance.mask).toBe('SS');
expect(nativeElement.value).toBe('DI');
expect(nativeElement.selectionStart).toBe(2);
expect(nativeElement.selectionEnd).toBe(2);
});
});
describe('validation', () => {
it('should mark as invalid and touch input immediately for non-existing country code', () => {
createTestComponent(FormIbanMaskComponent);
expect(testInstance.testForm.touched).toBe(false);
assertInputValue(nativeElement, 'GD', 'GD');
expect(testInstance.testForm.valid).toBe(false);
expect(testInstance.testForm.touched).toBe(true);
expect(testInstance.testForm.get('maskInput')!.value).toBe('GD');
});
it('should mark as invalid if iban is not valid', () => {
createTestComponent(FormIbanMaskComponent);
// quick solution for getting the mask updated after entering the first to letters
assertInputValue(nativeElement, 'DE', 'DE');
assertInputValue(nativeElement, 'DE89370400440532013001', 'DE89 3704 0044 0532 0130 01');
expect(testInstance.testForm.valid).toBe(false);
expect(testInstance.testForm.get('maskInput')!.value).toBe('DE89 3704 0044 0532 0130 01');
assertInputValue(nativeElement, 'DE89370400440532013000', 'DE89 3704 0044 0532 0130 00');
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.value).toBe('DE89 3704 0044 0532 0130 00');
assertInputValue(nativeElement, 'DE89370400440532013002', 'DE89 3704 0044 0532 0130 02');
expect(testInstance.testForm.valid).toBe(false);
expect(testInstance.testForm.get('maskInput')!.value).toBe('DE89 3704 0044 0532 0130 02');
});
it('should not do iban valdation on mask validation turned off', () => {
createTestComponent(FormIbanMaskComponent);
expect(maskInstance.validateMask).toBe(true);
testInstance.validateMask = false;
fixture.detectChanges();
assertInputValue(nativeElement, 'GD', 'GD');
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.value).toBe('GD');
// quick solution for getting the mask updated after entering the first to letters
assertInputValue(nativeElement, 'DE', 'DE');
assertInputValue(nativeElement, 'DE89370400440532013001', 'DE89 3704 0044 0532 0130 01');
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.value).toBe('DE89 3704 0044 0532 0130 01');
assertInputValue(nativeElement, 'DE89370400440532013000', 'DE89 3704 0044 0532 0130 00');
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.value).toBe('DE89 3704 0044 0532 0130 00');
assertInputValue(nativeElement, 'DE89370400440532013002', 'DE89 3704 0044 0532 0130 02');
expect(testInstance.testForm.valid).toBe(true);
expect(testInstance.testForm.get('maskInput')!.value).toBe('DE89 3704 0044 0532 0130 02');
});
});
describe('test real ibans', () => {
it('test test-ibans from iban.js', () => {
createTestComponent(FormIbanMaskComponent);
testIban('AD1200012030200359100100', 'AD12 0001 2030 2003 5910 0100');
testIban('AE070331234567890123456', 'AE07 0331 2345 6789 0123 456');
testIban('AL47212110090000000235698741', 'AL47 2121 1009 0000 0002 3569 8741');
testIban('AT611904300234573201', 'AT61 1904 3002 3457 3201');
testIban('AZ21NABZ00000000137010001944', 'AZ21 NABZ 0000 0000 1370 1000 1944');
testIban('BA391290079401028494', 'BA39 1290 0794 0102 8494');
testIban('BE68539007547034', 'BE68 5390 0754 7034');
testIban('BG80BNBG96611020345678', 'BG80 BNBG 9661 1020 3456 78');
testIban('BH67BMAG00001299123456', 'BH67 BMAG 0000 1299 1234 56');
testIban('BR9700360305000010009795493P1', 'BR97 0036 0305 0000 1000 9795 493P 1');
testIban('BY13NBRB3600900000002Z00AB00', 'BY13 NBRB 3600 9000 0000 2Z00 AB00');
testIban('CH9300762011623852957', 'CH93 0076 2011 6238 5295 7');
testIban('CR72012300000171549015', 'CR72 0123 0000 0171 5490 15');
testIban('CY17002001280000001200527600', 'CY17 0020 0128 0000 0012 0052 7600');
testIban('CZ6508000000192000145399', 'CZ65 0800 0000 1920 0014 5399');
testIban('DE89370400440532013000', 'DE89 3704 0044 0532 0130 00');
testIban('DK5000400440116243', 'DK50 0040 0440 1162 43');
testIban('DO28BAGR00000001212453611324', 'DO28 BAGR 0000 0001 2124 5361 1324');
testIban('EE382200221020145685', 'EE38 2200 2210 2014 5685');
testIban('ES9121000418450200051332', 'ES91 2100 0418 4502 0005 1332');
testIban('FI2112345600000785', 'FI21 1234 5600 0007 85');
testIban('FO6264600001631634', 'FO62 6460 0001 6316 34');
testIban('FR1420041010050500013M02606', 'FR14 2004 1010 0505 0001 3M02 606');
testIban('GB29NWBK60161331926819', 'GB29 NWBK 6016 1331 9268 19');
testIban('GE29NB0000000101904917', 'GE29 NB00 0000 0101 9049 17');
testIban('GI75NWBK000000007099453', 'GI75 NWBK 0000 0000 7099 453');
testIban('GL8964710001000206', 'GL89 6471 0001 0002 06');
testIban('GR1601101250000000012300695', 'GR16 0110 1250 0000 0001 2300 695');
testIban('GT82TRAJ01020000001210029690', 'GT82 TRAJ 0102 0000 0012 1002 9690');
testIban('HR1210010051863000160', 'HR12 1001 0051 8630 0016 0');
testIban('HU42117730161111101800000000', 'HU42 1177 3016 1111 1018 0000 0000');
testIban('IE29AIBK93115212345678', 'IE29 AIBK 9311 5212 3456 78');
testIban('IL620108000000099999999', 'IL62 0108 0000 0009 9999 999');
testIban('IS140159260076545510730339', 'IS14 0159 2600 7654 5510 7303 39');
testIban('IT60X0542811101000000123456', 'IT60 X054 2811 1010 0000 0123 456');
testIban('IQ98NBIQ850123456789012', 'IQ98 NBIQ 8501 2345 6789 012');
testIban('JO15AAAA1234567890123456789012', 'JO15 AAAA 1234 5678 9012 3456 7890 12');
testIban('KW81CBKU0000000000001234560101', 'KW81 CBKU 0000 0000 0000 1234 5601 01');
testIban('KZ86125KZT5004100100', 'KZ86 125K ZT50 0410 0100');
testIban('LB62099900000001001901229114', 'LB62 0999 0000 0001 0019 0122 9114');
testIban('LC07HEMM000100010012001200013015', 'LC07 HEMM 0001 0001 0012 0012 0001 3015');
testIban('LI21088100002324013AA', 'LI21 0881 0000 2324 013A A');
testIban('LT121000011101001000', 'LT12 1000 0111 0100 1000');
testIban('LU280019400644750000', 'LU28 0019 4006 4475 0000');
testIban('LV80BANK0000435195001', 'LV80 BANK 0000 4351 9500 1');
testIban('MC5811222000010123456789030', 'MC58 1122 2000 0101 2345 6789 030');
testIban('MD24AG000225100013104168', 'MD24 AG00 0225 1000 1310 4168');
testIban('ME25505000012345678951', 'ME25 5050 0001 2345 6789 51');
testIban('MK07250120000058984', 'MK07 2501 2000 0058 984');
testIban('MR1300020001010000123456753', 'MR13 0002 0001 0100 0012 3456 753');
testIban('MT84MALT011000012345MTLCAST001S', 'MT84 MALT 0110 0001 2345 MTLC AST0 01S');
testIban('MU17BOMM0101101030300200000MUR', 'MU17 BOMM 0101 1010 3030 0200 000M UR');
testIban('NL91ABNA0417164300', 'NL91 ABNA 0417 1643 00');
testIban('NO9386011117947', 'NO93 8601 1117 947');
testIban('PK36SCBL0000001123456702', 'PK36 SCBL 0000 0011 2345 6702');
testIban('PL61109010140000071219812874', 'PL61 1090 1014 0000 0712 1981 2874');
testIban('PS92PALS000000000400123456702', 'PS92 PALS 0000 0000 0400 1234 5670 2');
testIban('PT50000201231234567890154', 'PT50 0002 0123 1234 5678 9015 4');
testIban('QA30AAAA123456789012345678901', 'QA30 AAAA 1234 5678 9012 3456 7890 1');
testIban('RO49AAAA1B31007593840000', 'RO49 AAAA 1B31 0075 9384 0000');
testIban('RS35260005601001611379', 'RS35 2600 0560 1001 6113 79');
testIban('SA0380000000608010167519', 'SA03 8000 0000 6080 1016 7519');
testIban('SC18SSCB11010000000000001497USD', 'SC18 SSCB 1101 0000 0000 0000 1497 USD');
testIban('SE4550000000058398257466', 'SE45 5000 0000 0583 9825 7466');
testIban('SI56263300012039086', 'SI56 2633 0001 2039 086');
testIban('SK3112000000198742637541', 'SK31 1200 0000 1987 4263 7541');
testIban('SM86U0322509800000000270100', 'SM86 U032 2509 8000 0000 0270 100');
testIban('ST68000100010051845310112', 'ST68 0001 0001 0051 8453 1011 2');
testIban('SV62CENR00000000000000700025', 'SV62 CENR 0000 0000 0000 0070 0025');
testIban('TL380080012345678910157', 'TL38 0080 0123 4567 8910 157');
testIban('TN5910006035183598478831', 'TN59 1000 6035 1835 9847 8831');
testIban('TR330006100519786457841326', 'TR33 0006 1005 1978 6457 8413 26');
testIban('UA511234567890123456789012345', 'UA51 1234 5678 9012 3456 7890 1234 5');
testIban('VA59001123000012345678', 'VA59 0011 2300 0012 3456 78');
testIban('VG96VPVG0000012345678901', 'VG96 VPVG 0000 0123 4567 8901');
testIban('XK051212012345678906', 'XK05 1212 0123 4567 8906');
// The following countries are not included in the official IBAN registry but use the IBAN specification
testIban('AO69123456789012345678901', 'AO69 1234 5678 9012 3456 7890 1');
testIban('BF2312345678901234567890123', 'BF23 1234 5678 9012 3456 7890 123');
testIban('BI41123456789012', 'BI41 1234 5678 9012');
testIban('BJ39123456789012345678901234', 'BJ39 1234 5678 9012 3456 7890 1234');
testIban('CI70CI1234567890123456789012', 'CI70 CI12 3456 7890 1234 5678 9012');
testIban('CM9012345678901234567890123', 'CM90 1234 5678 9012 3456 7890 123');
testIban('CV30123456789012345678901', 'CV30 1234 5678 9012 3456 7890 1');
testIban('DZ8612345678901234567890', 'DZ86 1234 5678 9012 3456 7890');
testIban('IR861234568790123456789012', 'IR86 1234 5687 9012 3456 7890 12');
testIban('MG1812345678901234567890123', 'MG18 1234 5678 9012 3456 7890 123');
testIban('ML15A12345678901234567890123', 'ML15 A123 4567 8901 2345 6789 0123');
testIban('MZ25123456789012345678901', 'MZ25 1234 5678 9012 3456 7890 1');
testIban('SN52A12345678901234567890123', 'SN52 A123 4567 8901 2345 6789 0123');
});
});
});
@Component({
template: `
<input nxMask nxIbanMask/>
`
})
class BasicIbanMaskComponent extends IbanMaskTest {}
@Component({
template: `
<form [formGroup]="testForm">
<input nxMask nxIbanMask formControlName="maskInput" [validateMask]="validateMask"/>
</form>
`
})
class FormIbanMaskComponent extends IbanMaskTest {}
@Component({
template: `
<form [formGroup]="testForm">
<input nxMask nxIbanMask formControlName="maskInput" [validateMask]="validateMask"/>
</form>
`
})
class FormWithInitalIbanMaskComponent extends IbanMaskTest {
testForm: FormGroup = new FormGroup({
maskInput: new FormControl('NL91 ABNA 0417 1643 00', {})
});
} | the_stack |
import { ThemeColorDefinition } from '@fluentui-react-native/theme-types';
import { getCurrentAppearance } from '@fluentui-react-native/theming-utils';
import { AppleSemanticPalette, FluentUIApplePalette } from './appleColors.types.macos';
import { PlatformColor, DynamicColorMacOS, ColorWithSystemEffectMacOS } from 'react-native-macos';
import { Appearance } from 'react-native';
import { createMacOSAliasTokens } from './createMacOSAliasTokens';
/** Creates a Palette of PlatformColors defined for macOS */
export function getAppleSemanticPalette(): AppleSemanticPalette {
return {
labelColor: PlatformColor('labelColor'),
secondaryLabelColor: PlatformColor('secondaryLabelColor'),
tertiaryLabelColor: PlatformColor('tertiaryLabelColor'),
quaternaryLabelColor: PlatformColor('quaternaryLabelColor'),
textColor: PlatformColor('textColor'),
placeholderTextColor: PlatformColor('placeholderTextColor'),
textBackgroundColor: PlatformColor('textBackgroundColor'),
selectedTextColor: PlatformColor('selectedTexColor'),
selectedTextBackgroundColor: PlatformColor('selectedTextBackgroundColor'),
keyboardFocusIndicatorColor: PlatformColor('keyboardFocusIndicatorColor'),
unemphasizedSelectedTextColor: PlatformColor('unemphasizedSelectedTextColor'),
unemphasizedSelectedTextBackgroundColor: PlatformColor('unemphasizedSelectedTextBackgroundColor'),
linkColor: PlatformColor('linkColor'),
separatorColor: PlatformColor('separatorColor'),
selectedContentBackgroundColor: PlatformColor('selectedContentBackgroundColor'),
unemphasizedSelectedContentBackgroundColor: PlatformColor('unemphasizedSelectedContentBackgroundColor'),
selectedMenuItemTextColor: PlatformColor('selectedMenuItemTextColor'),
gridColor: PlatformColor('gridColor'),
headerTextColor: PlatformColor('headerTextColor'),
alternatingOddContentBackgroundColor: PlatformColor('alternatingOddContentBackgroundColor'),
alternatingEvenContentBackgroundColor: PlatformColor('alternatingOddContentBackgroundColor'),
controlAccentColor: PlatformColor('controlAccentColor'),
controlColor: PlatformColor('controlColor'),
controlBackgroundColor: PlatformColor('controlBackgroundColor'),
controlTextColor: PlatformColor('controlTextColor'),
disabledControlTextColor: PlatformColor('disabledControlTextColor'),
selectedControlColor: PlatformColor('selectedControlColor'),
selectedControlTextColor: PlatformColor('selectedControlTextColor'),
alternateSelectedControlTextColor: PlatformColor('alternateSelectedControlTextColor'),
scrubberTexturedBackground: PlatformColor('scrubberTexturedBackground'),
windowBackgroundColor: PlatformColor('windowBackgroundColor'),
windowFrameTextColor: PlatformColor('windowFrameTextColor'),
underPageBackgroundColor: PlatformColor('underPageBackgroundColor'),
findHighlightColor: PlatformColor('findHighlightColor'),
highlightColor: PlatformColor('highlightColor'),
shadowColor: PlatformColor('shadowColor'),
};
}
function getFluentUIApplePalette(): FluentUIApplePalette {
const appearance = Appearance.getColorScheme();
const mode = getCurrentAppearance(appearance, 'light');
const macOSAliasColorTokens = createMacOSAliasTokens(mode);
return {
blue10: '#4F6BED',
blueMagenta20: '#8764B8',
blueMagenta30: '#5C2E91',
communicationBlue: DynamicColorMacOS({
light: '#0078D4',
dark: '#1890F1',
}),
communicationBlueShade10: DynamicColorMacOS({
light: '#106EBE',
dark: '#1890F1',
}),
communicationBlueShade20: DynamicColorMacOS({
light: '#005A9E',
dark: '#3AA0F3',
}),
communicationBlueShade30: DynamicColorMacOS({
light: '#004578',
dark: '#6CB8F6',
}),
communicationBlueTint10: DynamicColorMacOS({
light: '#2B88D8',
dark: '#0078D4',
}),
communicationBlueTint20: DynamicColorMacOS({
light: '#C7E0F4',
dark: '#004C87',
}),
communicationBlueTint30: DynamicColorMacOS({
light: '#DEECF9',
dark: '#043862',
}),
communicationBlueTint40: DynamicColorMacOS({
light: '#EFF6FC',
dark: '#092C47',
}),
cyan20: '#038387',
cyan30: '#005B70',
cyanBlue10: '#0078D4',
cyanBlue20: '#004E8C',
dangerPrimary: DynamicColorMacOS({
light: '#D92C2C',
dark: '#clear',
}),
dangerShade10: DynamicColorMacOS({
light: '#C32727',
dark: '#clear',
}),
dangerShade20: DynamicColorMacOS({
light: '#A52121',
dark: '#clear',
}),
dangerShade30: DynamicColorMacOS({
light: '#791818',
dark: '#clear',
}),
dangerTint10: DynamicColorMacOS({
light: '#DD4242',
dark: '#clear',
}),
dangerTint20: DynamicColorMacOS({
light: '#E87979',
dark: '#clear',
}),
dangerTint30: DynamicColorMacOS({
light: '#F4B9B9',
dark: '#clear',
}),
dangerTint40: DynamicColorMacOS({
light: '#F9D9D9',
dark: '#clear',
}),
gray20: '#69797E',
gray25: '#F8F8F8',
gray30: '#7A7574',
gray40: '#393939',
gray50: '#F1F1F1',
gray100: '#E1E1E1',
gray200: '#C8C8C8',
gray300: '#ACACAC',
gray400: '#919191',
gray500: '#6E6E6E',
gray600: '#404040',
gray700: '#303030',
gray800: '#292929',
gray900: '#212121',
gray950: '#141414',
green10: '#498205',
green20: '#0B6A0B',
magenta10: '#C239B3',
magenta20: '#881798',
magentaPink10: '#E3008C',
orange20: '#CA5010',
orange30: '#8E562E',
orangeYellow20: '#986F0B',
pinkRed10: '#750B1C',
presenceAvailable: DynamicColorMacOS({
light: '#6BB700',
dark: '#92C353',
}),
presenceAway: DynamicColorMacOS({
light: '#FFAA44',
dark: '#F8D22A',
}),
presenceBlocked: DynamicColorMacOS({
light: '#C50F1F',
dark: '#D74553',
}),
presenceBusy: DynamicColorMacOS({
light: '#C50F1F',
dark: '#D74553',
}),
presenceDnd: DynamicColorMacOS({
light: '#C50F1F',
dark: '#D74553',
}),
presenceOffline: DynamicColorMacOS({
light: '#8A8886',
dark: '#979593',
}),
presenceOof: DynamicColorMacOS({
light: '#B4009E',
dark: '#E959D9',
}),
presenceUnknown: DynamicColorMacOS({
light: '#8A8886',
dark: '#979593',
}),
red10: '#D13438',
red20: '#A4262C',
successPrimary: DynamicColorMacOS({
light: '#13A10E',
dark: '#979593',
}),
successShade10: DynamicColorMacOS({
light: '#11910D',
dark: '#20BA53',
}),
successShade20: DynamicColorMacOS({
light: '#0F7A0B',
dark: '#3BC569',
}),
successShade30: DynamicColorMacOS({
light: '#0B5A08',
dark: '#67D48B',
}),
successTint10: DynamicColorMacOS({
light: '#27AC22',
dark: '#0D9D3D',
}),
successTint20: DynamicColorMacOS({
light: '#5EC65A',
dark: '#096B29',
}),
successTint30: DynamicColorMacOS({
light: '#A7E3A5',
dark: '#043615',
}),
successTint40: DynamicColorMacOS({
light: '#CEF0CD',
dark: '#021D0B',
}),
warningPrimary: DynamicColorMacOS({
light: '#FFD335',
dark: '#FFC328',
}),
warningShade10: DynamicColorMacOS({
light: '#E6BE30',
dark: '#FFC83E',
}),
warningShade20: DynamicColorMacOS({
light: '#C2A129',
dark: '#FFDD15',
}),
warningShade30: DynamicColorMacOS({
light: '#8F761E',
dark: '#FFDD87',
}),
warningTint10: DynamicColorMacOS({
light: '#FFD94E',
dark: '#E0AB24',
}),
warningTint20: DynamicColorMacOS({
light: '#FFE586',
dark: '#997518',
}),
warningTint30: DynamicColorMacOS({
light: '#FFF2C3',
dark: '#4D3A0C',
}),
warningTint40: DynamicColorMacOS({
light: '#FFF8DF',
dark: '#291F07',
}),
brandForegroundDisabled: DynamicColorMacOS({
light: '#2525253F',
dark: '#FFFFFF3F',
}),
brandBackgroundDisabled: DynamicColorMacOS({
light: '#2525253F',
dark: '#5656567F',
}),
brandedBackground: macOSAliasColorTokens.brandBackground,
brandBackgroundPressed: macOSAliasColorTokens.brandBackgroundPressed,
brandBackgroundHovered: macOSAliasColorTokens.brandBackgroundHover,
neutralBackgroundInverted: macOSAliasColorTokens.neutralBackgroundInverted,
neutralForegroundInverted: macOSAliasColorTokens.neutralForegroundInverted,
neutralForeground2: macOSAliasColorTokens.neutralForeground2,
neutralBackground2: macOSAliasColorTokens.neutralBackground2,
neutralStroke2: macOSAliasColorTokens.neutralStroke2,
neutralForeground3: macOSAliasColorTokens.neutralForeground3,
neutralBackground3: macOSAliasColorTokens.neutralBackground3,
neutralStrokeDisabled: macOSAliasColorTokens.neutralStrokeDisabled,
transparentBackground: macOSAliasColorTokens.transparentBackground,
};
}
/** Creates a palette of colors for the apple theme, given the FluentUI Apple Palette and Apple Semantic Palette
* The fallback palette is loaded while we wait for the native theming module to load, or if the module is not found
*/
export function fallbackApplePalette(): ThemeColorDefinition {
const fluentUIApple = getFluentUIApplePalette();
const applePlatform = getAppleSemanticPalette();
return {
/* PaletteBackgroundColors & PaletteTextColors */
background: applePlatform.windowBackgroundColor,
bodyStandoutBackground: applePlatform.underPageBackgroundColor,
bodyFrameBackground: applePlatform.windowBackgroundColor,
bodyFrameDivider: applePlatform.separatorColor,
bodyText: applePlatform.labelColor,
bodyTextChecked: applePlatform.labelColor,
subText: applePlatform.secondaryLabelColor,
bodyDivider: applePlatform.separatorColor,
disabledBackground: fluentUIApple.gray100,
disabledText: applePlatform.tertiaryLabelColor,
disabledBodyText: applePlatform.tertiaryLabelColor,
disabledSubtext: applePlatform.quaternaryLabelColor,
disabledBodySubtext: applePlatform.quaternaryLabelColor,
focusBorder: 'transparent',
variantBorder: applePlatform.separatorColor,
variantBorderHovered: applePlatform.separatorColor,
defaultStateBackground: applePlatform.controlBackgroundColor,
errorText: fluentUIApple.dangerPrimary,
warningText: fluentUIApple.warningPrimary,
errorBackground: fluentUIApple.dangerTint10,
blockingBackground: fluentUIApple.dangerTint10,
warningBackground: fluentUIApple.warningPrimary,
warningHighlight: fluentUIApple.warningTint10,
successBackground: fluentUIApple.successTint10,
inputBorder: applePlatform.separatorColor,
inputBorderHovered: applePlatform.separatorColor,
inputBackground: applePlatform.textBackgroundColor,
inputBackgroundChecked: applePlatform.textBackgroundColor,
inputBackgroundCheckedHovered: applePlatform.textBackgroundColor,
inputForegroundChecked: fluentUIApple.communicationBlue,
inputFocusBorderAlt: applePlatform.keyboardFocusIndicatorColor,
smallInputBorder: applePlatform.separatorColor,
inputText: applePlatform.textColor,
inputTextHovered: applePlatform.textColor,
inputPlaceholderText: applePlatform.placeholderTextColor,
// Set the default button tokens to match the Acrylic Button style
buttonBackground: fluentUIApple.neutralBackground3,
buttonBackgroundChecked: fluentUIApple.neutralBackground3,
buttonBackgroundHovered: fluentUIApple.neutralBackground3,
buttonBackgroundCheckedHovered: fluentUIApple.neutralBackground3,
buttonBackgroundPressed: ColorWithSystemEffectMacOS(fluentUIApple.neutralBackground3, 'pressed'),
buttonBackgroundDisabled: ColorWithSystemEffectMacOS(fluentUIApple.neutralBackground3, 'disabled'),
buttonBorder: fluentUIApple.transparentBackground,
buttonText: fluentUIApple.neutralForeground3,
buttonTextHovered: fluentUIApple.neutralForeground3,
buttonTextChecked: fluentUIApple.neutralForeground3,
buttonTextCheckedHovered: fluentUIApple.neutralForeground3,
buttonTextPressed: ColorWithSystemEffectMacOS(fluentUIApple.neutralForeground3, 'pressed'),
buttonTextDisabled: ColorWithSystemEffectMacOS(fluentUIApple.neutralForeground3, 'disabled'),
buttonBorderDisabled: fluentUIApple.transparentBackground,
buttonBorderFocused: fluentUIApple.transparentBackground,
primaryButtonBackground: fluentUIApple.communicationBlue,
primaryButtonBackgroundHovered: fluentUIApple.communicationBlue,
primaryButtonBackgroundPressed: ColorWithSystemEffectMacOS(fluentUIApple.communicationBlue, 'pressed'),
primaryButtonBackgroundDisabled: fluentUIApple.brandBackgroundDisabled,
primaryButtonBorder: 'transparent',
primaryButtonBorderFocused: 'transparent',
primaryButtonText: fluentUIApple.neutralForegroundInverted,
primaryButtonTextHovered: fluentUIApple.neutralForegroundInverted,
primaryButtonTextPressed: ColorWithSystemEffectMacOS(fluentUIApple.neutralForegroundInverted, 'pressed'),
primaryButtonTextDisabled: fluentUIApple.brandForegroundDisabled,
accentButtonBackground: fluentUIApple.communicationBlue,
accentButtonText: fluentUIApple.neutralForegroundInverted,
menuBackground: 'transparent',
menuDivider: applePlatform.separatorColor,
menuIcon: fluentUIApple.neutralForeground3, //GH:728 Icon doesn't support PlatformColor
menuHeader: applePlatform.headerTextColor,
menuItemBackgroundHovered: applePlatform.controlAccentColor,
menuItemBackgroundPressed: ColorWithSystemEffectMacOS(applePlatform.controlAccentColor, 'pressed'),
menuItemText: applePlatform.labelColor,
menuItemTextHovered: 'white',
listBackground: 'transparent',
listText: applePlatform.labelColor,
listItemBackgroundHovered: 'transparent',
listItemBackgroundChecked: 'transparent',
listItemBackgroundCheckedHovered: 'transparent',
listHeaderBackgroundHovered: applePlatform.headerTextColor,
listHeaderBackgroundPressed: applePlatform.headerTextColor,
actionLink: applePlatform.linkColor,
actionLinkHovered: applePlatform.linkColor,
link: applePlatform.linkColor,
linkHovered: applePlatform.linkColor,
linkPressed: applePlatform.selectedControlColor,
/* ControlColorTokens */
// Set the default button tokens to match the Acrylic Button style
defaultBackground: fluentUIApple.neutralBackground3,
defaultBorder: 'transparent',
defaultContent: fluentUIApple.neutralForeground3,
defaultIcon: fluentUIApple.neutralForeground3, //GH:728 Icon doesn't support PlatformColor
defaultHoveredBackground: fluentUIApple.neutralBackground3,
defaultHoveredBorder: 'transparent',
defaultHoveredContent: fluentUIApple.neutralForeground3,
defaultHoveredIcon: fluentUIApple.neutralForeground3, //GH:728 Icon doesn't support PlatformColor
defaultFocusedBackground: fluentUIApple.neutralBackground3,
defaultFocusedBorder: 'transparent',
defaultFocusedContent: fluentUIApple.neutralForeground3,
defaultFocusedIcon: fluentUIApple.neutralForeground3, //GH:728 Icon doesn't support PlatformColor
defaultPressedBackground: ColorWithSystemEffectMacOS(fluentUIApple.neutralBackground3, 'pressed'),
defaultPressedBorder: 'transparent',
defaultPressedContent: ColorWithSystemEffectMacOS(fluentUIApple.neutralForeground3, 'pressed'),
defaultPressedIcon: fluentUIApple.neutralForeground3, //GH:728 Icon doesn't support PlatformColor
defaultDisabledBackground: fluentUIApple.neutralStrokeDisabled,
defaultDisabledBorder: 'transparent',
defaultDisabledContent: ColorWithSystemEffectMacOS(fluentUIApple.neutralForeground3, 'pressed'),
defaultDisabledIcon: fluentUIApple.neutralForeground3, //GH:728 Icon doesn't support PlatformColor
ghostBackground: 'transparent',
ghostBorder: 'transparent',
ghostContent: fluentUIApple.communicationBlue,
ghostIcon: fluentUIApple.communicationBlue,
ghostHoveredBackground: 'transparent',
ghostHoveredBorder: 'transparent',
ghostHoveredContent: fluentUIApple.communicationBlue,
ghostHoveredIcon: fluentUIApple.communicationBlue,
ghostFocusedBackground: 'transparent',
ghostFocusedBorder: 'transparent',
ghostFocusedContent: fluentUIApple.communicationBlue,
ghostFocusedIcon: fluentUIApple.communicationBlue,
ghostPressedBackground: 'transparent',
ghostPressedBorder: 'transparent',
ghostPressedContent: ColorWithSystemEffectMacOS(fluentUIApple.communicationBlue, 'deepPressed'),
ghostPressedIcon: fluentUIApple.neutralForeground3, //GH:728 Icon doesn't support PlatformColor
ghostDisabledBackground: 'transparent',
ghostDisabledBorder: 'transparent',
ghostDisabledContent: fluentUIApple.brandForegroundDisabled,
ghostDisabledIcon: fluentUIApple.brandForegroundDisabled,
brandedBackground: fluentUIApple.brandedBackground,
brandedBorder: 'transparent',
brandedContent: fluentUIApple.neutralForegroundInverted,
brandedIcon: fluentUIApple.neutralForegroundInverted,
brandedHoveredBackground: fluentUIApple.brandBackgroundHovered,
brandedHoveredBorder: 'transparent',
brandedHoveredContent: fluentUIApple.neutralForegroundInverted,
brandedHoveredIcon: fluentUIApple.neutralForegroundInverted,
brandedFocusedBackground: fluentUIApple.communicationBlue,
brandedFocusedBorder: 'transparent',
brandedFocusedContent: fluentUIApple.neutralForegroundInverted,
brandedFocusedIcon: fluentUIApple.neutralForegroundInverted,
brandedPressedBackground: fluentUIApple.brandBackgroundPressed, //ColorWithSystemEffectMacOS(fluentUIApple.communicationBlue, 'pressed'),
brandedPressedBorder: 'transparent',
brandedPressedContent: fluentUIApple.neutralForegroundInverted,
brandedPressedIcon: fluentUIApple.neutralForegroundInverted,
brandedDisabledBackground: fluentUIApple.brandBackgroundDisabled,
brandedDisabledBorder: 'transparent',
brandedDisabledContent: fluentUIApple.brandForegroundDisabled,
brandedDisabledIcon: fluentUIApple.neutralForeground3, //GH:728 Icon doesn't support PlatformColor
defaultCheckedBackground: fluentUIApple.communicationBlue,
defaultCheckedContent: fluentUIApple.neutralForegroundInverted,
defaultCheckedHoveredBackground: fluentUIApple.communicationBlue,
defaultCheckedHoveredContent: fluentUIApple.neutralForegroundInverted,
brandedCheckedBackground: fluentUIApple.communicationBlue,
brandedCheckedContent: fluentUIApple.neutralForegroundInverted,
brandedCheckedHoveredBackground: fluentUIApple.communicationBlue,
brandedCheckedHoveredContent: fluentUIApple.neutralForegroundInverted,
ghostCheckedBackground: 'transparent',
ghostCheckedContent: fluentUIApple.communicationBlue,
ghostCheckedHoveredBackground: 'transparent',
ghostCheckedHoveredContent: fluentUIApple.communicationBlue,
ghostCheckedHoveredBorder: 'transparent',
ghostSecondaryContent: fluentUIApple.communicationBlue,
ghostFocusedSecondaryContent: fluentUIApple.communicationBlue,
ghostHoveredSecondaryContent: fluentUIApple.communicationBlue,
ghostPressedSecondaryContent: ColorWithSystemEffectMacOS(fluentUIApple.communicationBlue, 'deepPressed'),
brandedSecondaryContent: fluentUIApple.neutralForegroundInverted,
brandedFocusedSecondaryContent: fluentUIApple.neutralForegroundInverted,
brandedHoveredSecondaryContent: fluentUIApple.neutralForegroundInverted,
brandedPressedSecondaryContent: ColorWithSystemEffectMacOS(fluentUIApple.neutralForegroundInverted, 'pressed'),
defaultDisabledSecondaryContent: fluentUIApple.brandForegroundDisabled,
defaultHoveredSecondaryContent: fluentUIApple.neutralForeground3,
defaultPressedSecondaryContent: fluentUIApple.neutralForegroundInverted,
checkboxBackground: fluentUIApple.communicationBlue,
checkboxBackgroundDisabled: fluentUIApple.brandBackgroundDisabled,
checkboxBorderColor: fluentUIApple.gray600,
checkmarkColor: fluentUIApple.neutralForegroundInverted,
personaActivityRing: fluentUIApple.neutralForegroundInverted,
personaActivityGlow: fluentUIApple.red10,
};
} | the_stack |
import {
AnimationOptionMixin,
AnimationDelayCallbackParam,
PayloadAnimationPart,
AnimationOption
} from '../util/types';
import { AnimationEasing } from 'zrender/src/animation/easing';
import Element, { ElementAnimateConfig } from 'zrender/src/Element';
import Model from '../model/Model';
import {
isObject,
retrieve2
} from 'zrender/src/core/util';
import Displayable from 'zrender/src/graphic/Displayable';
import Group from 'zrender/src/graphic/Group';
import { makeInner } from '../util/model';
// Stored properties for further transition.
export const transitionStore = makeInner<{
oldStyle: Displayable['style']
}, Displayable>();
type AnimateOrSetPropsOption = {
dataIndex?: number;
cb?: () => void;
during?: (percent: number) => void;
removeOpt?: AnimationOption
isFrom?: boolean;
};
/**
* Return null if animation is disabled.
*/
export function getAnimationConfig(
animationType: 'init' | 'update' | 'remove',
animatableModel: Model<AnimationOptionMixin>,
dataIndex: number,
// Extra opts can override the option in animatable model.
extraOpts?: Pick<ElementAnimateConfig, 'easing' | 'duration' | 'delay'>,
// TODO It's only for pictorial bar now.
extraDelayParams?: unknown
): Pick<ElementAnimateConfig, 'easing' | 'duration' | 'delay'> | null {
let animationPayload: PayloadAnimationPart;
// Check if there is global animation configuration from dataZoom/resize can override the config in option.
// If animation is enabled. Will use this animation config in payload.
// If animation is disabled. Just ignore it.
if (animatableModel && animatableModel.ecModel) {
const updatePayload = animatableModel.ecModel.getUpdatePayload();
animationPayload = (updatePayload && updatePayload.animation) as PayloadAnimationPart;
}
const animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
const isUpdate = animationType === 'update';
if (animationEnabled) {
let duration: number | Function;
let easing: AnimationEasing;
let delay: number | Function;
if (extraOpts) {
duration = retrieve2(extraOpts.duration, 200);
easing = retrieve2(extraOpts.easing, 'cubicOut');
delay = 0;
}
else {
duration = animatableModel.getShallow(
isUpdate ? 'animationDurationUpdate' : 'animationDuration'
);
easing = animatableModel.getShallow(
isUpdate ? 'animationEasingUpdate' : 'animationEasing'
);
delay = animatableModel.getShallow(
isUpdate ? 'animationDelayUpdate' : 'animationDelay'
);
}
// animation from payload has highest priority.
if (animationPayload) {
animationPayload.duration != null && (duration = animationPayload.duration);
animationPayload.easing != null && (easing = animationPayload.easing);
animationPayload.delay != null && (delay = animationPayload.delay);
}
if (typeof delay === 'function') {
delay = delay(
dataIndex as number,
extraDelayParams
);
}
if (typeof duration === 'function') {
duration = duration(dataIndex as number);
}
const config = {
duration: duration as number || 0,
delay: delay as number,
easing
};
return config;
}
else {
return null;
}
}
function animateOrSetProps<Props>(
animationType: 'init' | 'update' | 'remove',
el: Element<Props>,
props: Props,
animatableModel?: Model<AnimationOptionMixin> & {
getAnimationDelayParams?: (el: Element<Props>, dataIndex: number) => AnimationDelayCallbackParam
},
dataIndex?: AnimateOrSetPropsOption['dataIndex'] | AnimateOrSetPropsOption['cb'] | AnimateOrSetPropsOption,
cb?: AnimateOrSetPropsOption['cb'] | AnimateOrSetPropsOption['during'],
during?: AnimateOrSetPropsOption['during']
) {
let isFrom = false;
let removeOpt: AnimationOption;
if (typeof dataIndex === 'function') {
during = cb;
cb = dataIndex;
dataIndex = null;
}
else if (isObject(dataIndex)) {
cb = dataIndex.cb;
during = dataIndex.during;
isFrom = dataIndex.isFrom;
removeOpt = dataIndex.removeOpt;
dataIndex = dataIndex.dataIndex;
}
const isRemove = (animationType === 'remove');
if (!isRemove) {
// Must stop the remove animation.
el.stopAnimation('remove');
}
const animationConfig = getAnimationConfig(
animationType,
animatableModel,
dataIndex as number,
isRemove ? (removeOpt || {}) : null,
(animatableModel && animatableModel.getAnimationDelayParams)
? animatableModel.getAnimationDelayParams(el, dataIndex as number)
: null
);
if (animationConfig && animationConfig.duration > 0) {
const duration = animationConfig.duration;
const animationDelay = animationConfig.delay;
const animationEasing = animationConfig.easing;
const animateConfig: ElementAnimateConfig = {
duration: duration as number,
delay: animationDelay as number || 0,
easing: animationEasing,
done: cb,
force: !!cb || !!during,
// Set to final state in update/init animation.
// So the post processing based on the path shape can be done correctly.
setToFinal: !isRemove,
scope: animationType,
during: during
};
isFrom
? el.animateFrom(props, animateConfig)
: el.animateTo(props, animateConfig);
}
else {
el.stopAnimation();
// If `isFrom`, the props is the "from" props.
!isFrom && el.attr(props);
// Call during at least once.
during && during(1);
cb && (cb as AnimateOrSetPropsOption['cb'])();
}
}
/**
* Update graphic element properties with or without animation according to the
* configuration in series.
*
* Caution: this method will stop previous animation.
* So do not use this method to one element twice before
* animation starts, unless you know what you are doing.
* @example
* graphic.updateProps(el, {
* position: [100, 100]
* }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
* // Or
* graphic.updateProps(el, {
* position: [100, 100]
* }, seriesModel, function () { console.log('Animation done!'); });
*/
function updateProps<Props>(
el: Element<Props>,
props: Props,
// TODO: TYPE AnimatableModel
animatableModel?: Model<AnimationOptionMixin>,
dataIndex?: AnimateOrSetPropsOption['dataIndex'] | AnimateOrSetPropsOption['cb'] | AnimateOrSetPropsOption,
cb?: AnimateOrSetPropsOption['cb'] | AnimateOrSetPropsOption['during'],
during?: AnimateOrSetPropsOption['during']
) {
animateOrSetProps('update', el, props, animatableModel, dataIndex, cb, during);
}
export {updateProps};
/**
* Init graphic element properties with or without animation according to the
* configuration in series.
*
* Caution: this method will stop previous animation.
* So do not use this method to one element twice before
* animation starts, unless you know what you are doing.
*/
export function initProps<Props>(
el: Element<Props>,
props: Props,
animatableModel?: Model<AnimationOptionMixin>,
dataIndex?: AnimateOrSetPropsOption['dataIndex'] | AnimateOrSetPropsOption['cb'] | AnimateOrSetPropsOption,
cb?: AnimateOrSetPropsOption['cb'] | AnimateOrSetPropsOption['during'],
during?: AnimateOrSetPropsOption['during']
) {
animateOrSetProps('init', el, props, animatableModel, dataIndex, cb, during);
}
/**
* If element is removed.
* It can determine if element is having remove animation.
*/
export function isElementRemoved(el: Element) {
if (!el.__zr) {
return true;
}
for (let i = 0; i < el.animators.length; i++) {
const animator = el.animators[i];
if (animator.scope === 'remove') {
return true;
}
}
return false;
}
/**
* Remove graphic element
*/
export function removeElement<Props>(
el: Element<Props>,
props: Props,
animatableModel?: Model<AnimationOptionMixin>,
dataIndex?: AnimateOrSetPropsOption['dataIndex'] | AnimateOrSetPropsOption['cb'] | AnimateOrSetPropsOption,
cb?: AnimateOrSetPropsOption['cb'] | AnimateOrSetPropsOption['during'],
during?: AnimateOrSetPropsOption['during']
) {
// Don't do remove animation twice.
if (isElementRemoved(el)) {
return;
}
animateOrSetProps('remove', el, props, animatableModel, dataIndex, cb, during);
}
function fadeOutDisplayable(
el: Displayable,
animatableModel?: Model<AnimationOptionMixin>,
dataIndex?: number,
done?: AnimateOrSetPropsOption['cb']
) {
el.removeTextContent();
el.removeTextGuideLine();
removeElement(el, {
style: {
opacity: 0
}
}, animatableModel, dataIndex, done);
}
export function removeElementWithFadeOut(
el: Element,
animatableModel?: Model<AnimationOptionMixin>,
dataIndex?: number
) {
function doRemove() {
el.parent && el.parent.remove(el);
}
// Hide label and labelLine first
// TODO Also use fade out animation?
if (!el.isGroup) {
fadeOutDisplayable(el as Displayable, animatableModel, dataIndex, doRemove);
}
else {
(el as Group).traverse(function (disp: Displayable) {
if (!disp.isGroup) {
// Can invoke doRemove multiple times.
fadeOutDisplayable(disp as Displayable, animatableModel, dataIndex, doRemove);
}
});
}
}
/**
* Save old style for style transition in universalTransition module.
* It's used when element will be reused in each render.
* For chart like map, heatmap, which will always create new element.
* We don't need to save this because universalTransition can get old style from the old element
*/
export function saveOldStyle(el: Displayable) {
transitionStore(el).oldStyle = el.style;
}
export function getOldStyle(el: Displayable) {
return transitionStore(el).oldStyle;
} | the_stack |
import type { SinonSpy } from 'sinon';
import { utils, random, ready as cryptoReady, tcrypto, encryptionV4, encryptionV3 } from '@tanker/crypto';
import { DecryptionFailed, InvalidArgument } from '@tanker/errors';
import { expect, sinon, BufferingObserver, makeTimeoutPromise } from '@tanker/test-utils';
import { Writable } from '@tanker/stream-base';
import { DecryptionStream } from '../DecryptionStream';
import { PromiseWrapper } from '../../PromiseWrapper';
// Needed to run in IE without polyfilling `String.prototype.repeat()`
// extract from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat#polyfill
// without error checking
function repeat(string: string, c: number) {
let str = string;
let count = c;
if (str.length === 0 || count === 0)
return '';
const maxCount = str.length * count;
count = Math.floor(Math.log(count) / Math.log(2));
while (count) {
str += str;
count -= 1;
}
str += str.substring(0, maxCount - str.length);
return str;
}
describe('DecryptionStream', () => {
let buffer: Array<Uint8Array>;
let key: Uint8Array;
let resourceId: Uint8Array;
let mapper: { findKey: SinonSpy<any[], Promise<Uint8Array>> };
let stream: DecryptionStream;
let sync: PromiseWrapper<void>;
const watchStream = (str: DecryptionStream) => {
const pw = new PromiseWrapper<void>();
buffer = [];
str.on('data', (data: Uint8Array) => buffer.push(data));
str.on('error', (err: Error) => pw.reject(err));
str.on('end', () => pw.resolve());
return pw;
};
const encryptMsg = (index: number, str: string) => {
const clear = utils.fromString(str);
const encryptedChunkSize = encryptionV4.overhead + clear.length;
const encrypted = encryptionV4.serialize(encryptionV4.encrypt(key, index, resourceId, encryptedChunkSize, clear));
return { clear, encrypted };
};
before(() => cryptoReady);
beforeEach(() => {
key = random(tcrypto.SYMMETRIC_KEY_SIZE);
resourceId = random(16);
// Note: we don't use sinon.fake.resolves(key) that would bind the key
// now, as the key is overridden later in some tests ;-)
mapper = { findKey: sinon.fake(() => Promise.resolve(key)) };
stream = new DecryptionStream(mapper);
sync = watchStream(stream);
});
it('can extract header v4, resource id and message', async () => {
const msg = encryptMsg(0, '1st message');
const emptyMsg = encryptMsg(1, '');
stream.write(utils.concatArrays(msg.encrypted, emptyMsg.encrypted));
stream.end();
await expect(sync.promise).to.be.fulfilled;
expect(mapper.findKey.calledOnce).to.be.true;
expect(mapper.findKey.args[0]).to.deep.equal([resourceId]);
expect(buffer.length).to.equal(1);
expect(buffer[0]).to.deep.equal(msg.clear);
});
it('can decrypt chunks of fixed size', async () => {
const msg1 = encryptMsg(0, '1st message');
const msg2 = encryptMsg(1, '2nd message');
const emptyMsg = encryptMsg(2, '');
stream.write(msg1.encrypted);
stream.write(msg2.encrypted);
stream.write(emptyMsg.encrypted);
stream.end();
await expect(sync.promise).to.be.fulfilled;
expect(buffer.length).to.equal(2);
expect(buffer[0]).to.deep.equal(msg1.clear);
expect(buffer[1]).to.deep.equal(msg2.clear);
});
it('can decrypt chunks of fixed size except last one', async () => {
const msg1 = encryptMsg(0, '1st message');
const msg2 = encryptMsg(1, '2nd');
stream.write(msg1.encrypted);
stream.write(msg2.encrypted);
stream.end();
await expect(sync.promise).to.be.fulfilled;
expect(buffer.length).to.equal(2);
expect(buffer[0]).to.deep.equal(msg1.clear);
expect(buffer[1]).to.deep.equal(msg2.clear);
});
it('can decrypt a test vector (empty data)', async () => {
const emptyTestVector = new Uint8Array([
// version
0x4,
// encrypted chunk size
0x0, 0x0, 0x10, 0x0,
// resource id
0x5e, 0x44, 0x54, 0xa7, 0x83, 0x21, 0xd8, 0x77, 0x8c, 0x7a, 0x25, 0xc9,
0x46, 0x52, 0xa, 0x60,
// iv seed
0x1d, 0xb1, 0x25, 0xaf, 0x1e, 0x85, 0x84, 0xa9, 0xcf, 0x19, 0x71, 0x26,
0x79, 0xf3, 0x47, 0xd1, 0xf6, 0xf0, 0xf7, 0x2, 0x85, 0x47, 0xfb, 0xe8,
// (no encrypted data) + mac
0x5e, 0x16, 0x25, 0x33, 0xf6, 0x66, 0x7b, 0xb9, 0xd5, 0xa5, 0x1d, 0xe9,
0x23, 0x71, 0xb, 0x75,
]);
key = new Uint8Array([
0xda, 0xa5, 0x3d, 0x7, 0xc, 0x4b, 0x63, 0x54, 0xe3, 0x6f, 0x96, 0xc1,
0x14, 0x4c, 0x23, 0xcc, 0x16, 0x23, 0x52, 0xa1, 0xc5, 0x53, 0xe3, 0xea,
0xd9, 0xc4, 0x1d, 0x28, 0x4c, 0x45, 0x43, 0xa9,
]);
resourceId = new Uint8Array([
0x5e, 0x44, 0x54, 0xa7, 0x83, 0x21, 0xd8, 0x77, 0x8c, 0x7a, 0x25, 0xc9,
0x46, 0x52, 0xa, 0x60,
]);
stream.write(emptyTestVector);
stream.end();
await expect(sync.promise).to.be.fulfilled;
expect(mapper.findKey.calledOnce).to.be.true;
expect(mapper.findKey.args[0]).to.deep.equal([resourceId]);
expect(buffer.length).to.equal(0); // no data
});
it('can decrypt a test vector (with data)', async () => {
const testMessage = 'this is a secret';
const testVector = new Uint8Array([
// version
0x4,
// encrypted chunk size
0x0, 0x0, 0x10, 0x0,
// resource id
0xf2, 0x38, 0x50, 0x31, 0x6c, 0xfa, 0xaa, 0x96, 0x8c, 0x1b, 0x25, 0x43,
0xf4, 0x38, 0xe3, 0x61,
// iv seed
0x55, 0x24, 0x50, 0xe8, 0x3b, 0x3, 0xe9, 0xf6, 0x1, 0xf1, 0x73, 0x5f,
0x3e, 0x52, 0xb2, 0x8f, 0xc0, 0x1f, 0xd, 0xcd, 0xac, 0x8f, 0x5, 0x2a,
// encrypted data + mac
0xbd, 0x31, 0x32, 0xe, 0x16, 0xdd, 0x20, 0x40, 0x58, 0xa2, 0xfe, 0xc6,
0xf3, 0x5d, 0xff, 0x25, 0xe8, 0xc9, 0x33, 0xc1, 0x8, 0xe0, 0xb1, 0xb0,
0xb, 0xe4, 0x86, 0x8c, 0x36, 0xb8, 0x2f, 0xbf,
]);
key = new Uint8Array([
0xaf, 0x38, 0x67, 0x9d, 0x20, 0x56, 0x38, 0x6b, 0xef, 0xdd, 0x62, 0x6d,
0x60, 0x1b, 0xf9, 0x39, 0xad, 0x71, 0x43, 0xc0, 0x30, 0x14, 0xed, 0xea,
0x56, 0xff, 0x1f, 0x8a, 0x30, 0x90, 0xb6, 0x8b,
]);
resourceId = new Uint8Array([
0xf2, 0x38, 0x50, 0x31, 0x6c, 0xfa, 0xaa, 0x96, 0x8c, 0x1b, 0x25, 0x43,
0xf4, 0x38, 0xe3, 0x61,
]);
stream.write(testVector);
stream.end();
await expect(sync.promise).to.be.fulfilled;
expect(mapper.findKey.calledOnce).to.be.true;
expect(mapper.findKey.args[0]).to.deep.equal([resourceId]);
expect(buffer.length).to.equal(1);
expect(utils.toString(buffer[0]!)).to.equal(testMessage);
});
it('can decrypt a test vector (with multiple chunks)', async () => {
const testMessage = 'this is a secret';
const testVector = new Uint8Array([
// version
0x4,
// encrypted chunk size
0x46, 0x0, 0x0, 0x0,
// resource id
0x40, 0xec, 0x8d, 0x84, 0xad, 0xbe, 0x2b, 0x27, 0x32, 0xc9, 0xa, 0x1e,
0xc6, 0x8f, 0x2b, 0xdb,
// iv seed
0xcd, 0x7, 0xd0, 0x3a, 0xc8, 0x74, 0xe1, 0x8, 0x7e, 0x5e, 0xaa, 0xa2,
0x82, 0xd8, 0x8b, 0xf5, 0xed, 0x22, 0xe6, 0x30, 0xbb, 0xaa, 0x9d, 0x71,
// encrypted data + mac
0xe3, 0x9a, 0x4, 0x22, 0x67, 0x3d, 0xdf, 0xcf, 0x28, 0x48, 0xe2, 0xeb,
0x4b, 0xb4, 0x30, 0x92, 0x70, 0x23, 0x49, 0x1c, 0xc9, 0x31, 0xcb, 0xda,
0x1a,
// version
0x4,
// encrypted chunk size
0x46, 0, 0, 0,
// resource id
0x40, 0xec, 0x8d, 0x84, 0xad, 0xbe, 0x2b, 0x27, 0x32, 0xc9, 0xa, 0x1e,
0xc6, 0x8f, 0x2b, 0xdb,
// iv see
0x3f, 0x34, 0xf3, 0xd3, 0x23, 0x90, 0xfc, 0x6, 0x35, 0xda, 0x99, 0x1e,
0x81, 0xdf, 0x88, 0xfc, 0x21, 0x1e, 0xed, 0x3a, 0x28, 0x2d, 0x51, 0x82,
// encrypted data + mac
0x77, 0x7c, 0xf6, 0xbe, 0x54, 0xd4, 0x92, 0xcd, 0x86, 0xd4, 0x88, 0x55,
0x20, 0x1f, 0xd6, 0x44, 0x47, 0x30, 0x40, 0x2f, 0xe8, 0xf4, 0x50,
]);
key = new Uint8Array([
0xa, 0x7, 0x3d, 0xd0, 0x2c, 0x2d, 0x17, 0xf9, 0x49, 0xd9, 0x35, 0x8e, 0xf7,
0xfe, 0x7b, 0xd1, 0xf6, 0xb, 0xf1, 0x5c, 0xa4, 0x32, 0x1e, 0xe4, 0xaa, 0x18,
0xe1, 0x97, 0xbf, 0xf4, 0x5e, 0xfe,
]);
resourceId = new Uint8Array([
0x40, 0xec, 0x8d, 0x84, 0xad, 0xbe, 0x2b, 0x27, 0x32, 0xc9, 0xa, 0x1e, 0xc6,
0x8f, 0x2b, 0xdb,
]);
stream.write(testVector);
stream.end();
await expect(sync.promise).to.be.fulfilled;
expect(mapper.findKey.calledOnce).to.be.true;
expect(mapper.findKey.args[0]).to.deep.equal([resourceId]);
expect(buffer.length).to.equal(2);
expect(utils.toString(utils.concatArrays(...buffer))).to.equal(testMessage);
});
describe('Errors', () => {
let chunks: Array<Uint8Array>;
beforeEach(async () => {
const msg1 = encryptMsg(0, '1st message');
const msg2 = encryptMsg(1, '2nd message');
chunks = [msg1.encrypted, msg2.encrypted];
});
it('throws InvalidArgument when writing anything else than Uint8Array', async () => {
stream.write('fail');
await expect(sync.promise).to.be.rejectedWith(InvalidArgument);
});
it('throws DecryptionFailed when missing empty chunk after only maximum size chunks', async () => {
stream.write(chunks[0]!); // valid chunk of the maximum size
stream.end();
await expect(sync.promise).to.be.rejectedWith(DecryptionFailed);
});
it('throws DecryptionFailed when data is corrupted', async () => {
chunks[0]![61] += 1;
stream.write(chunks[0]!); // corrupted chunk
await expect(sync.promise).to.be.rejectedWith(DecryptionFailed);
});
it('throws InvalidArgument when the header is not fully given during first write', async () => {
const incompleteHeader = chunks[0]!.subarray(0, 1);
stream.write(incompleteHeader);
await expect(sync.promise).to.be.rejectedWith(InvalidArgument);
});
it('throws InvalidArgument when the header is corrupted', async () => {
chunks[0]![0] = 255; // unknown version number
stream.write(chunks[0]);
await expect(sync.promise).to.be.rejectedWith(InvalidArgument);
});
it('throws DecryptionFailed when data is written in wrong order', async () => {
stream.write(chunks[1]!);
await expect(sync.promise).to.be.rejectedWith(DecryptionFailed);
});
it('forwards the error when the key is not found for a small resource', async () => {
const unknownKey = random(tcrypto.SYMMETRIC_KEY_SIZE);
mapper.findKey = sinon.fake(() => {
throw new InvalidArgument('some error');
});
const chunk = encryptionV3.serialize(encryptionV3.encrypt(unknownKey, utils.fromString('some random data')));
stream.write(chunk);
stream.end();
await expect(sync.promise).to.be.rejectedWith(InvalidArgument, 'some error');
});
it('forwards the error when the key is not found for a large resource', async () => {
mapper.findKey = sinon.fake(() => {
throw new InvalidArgument('some error');
});
stream.write(chunks[0]);
await expect(sync.promise).to.be.rejectedWith(InvalidArgument, 'some error');
});
});
const coef = 3;
describe(`buffers at most ${coef} * max encrypted chunk size`, () => {
[10, 50, 100, 1000].forEach(chunkSize => {
it(`supports back pressure when piped to a slow writable with ${chunkSize} bytes input chunks`, async () => {
const timeout = makeTimeoutPromise(50);
const chunk = repeat('0', chunkSize);
const inputSize = 10 * (chunkSize + encryptionV4.overhead);
const bufferCounter = new BufferingObserver();
const slowWritable = new Writable({
highWaterMark: 1,
objectMode: true,
write: async (data, _, done) => {
// flood every stream before unlocking writing end
await timeout.promise;
bufferCounter.incrementOutputAndSnapshot(data.length + encryptionV4.overhead);
done();
},
});
let idx = -1;
let msg;
const continueWriting = () => {
do {
idx += 1;
msg = encryptMsg(idx, chunk);
bufferCounter.incrementInput(msg.encrypted.length);
timeout.reset();
} while (bufferCounter.inputWritten < inputSize && stream.write(msg.encrypted));
if (bufferCounter.inputWritten === inputSize) {
const emptyMsg = encryptMsg(idx, '');
stream.write(emptyMsg.encrypted);
stream.end();
}
};
await new Promise((resolve, reject) => {
stream.on('error', reject);
stream.on('drain', continueWriting);
slowWritable.on('finish', resolve);
stream.pipe(slowWritable);
continueWriting();
});
bufferCounter.snapshots.forEach(bufferedLength => {
expect(bufferedLength).to.be.at.most(
coef * (chunkSize + encryptionV4.overhead),
`buffered data exceeds threshold (${coef} * chunk size): got ${bufferedLength}, chunk (size: ${chunkSize} + overhead: ${encryptionV4.overhead})`,
);
});
});
});
});
}); | the_stack |
import { html } from 'snabbdom-jsx'; // must be html here, as we're creating a div
import { init } from "snabbdom";
import { VNode } from "snabbdom/vnode";
import { Module } from "snabbdom/modules/module";
import { propsModule } from "snabbdom/modules/props";
import { attributesModule } from "snabbdom/modules/attributes";
import { styleModule } from "snabbdom/modules/style";
import { eventListenersModule } from "snabbdom/modules/eventlisteners";
import { classModule } from "snabbdom/modules/class";
import { inject, injectable, multiInject, optional } from "inversify";
import { TYPES } from "../types";
import { ILogger } from "../../utils/logging";
import { ORIGIN_POINT } from "../../utils/geometry";
import { SModelElement, SModelRoot, SParentElement } from "../model/smodel";
import { IActionDispatcher } from "../actions/action-dispatcher";
import { InitializeCanvasBoundsAction } from "../features/initialize-canvas";
import { IVNodeDecorator } from "./vnode-decorators";
import { RenderingContext, ViewRegistry } from "./view";
import { setClass, setAttr, copyClassesFromElement, copyClassesFromVNode } from "./vnode-utils";
import { ViewerOptions } from "./viewer-options";
import { isThunk } from "./thunk-view";
import { EMPTY_ROOT } from "../model/smodel-factory";
export interface IViewer {
update(model: SModelRoot): void
updateHidden(hiddenModel: SModelRoot): void
updatePopup(popupModel: SModelRoot): void
}
export class ModelRenderer implements RenderingContext {
constructor(public viewRegistry: ViewRegistry,
private decorators: IVNodeDecorator[]) {
}
decorate(vnode: VNode, element: Readonly<SModelElement>): VNode {
if (isThunk(vnode))
return vnode;
return this.decorators.reduce(
(n: VNode, decorator: IVNodeDecorator) => decorator.decorate(n, element),
vnode);
}
renderElement(element: Readonly<SModelElement>, args?: object): VNode {
const vNode = this.viewRegistry.get(element.type, undefined).render(element, this, args);
return this.decorate(vNode, element);
}
renderChildren(element: Readonly<SParentElement>, args?: object): VNode[] {
return element.children.map((child) => this.renderElement(child, args));
}
postUpdate() {
this.decorators.forEach(decorator => decorator.postUpdate());
}
}
export type ModelRendererFactory = (decorators: IVNodeDecorator[]) => ModelRenderer;
/**
* The component that turns the model into an SVG DOM.
* Uses a VDOM based on snabbdom.js for performance.
*/
@injectable()
export class Viewer implements IViewer {
protected renderer: ModelRenderer;
protected hiddenRenderer: ModelRenderer;
protected popupRenderer: ModelRenderer;
protected readonly patcher: Patcher;
protected lastVDOM: VNode;
protected lastHiddenVDOM: VNode;
protected lastPopupVDOM: VNode;
constructor(@inject(TYPES.ModelRendererFactory) modelRendererFactory: ModelRendererFactory,
@multiInject(TYPES.IVNodeDecorator) @optional() protected decorators: IVNodeDecorator[],
@multiInject(TYPES.HiddenVNodeDecorator) @optional() protected hiddenDecorators: IVNodeDecorator[],
@multiInject(TYPES.PopupVNodeDecorator) @optional() protected popupDecorators: IVNodeDecorator[],
@inject(TYPES.ViewerOptions) protected options: ViewerOptions,
@inject(TYPES.ILogger) protected logger: ILogger,
@inject(TYPES.IActionDispatcher) protected actiondispatcher: IActionDispatcher) {
this.patcher = this.createPatcher();
this.renderer = modelRendererFactory(decorators);
this.hiddenRenderer = modelRendererFactory(hiddenDecorators);
this.popupRenderer = modelRendererFactory(popupDecorators);
}
protected createModules(): Module[] {
return [
propsModule,
attributesModule,
classModule,
styleModule,
eventListenersModule
];
}
protected createPatcher() {
return init(this.createModules());
}
protected onWindowResize = (vdom: VNode): void => {
const baseDiv = document.getElementById(this.options.baseDiv);
if (baseDiv !== null) {
const newBounds = this.getBoundsInPage(baseDiv as Element);
this.actiondispatcher.dispatch(new InitializeCanvasBoundsAction(newBounds));
}
}
protected getBoundsInPage(element: Element) {
const bounds = element.getBoundingClientRect();
const scroll = typeof window !== 'undefined' ? {x: window.scrollX, y: window.scrollY} : ORIGIN_POINT;
return {
x: bounds.left + scroll.x,
y: bounds.top + scroll.y,
width: bounds.width,
height: bounds.height
};
}
update(model: Readonly<SModelRoot>): void {
this.logger.log(this, 'rendering', model);
const newVDOM = <div id={this.options.baseDiv}>
{this.renderer.renderElement(model)}
</div>;
if (this.lastVDOM !== undefined) {
const hadFocus = this.hasFocus();
copyClassesFromVNode(this.lastVDOM, newVDOM);
this.lastVDOM = this.patcher.call(this, this.lastVDOM, newVDOM);
this.restoreFocus(hadFocus);
} else if (typeof document !== 'undefined') {
const placeholder = document.getElementById(this.options.baseDiv);
if (placeholder !== null) {
if (typeof window !== 'undefined') {
window.addEventListener('resize', () => {
this.onWindowResize(newVDOM);
});
}
copyClassesFromElement(placeholder, newVDOM);
setClass(newVDOM, this.options.baseClass, true);
this.lastVDOM = this.patcher.call(this, placeholder, newVDOM);
} else {
this.logger.error(this, 'element not in DOM:', this.options.baseDiv);
}
}
this.renderer.postUpdate();
}
protected hasFocus(): boolean {
if (typeof document !== 'undefined' && document.activeElement && this.lastVDOM.children && this.lastVDOM.children.length > 0) {
const lastRootVNode = this.lastVDOM.children[0];
if (typeof lastRootVNode === 'object') {
const lastElement = (lastRootVNode as VNode).elm;
return document.activeElement === lastElement;
}
}
return false;
}
protected restoreFocus(focus: boolean) {
if (focus && this.lastVDOM.children && this.lastVDOM.children.length > 0) {
const lastRootVNode = this.lastVDOM.children[0];
if (typeof lastRootVNode === 'object') {
const lastElement = (lastRootVNode as VNode).elm;
if (lastElement && typeof (lastElement as any).focus === 'function')
(lastElement as any).focus();
}
}
}
updateHidden(hiddenModel: Readonly<SModelRoot>): void {
this.logger.log(this, 'rendering hidden');
let newVDOM: VNode;
if (hiddenModel.type === EMPTY_ROOT.type) {
newVDOM = <div id={this.options.hiddenDiv}></div>;
} else {
const hiddenVNode = this.hiddenRenderer.renderElement(hiddenModel);
setAttr(hiddenVNode, 'opacity', 0);
newVDOM = <div id={this.options.hiddenDiv}>
{hiddenVNode}
</div>;
}
if (this.lastHiddenVDOM !== undefined) {
copyClassesFromVNode(this.lastHiddenVDOM, newVDOM);
this.lastHiddenVDOM = this.patcher.call(this, this.lastHiddenVDOM, newVDOM);
} else {
let placeholder = document.getElementById(this.options.hiddenDiv);
if (placeholder === null) {
placeholder = document.createElement("div");
document.body.appendChild(placeholder);
} else {
copyClassesFromElement(placeholder, newVDOM);
}
setClass(newVDOM, this.options.baseClass, true);
setClass(newVDOM, this.options.hiddenClass, true);
this.lastHiddenVDOM = this.patcher.call(this, placeholder, newVDOM);
}
this.hiddenRenderer.postUpdate();
}
updatePopup(model: Readonly<SModelRoot>): void {
this.logger.log(this, 'rendering popup', model);
const popupClosed = model.type === EMPTY_ROOT.type;
let newVDOM: VNode;
if (popupClosed) {
newVDOM = <div id={this.options.popupDiv}></div>;
} else {
const position = model.canvasBounds;
const inlineStyle = {
top: position.y + 'px',
left: position.x + 'px'
};
newVDOM = <div id={this.options.popupDiv} style={inlineStyle}>
{this.popupRenderer.renderElement(model)}
</div>;
}
if (this.lastPopupVDOM !== undefined) {
copyClassesFromVNode(this.lastPopupVDOM, newVDOM);
setClass(newVDOM, this.options.popupClosedClass, popupClosed);
this.lastPopupVDOM = this.patcher.call(this, this.lastPopupVDOM, newVDOM);
} else if (typeof document !== 'undefined') {
let placeholder = document.getElementById(this.options.popupDiv);
if (placeholder === null) {
placeholder = document.createElement("div");
document.body.appendChild(placeholder);
} else {
copyClassesFromElement(placeholder, newVDOM);
}
setClass(newVDOM, this.options.popupClass, true);
setClass(newVDOM, this.options.popupClosedClass, popupClosed);
this.lastPopupVDOM = this.patcher.call(this, placeholder, newVDOM);
}
this.popupRenderer.postUpdate();
}
}
export type Patcher = (oldRoot: VNode | Element, newRoot: VNode) => VNode;
export type IViewerProvider = () => Promise<Viewer>; | the_stack |
import { Wallet, ContractFactory, utils, providers } from 'ethers';
import { colors, isSigner, isValidContract, isValidLibrary, isValidBytecode, linkLibrary } from 'etherlime-utils';
import DeployedContractWrapper from './../deployed-contract/deployed-contract-wrapper';
import { logsStore, logger } from 'etherlime-logger';
import { TxParams, CompiledContract, Generic } from './../types/types';
declare var Verifier: any;
class Deployer {
/**
*
* Instantiates new deployer. You probably should not use this class directly but use something inheriting this
*
* @param {*} signer ethers.Wallet instance
* @param {*} provider ethers.provider instance
* @param {*} defaultOverrides [Optional] default deployment overrides
*/
signer: Wallet;
provider: providers.JsonRpcProvider | providers.Web3Provider;
defaultOverrides: TxParams;
constructor(signer: Wallet, provider: providers.JsonRpcProvider | providers.Web3Provider, defaultOverrides?: TxParams) {
this._validateInput(signer);
this.signer = signer;
this.provider = provider;
this.signer = this.signer.connect(this.provider);
this.defaultOverrides = defaultOverrides;
logsStore.initHistoryRecord();
}
setSigner(signer: Wallet): void {
this._validateInput(signer);
this.signer = signer;
this.signer = this.signer.connect(this.provider);
}
setProvider(provider: providers.JsonRpcProvider): void {
this.provider = provider;
this.signer = this.signer.connect(this.provider);
}
setDefaultOverrides(defaultOverrides: TxParams): void {
this.defaultOverrides = defaultOverrides;
}
setVerifierApiKey(etherscanApiKey: string): void {
if (!this.defaultOverrides) {
this.defaultOverrides = {}
}
this.defaultOverrides.etherscanApiKey = etherscanApiKey;
}
private _validateInput(signer): void {
if (!(isSigner(signer))) {
throw new Error('Passed signer is not valid signer instance of ethers Wallet');
}
}
/**
*
* Use this function to deploy a contract.
*
* @return DeploymentResult object
*
* @param {*} contract the contract object to be deployed. Must have at least abi and bytecode fields. For now use the .json file generated from etherlime compile
*/
async deploy(contract: CompiledContract, libraries?: Generic<string>, ...args): Promise<DeployedContractWrapper> {
const deploymentArguments = Array.prototype.slice.call(args);
const { contractCopy, transaction, transactionReceipt, deploymentResult } = await this._prepareAndDeployTransaction(contract, libraries, deploymentArguments);
await this._logAction(this.constructor.name, contractCopy.contractName, transaction.hash, 0, transaction.gasPrice.toString(), transactionReceipt.gasUsed.toString(), deploymentResult.contractAddress, deploymentResult._contract.compiler ? deploymentResult._contract.compiler.version : null, false);
return deploymentResult;
}
async deployAndVerify(platform: string, contract: CompiledContract, libraries?: Generic<string>, ...args): Promise<DeployedContractWrapper> {
if (platform === 'etherscan' && (!this.defaultOverrides || !this.defaultOverrides.etherscanApiKey)) {
throw new Error('Please provide Etherscan API key!')
}
const deploymentArguments = Array.prototype.slice.call(args);
const { contractCopy, transaction, transactionReceipt, deploymentResult } = await this._prepareAndDeployTransaction(contract, libraries, deploymentArguments);
const verification = await Verifier.verifySmartContract(platform, deploymentResult, deploymentArguments, libraries, this.defaultOverrides);
await this._logAction(this.constructor.name, contractCopy.contractName, transaction.hash, 0, transaction.gasPrice.toString(), transactionReceipt.gasUsed.toString(), deploymentResult.contractAddress, deploymentResult._contract.compiler ? deploymentResult._contract.compiler.version : null, verification);
return deploymentResult;
}
private async _prepareAndDeployTransaction(contract: CompiledContract, libraries?: Generic<string>, deploymentArguments?: any[]):
Promise<{ contractCopy: CompiledContract, transaction: providers.TransactionResponse, transactionReceipt: providers.TransactionReceipt, deploymentResult: DeployedContractWrapper }> {
await this._preValidateArguments(contract, deploymentArguments);
let contractCopy = JSON.parse(JSON.stringify(contract));
contractCopy.bytecode = await this._prepareBytecode(libraries, contractCopy.bytecode);
let deployTransaction = await this._prepareDeployTransaction(contractCopy, deploymentArguments);
deployTransaction = await this._overrideDeployTransactionConfig(deployTransaction);
const transaction = await this._sendDeployTransaction(deployTransaction);
const transactionReceipt = await this._waitForDeployTransaction(transaction);
await this._postValidateTransaction(contractCopy, transaction, transactionReceipt);
const deploymentResult = await this._generateDeploymentResult(contractCopy, transaction, transactionReceipt);
return { contractCopy, transaction, transactionReceipt, deploymentResult }
}
/**
*
* Override for custom pre-send validation
*
* @param {*} contract the contract to be deployed
* @param {*} deploymentArguments the deployment arguments
*/
protected async _preValidateArguments(contract: CompiledContract, deploymentArguments: any[]): Promise<void> {
if (!(isValidContract(contract))) {
await this._logAction(this.constructor.name, contract ? contract.contractName : 'No contract name', '', 1, '-', '-', 'Invalid contract object', '-', false);
throw new Error(`Passed contract is not a valid contract object. It needs to have bytecode, abi and contractName properties`);
}
if (!isValidBytecode(contract.bytecode)) {
throw new Error(`The bytecode is invalid. It should be of type string with length bigger than 0`);
}
const deployContractStart = `\nDeploying contract: ${colors.colorName(contract.contractName)}`;
const argumentsEnd = (deploymentArguments.length === 0) ? '' : ` with parameters: ${colors.colorParams(deploymentArguments)}`;
logger.log(`${deployContractStart}${argumentsEnd}`);
}
/**
*
* Override this to include custom logic for deploy transaction generation
*
* @param {*} contract the contract to be deployed
* @param {*} deploymentArguments the arguments to this contract
*/
private async _prepareDeployTransaction(contract: CompiledContract, deploymentArguments: any[]):
Promise<utils.UnsignedTransaction> {
let factory = new ContractFactory(contract.abi, contract.bytecode);
return factory.getDeployTransaction(...deploymentArguments);
}
/**
*
* Override this for custom deploy transaction configuration
*
* @param {*} deployTransaction the transaction that is to be overridden
*/
protected async _overrideDeployTransactionConfig(deployTransaction: utils.UnsignedTransaction):
Promise<utils.UnsignedTransaction> {
if (this.defaultOverrides === undefined) {
return deployTransaction;
}
if (this.defaultOverrides.gasPrice > 0) {
deployTransaction.gasPrice = this.defaultOverrides.gasPrice;
}
if (this.defaultOverrides.gasLimit > 0) {
deployTransaction.gasLimit = this.defaultOverrides.gasLimit;
}
if (this.defaultOverrides.chainId !== undefined) {
deployTransaction.chainId = this.defaultOverrides.chainId;
}
return deployTransaction;
}
/**
*
* Override this to include custom logic for sending the deploy transaction
*
* @param {*} deployTransaction the transaction that is to be sent
*/
private async _sendDeployTransaction(deployTransaction: providers.TransactionRequest): Promise<providers.TransactionResponse> {
return this.signer.sendTransaction(deployTransaction);
}
/**
*
* Override this to include custom logic for waiting for deployed transaction. For example you could trigger mined block for testrpc/ganache-cli
*
* @param {*} transaction The sent transaction object to be waited for
*/
protected async _waitForDeployTransaction(transaction: providers.TransactionResponse): Promise<providers.TransactionReceipt> {
logger.log(`Waiting for transaction to be included in a block and mined: ${colors.colorTransactionHash(transaction.hash)}`);
return transaction.wait();
}
/**
*
* @param {*} contract the contract being deployed
* @param {*} transaction the transaction object being sent
* @param {*} transactionReceipt the transaction receipt
*/
protected async _postValidateTransaction(contract: CompiledContract, transaction: providers.TransactionResponse, transactionReceipt: providers.TransactionReceipt):
Promise<void> {
if (transactionReceipt.status === 0) {
await this._logAction(this.constructor.name, contract.contractName, transaction.hash, 1, transaction.gasPrice.toString(), transactionReceipt.gasUsed.toString(), 'Transaction failed', '-', false);
throw new Error(`Transaction ${colors.colorTransactionHash(transactionReceipt.transactionHash)} ${colors.colorFailure('failed')}. Please check etherscan for better reason explanation.`);
}
}
/**
*
* Override this for custom deployment result objects
*
* @param {*} contract the contract that has been deployed
* @param {*} transaction the transaction object that was sent
* @param {*} transactionReceipt the transaction receipt
*/
protected async _generateDeploymentResult(contract: CompiledContract, transaction: providers.TransactionResponse, transactionReceipt: providers.TransactionReceipt):
Promise<DeployedContractWrapper> {
logger.log(`Contract ${colors.colorName(contract.contractName)} deployed at address: ${colors.colorAddress(transactionReceipt.contractAddress)}`);
return new DeployedContractWrapper(contract, transactionReceipt.contractAddress, this.signer, this.provider, transactionReceipt);
}
/**
*
* Override this for custom logging functionality
*
* @param {*} deployerType type of deployer
* @param {*} nameOrLabel name of the contract or label of the transaction
* @param {*} transactionHash transaction hash if available
* @param {*} status 0 - success, 1 - failure
* @param {*} gasPrice the gas price param that was used by this transaction
* @param {*} gasUsed the gas used by this transaction
* @param {*} result arbitrary result text
*/
protected async _logAction(deployerType: string, nameOrLabel: string, transactionHash: string, status: number, gasPrice: string, gasUsed: string, result: string, solcVersion: string, verification: boolean):
Promise<void> {
const network = await this.provider.getNetwork();
logsStore.logAction(deployerType, nameOrLabel, transactionHash, status, gasPrice, gasUsed, network.chainId, result, solcVersion, verification);
}
/**
*
* Use this method to wrap an existing address in DeployedContractWrapper. You can use the goodies of the DeployedContractWrapper the same way you can do with a contract you've just deployed.
*
* @dev Useful for upgradability
*
* @param {*} contract
* @param {*} contractAddress
*
* @return
*/
wrapDeployedContract(contract: CompiledContract, contractAddress: string): DeployedContractWrapper {
logger.log(`Wrapping contract ${colors.colorName(contract.contractName)} at address: ${colors.colorAddress(contractAddress)}`);
return new DeployedContractWrapper(contract, contractAddress, this.signer, this.provider);
}
/**
*
* Use this estimate deployment gas cost for given transaction
*
* @return the gas it is going to cost
*
* @param {*} contract the contract object to be deployed. Must have at least abi and bytecode fields. For now use the .json file generated from etherlime compile. Add the deployment params as comma separated values
*/
async estimateGas(contract: CompiledContract, libraries?: Generic<string>, ...args): Promise<string> {
const deploymentArguments = Array.prototype.slice.call(args);
await this._preValidateArguments(contract, deploymentArguments);
let contractCopy = JSON.parse(JSON.stringify(contract));
contractCopy.bytecode = await this._prepareBytecode(libraries, contractCopy.bytecode);
let deployTransaction = await this._prepareDeployTransaction(contractCopy, deploymentArguments);
const gasBN = await this._estimateTransactionGas(deployTransaction);
return gasBN.toString();
}
private async _estimateTransactionGas(transaction: providers.TransactionRequest): Promise<utils.BigNumber> {
return this.provider.estimateGas(transaction);
}
/**
*
* Link a library or number of libraries to a contract
*
* @param {*} libraries The libraries which will be linked to the contract
* @param {*} bytecode The contract's bytecode which be used for linking
*/
private async _prepareBytecode(libraries: Generic<string>, bytecode: string): Promise<string> {
if (isValidLibrary(libraries)) {
return await linkLibrary(libraries, bytecode);
}
return bytecode;
}
}
export default Deployer; | the_stack |
import { Injectable } from '@angular/core';
import { CoreError } from '@classes/errors/error';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreCourseCommonModWSOptions } from '@features/course/services/course';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreGradesMenuItem } from '@features/grades/services/grades-helper';
import { CoreApp } from '@services/app';
import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites';
import { CoreTextFormat, defaultTextFormat } from '@services/utils/text';
import { CoreUtils } from '@services/utils/utils';
import { CoreStatusWithWarningsWSResponse, CoreWS, CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws';
import { makeSingleton, Translate } from '@singletons';
import { CoreFormFields } from '@singletons/form';
import { AddonModWorkshopOffline } from './workshop-offline';
import { AddonModWorkshopAutoSyncData, AddonModWorkshopSyncProvider } from './workshop-sync';
const ROOT_CACHE_KEY = 'mmaModWorkshop:';
export enum AddonModWorkshopPhase {
PHASE_SETUP = 10,
PHASE_SUBMISSION = 20,
PHASE_ASSESSMENT = 30,
PHASE_EVALUATION = 40,
PHASE_CLOSED = 50,
}
export enum AddonModWorkshopSubmissionType {
SUBMISSION_TYPE_DISABLED = 0,
SUBMISSION_TYPE_AVAILABLE = 1,
SUBMISSION_TYPE_REQUIRED = 2,
}
export enum AddonModWorkshopExampleMode {
EXAMPLES_VOLUNTARY = 0,
EXAMPLES_BEFORE_SUBMISSION = 1,
EXAMPLES_BEFORE_ASSESSMENT = 2,
}
export enum AddonModWorkshopAction {
ADD = 'add',
DELETE = 'delete',
UPDATE = 'update',
}
export enum AddonModWorkshopAssessmentMode {
ASSESSMENT = 'assessment',
PREVIEW = 'preview',
}
export enum AddonModWorkshopOverallFeedbackMode {
DISABLED = 0,
ENABLED_OPTIONAL = 1,
ENABLED_REQUIRED = 2,
}
declare module '@singletons/events' {
/**
* Augment CoreEventsData interface with events specific to this service.
*
* @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
*/
export interface CoreEventsData {
[AddonModWorkshopSyncProvider.AUTO_SYNCED]: AddonModWorkshopAutoSyncData;
[AddonModWorkshopProvider.SUBMISSION_CHANGED]: AddonModWorkshopSubmissionChangedEventData;
[AddonModWorkshopProvider.ASSESSMENT_SAVED]: AddonModWorkshopAssessmentSavedChangedEventData;
[AddonModWorkshopProvider.ASSESSMENT_INVALIDATED]: AddonModWorkshopAssessmentInvalidatedChangedEventData;
}
}
/**
* Service that provides some features for workshops.
*/
@Injectable({ providedIn: 'root' })
export class AddonModWorkshopProvider {
static readonly COMPONENT = 'mmaModWorkshop';
static readonly PER_PAGE = 10;
static readonly SUBMISSION_CHANGED = 'addon_mod_workshop_submission_changed';
static readonly ASSESSMENT_SAVED = 'addon_mod_workshop_assessment_saved';
static readonly ASSESSMENT_INVALIDATED = 'addon_mod_workshop_assessment_invalidated';
/**
* Get cache key for workshop data WS calls.
*
* @param courseId Course ID.
* @return Cache key.
*/
protected getWorkshopDataCacheKey(courseId: number): string {
return ROOT_CACHE_KEY + 'workshop:' + courseId;
}
/**
* Get prefix cache key for all workshop activity data WS calls.
*
* @param workshopId Workshop ID.
* @return Cache key.
*/
protected getWorkshopDataPrefixCacheKey(workshopId: number): string {
return ROOT_CACHE_KEY + workshopId;
}
/**
* Get cache key for workshop access information data WS calls.
*
* @param workshopId Workshop ID.
* @return Cache key.
*/
protected getWorkshopAccessInformationDataCacheKey(workshopId: number): string {
return this.getWorkshopDataPrefixCacheKey(workshopId) + ':access';
}
/**
* Get cache key for workshop user plan data WS calls.
*
* @param workshopId Workshop ID.
* @return Cache key.
*/
protected getUserPlanDataCacheKey(workshopId: number): string {
return this.getWorkshopDataPrefixCacheKey(workshopId) + ':userplan';
}
/**
* Get cache key for workshop submissions data WS calls.
*
* @param workshopId Workshop ID.
* @param userId User ID.
* @param groupId Group ID.
* @return Cache key.
*/
protected getSubmissionsDataCacheKey(workshopId: number, userId: number = 0, groupId: number = 0): string {
return this.getWorkshopDataPrefixCacheKey(workshopId) + ':submissions:' + userId + ':' + groupId;
}
/**
* Get cache key for a workshop submission data WS calls.
*
* @param workshopId Workshop ID.
* @param submissionId Submission ID.
* @return Cache key.
*/
protected getSubmissionDataCacheKey(workshopId: number, submissionId: number): string {
return this.getWorkshopDataPrefixCacheKey(workshopId) + ':submission:' + submissionId;
}
/**
* Get cache key for workshop grades data WS calls.
*
* @param workshopId Workshop ID.
* @return Cache key.
*/
protected getGradesDataCacheKey(workshopId: number): string {
return this.getWorkshopDataPrefixCacheKey(workshopId) + ':grades';
}
/**
* Get cache key for workshop grade report data WS calls.
*
* @param workshopId Workshop ID.
* @param groupId Group ID.
* @return Cache key.
*/
protected getGradesReportDataCacheKey(workshopId: number, groupId: number = 0): string {
return this.getWorkshopDataPrefixCacheKey(workshopId) + ':report:' + groupId;
}
/**
* Get cache key for workshop submission assessments data WS calls.
*
* @param workshopId Workshop ID.
* @param submissionId Submission ID.
* @return Cache key.
*/
protected getSubmissionAssessmentsDataCacheKey(workshopId: number, submissionId: number): string {
return this.getWorkshopDataPrefixCacheKey(workshopId) + ':assessments:' + submissionId;
}
/**
* Get cache key for workshop reviewer assessments data WS calls.
*
* @param workshopId Workshop ID.
* @param userId User ID or current user.
* @return Cache key.
*/
protected getReviewerAssessmentsDataCacheKey(workshopId: number, userId: number = 0): string {
return this.getWorkshopDataPrefixCacheKey(workshopId) + ':reviewerassessments:' + userId;
}
/**
* Get cache key for a workshop assessment data WS calls.
*
* @param workshopId Workshop ID.
* @param assessmentId Assessment ID.
* @return Cache key.
*/
protected getAssessmentDataCacheKey(workshopId: number, assessmentId: number): string {
return this.getWorkshopDataPrefixCacheKey(workshopId) + ':assessment:' + assessmentId;
}
/**
* Get cache key for workshop assessment form data WS calls.
*
* @param workshopId Workshop ID.
* @param assessmentId Assessment ID.
* @param mode Mode assessment (default) or preview.
* @return Cache key.
*/
protected getAssessmentFormDataCacheKey(workshopId: number, assessmentId: number, mode: string = 'assessment'): string {
return this.getWorkshopDataPrefixCacheKey(workshopId) + ':assessmentsform:' + assessmentId + ':' + mode;
}
/**
* Get a workshop with key=value. If more than one is found, only the first will be returned.
*
* @param courseId Course ID.
* @param key Name of the property to check.
* @param value Value to search.
* @param options Other options.
* @return Promise resolved when the workshop is retrieved.
*/
protected async getWorkshopByKey(
courseId: number,
key: string,
value: number,
options: CoreSitesCommonWSOptions = {},
): Promise<AddonModWorkshopData> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetWorkshopsByCoursesWSParams = {
courseids: [courseId],
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getWorkshopDataCacheKey(courseId),
updateFrequency: CoreSite.FREQUENCY_RARELY,
component: AddonModWorkshopProvider.COMPONENT,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModWorkshopGetWorkshopsByCoursesWSResponse>(
'mod_workshop_get_workshops_by_courses',
params,
preSets,
);
const workshop = response.workshops.find((workshop) => workshop[key] == value);
if (!workshop) {
throw new CoreError(Translate.instant('core.course.modulenotfound'));
}
// Set submission types for Moodle 3.5.
if (workshop.submissiontypetext === undefined) {
if (workshop.nattachments !== undefined && workshop.nattachments > 0) {
workshop.submissiontypetext = AddonModWorkshopSubmissionType.SUBMISSION_TYPE_AVAILABLE;
workshop.submissiontypefile = AddonModWorkshopSubmissionType.SUBMISSION_TYPE_AVAILABLE;
} else {
workshop.submissiontypetext = AddonModWorkshopSubmissionType.SUBMISSION_TYPE_REQUIRED;
workshop.submissiontypefile = AddonModWorkshopSubmissionType.SUBMISSION_TYPE_DISABLED;
}
}
return workshop;
}
/**
* Get a workshop by course module ID.
*
* @param courseId Course ID.
* @param cmId Course module ID.
* @param options Other options.
* @return Promise resolved when the workshop is retrieved.
*/
getWorkshop(courseId: number, cmId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModWorkshopData> {
return this.getWorkshopByKey(courseId, 'coursemodule', cmId, options);
}
/**
* Get a workshop by ID.
*
* @param courseId Course ID.
* @param id Workshop ID.
* @param options Other options.
* @return Promise resolved when the workshop is retrieved.
*/
getWorkshopById(courseId: number, id: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModWorkshopData> {
return this.getWorkshopByKey(courseId, 'id', id, options);
}
/**
* Invalidates workshop data.
*
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the workshop is invalidated.
*/
async invalidateWorkshopData(courseId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getWorkshopDataCacheKey(courseId));
}
/**
* Invalidates workshop data except files and module info.
*
* @param workshopId Workshop ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the workshop is invalidated.
*/
async invalidateWorkshopWSData(workshopId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKeyStartingWith(this.getWorkshopDataPrefixCacheKey(workshopId));
}
/**
* Get access information for a given workshop.
*
* @param workshopId Workshop ID.
* @param options Other options.
* @return Promise resolved when the workshop is retrieved.
*/
async getWorkshopAccessInformation(
workshopId: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModWorkshopGetWorkshopAccessInformationWSResponse> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetWorkshopAccessInformationWSParams = {
workshopid: workshopId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getWorkshopAccessInformationDataCacheKey(workshopId),
component: AddonModWorkshopProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
return site.read<AddonModWorkshopGetWorkshopAccessInformationWSResponse>(
'mod_workshop_get_workshop_access_information',
params,
preSets,
);
}
/**
* Invalidates workshop access information data.
*
* @param workshopId Workshop ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateWorkshopAccessInformationData(workshopId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getWorkshopAccessInformationDataCacheKey(workshopId));
}
/**
* Return the planner information for the given user.
*
* @param workshopId Workshop ID.
* @param options Other options.
* @return Promise resolved when the workshop data is retrieved.
*/
async getUserPlanPhases(
workshopId: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<Record<string, AddonModWorkshopPhaseData>> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetUserPlanWSParams = {
workshopid: workshopId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getUserPlanDataCacheKey(workshopId),
updateFrequency: CoreSite.FREQUENCY_OFTEN,
component: AddonModWorkshopProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModWorkshopGetUserPlanWSResponse>('mod_workshop_get_user_plan', params, preSets);
return CoreUtils.arrayToObject(response.userplan.phases, 'code');
}
/**
* Invalidates workshop user plan data.
*
* @param workshopId Workshop ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateUserPlanPhasesData(workshopId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getUserPlanDataCacheKey(workshopId));
}
/**
* Retrieves all the workshop submissions visible by the current user or the one done by the given user.
*
* @param workshopId Workshop ID.
* @param options Other options.
* @return Promise resolved when the workshop submissions are retrieved.
*/
async getSubmissions(
workshopId: number,
options: AddonModWorkshopGetSubmissionsOptions = {},
): Promise<AddonModWorkshopSubmissionData[]> {
const userId = options.userId || 0;
const groupId = options.groupId || 0;
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetSubmissionsWSParams = {
workshopid: workshopId,
userid: userId,
groupid: groupId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getSubmissionsDataCacheKey(workshopId, userId, groupId),
updateFrequency: CoreSite.FREQUENCY_OFTEN,
component: AddonModWorkshopProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModWorkshopGetSubmissionsWSResponse>('mod_workshop_get_submissions', params, preSets);
return response.submissions;
}
/**
* Invalidates workshop submissions data.
*
* @param workshopId Workshop ID.
* @param userId User ID.
* @param groupId Group ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateSubmissionsData(workshopId: number, userId: number = 0, groupId: number = 0, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getSubmissionsDataCacheKey(workshopId, userId, groupId));
}
/**
* Retrieves the given submission.
*
* @param workshopId Workshop ID.
* @param submissionId Submission ID.
* @param options Other options.
* @return Promise resolved when the workshop submission data is retrieved.
*/
async getSubmission(
workshopId: number,
submissionId: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModWorkshopSubmissionData> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetSubmissionWSParams = {
submissionid: submissionId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getSubmissionDataCacheKey(workshopId, submissionId),
component: AddonModWorkshopProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModWorkshopGetSubmissionWSResponse>('mod_workshop_get_submission', params, preSets);
return response.submission;
}
/**
* Invalidates workshop submission data.
*
* @param workshopId Workshop ID.
* @param submissionId Submission ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateSubmissionData(workshopId: number, submissionId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getSubmissionDataCacheKey(workshopId, submissionId));
}
/**
* Returns the grades information for the given workshop and user.
*
* @param workshopId Workshop ID.
* @param options Other options.
* @return Promise resolved when the workshop grades data is retrieved.
*/
async getGrades(workshopId: number, options: CoreCourseCommonModWSOptions = {}): Promise<AddonModWorkshopGetGradesWSResponse> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetGradesWSParams = {
workshopid: workshopId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getGradesDataCacheKey(workshopId),
component: AddonModWorkshopProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
return site.read<AddonModWorkshopGetGradesWSResponse>('mod_workshop_get_grades', params, preSets);
}
/**
* Invalidates workshop grades data.
*
* @param workshopId Workshop ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateGradesData(workshopId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getGradesDataCacheKey(workshopId));
}
/**
* Retrieves the assessment grades report.
*
* @param workshopId Workshop ID.
* @param options Other options.
* @return Promise resolved when the workshop data is retrieved.
*/
async getGradesReport(
workshopId: number,
options: AddonModWorkshopGetGradesReportOptions = {},
): Promise<AddonModWorkshoGradesReportData> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetGradesReportWSParams = {
workshopid: workshopId,
groupid: options.groupId,
page: options.page || 0,
perpage: options.perPage || AddonModWorkshopProvider.PER_PAGE,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getGradesReportDataCacheKey(workshopId, options.groupId),
updateFrequency: CoreSite.FREQUENCY_OFTEN,
component: AddonModWorkshopProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response =
await site.read<AddonModWorkshopGetGradesReportWSResponse>('mod_workshop_get_grades_report', params, preSets);
return response.report;
}
/**
* Performs the whole fetch of the grade reports in the workshop.
*
* @param workshopId Workshop ID.
* @param options Other options.
* @return Promise resolved when done.
*/
fetchAllGradeReports(
workshopId: number,
options: AddonModWorkshopFetchAllGradesReportOptions = {},
): Promise<AddonModWorkshopGradesData[]> {
return this.fetchGradeReportsRecursive(workshopId, [], {
...options, // Include all options.
page: 0,
perPage: options.perPage || AddonModWorkshopProvider.PER_PAGE,
siteId: options.siteId || CoreSites.getCurrentSiteId(),
});
}
/**
* Recursive call on fetch all grade reports.
*
* @param workshopId Workshop ID.
* @param grades Grades already fetched (just to concatenate them).
* @param options Other options.
* @return Promise resolved when done.
*/
protected async fetchGradeReportsRecursive(
workshopId: number,
grades: AddonModWorkshopGradesData[],
options: AddonModWorkshopGetGradesReportOptions = {},
): Promise<AddonModWorkshopGradesData[]> {
const report = await this.getGradesReport(workshopId, options);
Array.prototype.push.apply(grades, report.grades);
const canLoadMore = ((options.page! + 1) * options.perPage!) < report.totalcount;
if (canLoadMore) {
options.page!++;
return this.fetchGradeReportsRecursive(workshopId, grades, options);
}
return grades;
}
/**
* Invalidates workshop grade report data.
*
* @param workshopId Workshop ID.
* @param groupId Group ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateGradeReportData(workshopId: number, groupId: number = 0, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getGradesReportDataCacheKey(workshopId, groupId));
}
/**
* Retrieves the given submission assessment.
*
* @param workshopId Workshop ID.
* @param submissionId Submission ID.
* @param options Other options.
* @return Promise resolved when the workshop data is retrieved.
*/
async getSubmissionAssessments(
workshopId: number,
submissionId: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModWorkshopSubmissionAssessmentData[]> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetSubmissionAssessmentsWSParams = {
submissionid: submissionId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getSubmissionAssessmentsDataCacheKey(workshopId, submissionId),
component: AddonModWorkshopProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModWorkshopGetAssessmentsWSResponse>(
'mod_workshop_get_submission_assessments',
params,
preSets,
);
return response.assessments;
}
/**
* Invalidates workshop submission assessments data.
*
* @param workshopId Workshop ID.
* @param submissionId Submission ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateSubmissionAssesmentsData(workshopId: number, submissionId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getSubmissionAssessmentsDataCacheKey(workshopId, submissionId));
}
/**
* Add a new submission to a given workshop.
*
* @param workshopId Workshop ID.
* @param courseId Course ID the workshop belongs to.
* @param title The submission title.
* @param content The submission text content.
* @param attachmentsId The draft file area id for attachments.
* @param siteId Site ID. If not defined, current site.
* @param allowOffline True if it can be stored in offline, false otherwise.
* @return Promise resolved with submission ID if sent online or false if stored offline.
*/
async addSubmission(
workshopId: number,
courseId: number,
title: string,
content: string,
attachmentsId?: number,
siteId?: string,
allowOffline: boolean = false,
): Promise<number | false> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a message to be synchronized later.
const storeOffline = async (): Promise<false> => {
await AddonModWorkshopOffline.saveSubmission(
workshopId,
courseId,
title,
content,
undefined,
undefined,
AddonModWorkshopAction.ADD,
siteId,
);
return false;
};
// If we are editing an offline submission, discard previous first.
await AddonModWorkshopOffline.deleteSubmissionAction(workshopId, AddonModWorkshopAction.ADD, siteId);
if (!CoreApp.isOnline() && allowOffline) {
// App is offline, store the action.
return storeOffline();
}
try {
return await this.addSubmissionOnline(workshopId, title, content, attachmentsId as number, siteId);
} catch (error) {
if (allowOffline && !CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, store in offline.
return storeOffline();
}
// The WebService has thrown an error or offline not supported, reject.
throw error;
}
}
/**
* Add a new submission to a given workshop. It will fail if offline or cannot connect.
*
* @param workshopId Workshop ID.
* @param title The submission title.
* @param content The submission text content.
* @param attachmentsId The draft file area id for attachments.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the submission is created.
*/
async addSubmissionOnline(
workshopId: number,
title: string,
content: string,
attachmentsId?: number,
siteId?: string,
): Promise<number> {
const site = await CoreSites.getSite(siteId);
const params: AddonModWorkshopAddSubmissionWSParams = {
workshopid: workshopId,
title: title,
content: content,
attachmentsid: attachmentsId,
};
const response = await site.write<AddonModWorkshopAddSubmissionWSResponse>('mod_workshop_add_submission', params);
// Other errors ocurring.
CoreWS.throwOnFailedStatus(response, 'Add submission failed');
return response.submissionid!;
}
/**
* Updates the given submission.
*
* @param workshopId Workshop ID.
* @param submissionId Submission ID.
* @param courseId Course ID the workshop belongs to.
* @param title The submission title.
* @param content The submission text content.
* @param attachmentsId The draft file area id for attachments.
* @param siteId Site ID. If not defined, current site.
* @param allowOffline True if it can be stored in offline, false otherwise.
* @return Promise resolved with submission ID if sent online or false if stored offline.
*/
async updateSubmission(
workshopId: number,
submissionId: number,
courseId: number,
title: string,
content: string,
attachmentsId?: number | undefined,
siteId?: string,
allowOffline: boolean = false,
): Promise<number | false> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a message to be synchronized later.
const storeOffline = async (): Promise<false> => {
await AddonModWorkshopOffline.saveSubmission(
workshopId,
courseId,
title,
content,
undefined,
submissionId,
AddonModWorkshopAction.UPDATE,
siteId,
);
return false;
};
// If we are editing an offline discussion, discard previous first.
await AddonModWorkshopOffline.deleteSubmissionAction(workshopId, AddonModWorkshopAction.UPDATE, siteId);
if (!CoreApp.isOnline() && allowOffline) {
// App is offline, store the action.
return storeOffline();
}
try {
return await this.updateSubmissionOnline(submissionId, title, content, attachmentsId as number, siteId);
} catch (error) {
if (allowOffline && !CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, store in offline.
return storeOffline();
}
// The WebService has thrown an error or offline not supported, reject.
throw error;
}
}
/**
* Updates the given submission. It will fail if offline or cannot connect.
*
* @param submissionId Submission ID.
* @param title The submission title.
* @param content The submission text content.
* @param attachmentsId The draft file area id for attachments.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the submission is updated.
*/
async updateSubmissionOnline(
submissionId: number,
title: string,
content: string,
attachmentsId?: number,
siteId?: string,
): Promise<number> {
const site = await CoreSites.getSite(siteId);
const params: AddonModWorkshopUpdateSubmissionWSParams = {
submissionid: submissionId,
title: title,
content: content,
attachmentsid: attachmentsId || 0,
};
const response = await site.write<CoreStatusWithWarningsWSResponse>('mod_workshop_update_submission', params);
// Other errors ocurring.
CoreWS.throwOnFailedStatus(response, 'Update submission failed');
return submissionId;
}
/**
* Deletes the given submission.
*
* @param workshopId Workshop ID.
* @param submissionId Submission ID.
* @param courseId Course ID the workshop belongs to.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with submission ID if sent online, resolved with false if stored offline.
*/
async deleteSubmission(workshopId: number, submissionId: number, courseId: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a message to be synchronized later.
const storeOffline = (): Promise<void> => AddonModWorkshopOffline.saveSubmission(
workshopId,
courseId,
'',
'',
undefined,
submissionId,
AddonModWorkshopAction.DELETE,
siteId,
);
// If we are editing an offline discussion, discard previous first.
await AddonModWorkshopOffline.deleteSubmissionAction(workshopId, AddonModWorkshopAction.DELETE, siteId);
if (!CoreApp.isOnline()) {
// App is offline, store the action.
return storeOffline();
}
try {
return await this.deleteSubmissionOnline(submissionId, siteId);
} catch (error) {
if (!CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, store in offline.
return storeOffline();
}
// The WebService has thrown an error or offline not supported, reject.
throw error;
}
}
/**
* Deletes the given submission. It will fail if offline or cannot connect.
*
* @param submissionId Submission ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the submission is deleted.
*/
async deleteSubmissionOnline(submissionId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params: AddonModWorkshopDeleteSubmissionWSParams = {
submissionid: submissionId,
};
const response = await site.write<CoreStatusWithWarningsWSResponse>('mod_workshop_delete_submission', params);
// Other errors ocurring.
CoreWS.throwOnFailedStatus(response, 'Delete submission failed');
}
/**
* Retrieves all the assessments reviewed by the given user.
*
* @param workshopId Workshop ID.
* @param options Other options.
* @return Promise resolved when the workshop data is retrieved.
*/
async getReviewerAssessments(
workshopId: number,
options: AddonModWorkshopUserOptions = {},
): Promise<AddonModWorkshopSubmissionAssessmentData[]> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetReviewerAssessmentsWSParams = {
workshopid: workshopId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getReviewerAssessmentsDataCacheKey(workshopId, options.userId),
component: AddonModWorkshopProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
if (options.userId) {
params.userid = options.userId;
}
const response =
await site.read<AddonModWorkshopGetAssessmentsWSResponse>('mod_workshop_get_reviewer_assessments', params, preSets);
return response.assessments;
}
/**
* Invalidates workshop user assessments data.
*
* @param workshopId Workshop ID.
* @param userId User ID. If not defined, current user.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateReviewerAssesmentsData(workshopId: number, userId?: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getReviewerAssessmentsDataCacheKey(workshopId, userId));
}
/**
* Retrieves the given assessment.
*
* @param workshopId Workshop ID.
* @param assessmentId Assessment ID.
* @param options Other options.
* @return Promise resolved when the workshop data is retrieved.
*/
async getAssessment(
workshopId: number,
assessmentId: number,
options: CoreCourseCommonModWSOptions = {},
): Promise<AddonModWorkshopSubmissionAssessmentData> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetAssessmentWSParams = {
assessmentid: assessmentId,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getAssessmentDataCacheKey(workshopId, assessmentId),
component: AddonModWorkshopProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModWorkshopGetAssessmentWSResponse>('mod_workshop_get_assessment', params, preSets);
return response.assessment;
}
/**
* Invalidates workshop assessment data.
*
* @param workshopId Workshop ID.
* @param assessmentId Assessment ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAssessmentData(workshopId: number, assessmentId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getAssessmentDataCacheKey(workshopId, assessmentId));
}
/**
* Retrieves the assessment form definition (data required to be able to display the assessment form).
*
* @param workshopId Workshop ID.
* @param assessmentId Assessment ID.
* @param options Other options.
* @return Promise resolved when the workshop data is retrieved.
*/
async getAssessmentForm(
workshopId: number,
assessmentId: number,
options: AddonModWorkshopGetAssessmentFormOptions = {},
): Promise<AddonModWorkshopGetAssessmentFormDefinitionData> {
const mode = options.mode || AddonModWorkshopAssessmentMode.ASSESSMENT;
const site = await CoreSites.getSite(options.siteId);
const params: AddonModWorkshopGetAssessmentFormDefinitionWSParams = {
assessmentid: assessmentId,
mode: mode,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getAssessmentFormDataCacheKey(workshopId, assessmentId, mode),
updateFrequency: CoreSite.FREQUENCY_RARELY,
component: AddonModWorkshopProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModWorkshopGetAssessmentFormDefinitionWSResponse>(
'mod_workshop_get_assessment_form_definition',
params,
preSets,
);
return {
dimenssionscount: response.dimenssionscount,
descriptionfiles: response.descriptionfiles,
dimensionsinfo: response.dimensionsinfo,
warnings: response.warnings,
fields: this.parseFields(response.fields),
current: this.parseFields(response.current),
options: CoreUtils.objectToKeyValueMap<string>(response.options, 'name', 'value'),
};
}
/**
* Parse fieldes into a more handful format.
*
* @param fields Fields to parse
* @return Parsed fields
*/
parseFields(fields: AddonModWorkshopGetAssessmentFormFieldData[]): AddonModWorkshopGetAssessmentFormFieldsParsedData[] {
const parsedFields: AddonModWorkshopGetAssessmentFormFieldsParsedData[] = [];
fields.forEach((field) => {
const args: string[] = field.name.split('_');
const name = args[0];
const idx = args[3];
const idy = args[6] || false;
if (parseInt(idx, 10) + '' == idx) {
if (!parsedFields[idx]) {
parsedFields[idx] = {
number: idx + 1, // eslint-disable-line id-blacklist
};
}
if (idy && parseInt(idy, 10) + '' == idy) {
if (!parsedFields[idx].fields) {
parsedFields[idx].fields = [];
}
if (!parsedFields[idx].fields[idy]) {
parsedFields[idx].fields[idy] = {
number: idy + 1, // eslint-disable-line id-blacklist
};
}
parsedFields[idx].fields[idy][name] = field.value;
} else {
parsedFields[idx][name] = field.value;
}
}
});
return parsedFields;
}
/**
* Invalidates workshop assessments form data.
*
* @param workshopId Workshop ID.
* @param assessmentId Assessment ID.
* @param mode Mode assessment (default) or preview.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAssessmentFormData(
workshopId: number,
assessmentId: number,
mode: string = 'assessment',
siteId?: string,
):
Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getAssessmentFormDataCacheKey(workshopId, assessmentId, mode));
}
/**
* Updates the given assessment.
*
* @param workshopId Workshop ID.
* @param assessmentId Assessment ID.
* @param courseId Course ID the workshop belongs to.
* @param inputData Assessment data.
* @param siteId Site ID. If not defined, current site.
* @param allowOffline True if it can be stored in offline, false otherwise.
* @return Promise resolved with true if sent online, or false if stored offline.
*/
async updateAssessment(
workshopId: number,
assessmentId: number,
courseId: number,
inputData: CoreFormFields,
siteId?: string,
allowOffline = false,
): Promise<boolean> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a message to be synchronized later.
const storeOffline = async (): Promise<boolean> => {
await AddonModWorkshopOffline.saveAssessment(workshopId, assessmentId, courseId, inputData, siteId);
return false;
};
// If we are editing an offline discussion, discard previous first.
await AddonModWorkshopOffline.deleteAssessment(workshopId, assessmentId, siteId);
if (!CoreApp.isOnline() && allowOffline) {
// App is offline, store the action.
return storeOffline();
}
try {
await this.updateAssessmentOnline(assessmentId, inputData, siteId);
return true;
} catch (error) {
if (allowOffline && !CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, store in offline.
return storeOffline();
}
// The WebService has thrown an error or offline not supported, reject.
throw error;
}
}
/**
* Updates the given assessment. It will fail if offline or cannot connect.
*
* @param assessmentId Assessment ID.
* @param inputData Assessment data.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with the grade of the submission.
*/
async updateAssessmentOnline(assessmentId: number, inputData: CoreFormFields, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
const params: AddonModWorkshopUpdateAssessmentWSParams = {
assessmentid: assessmentId,
data: CoreUtils.objectToArrayOfObjects(inputData, 'name', 'value'),
};
const response = await site.write<AddonModWorkshopUpdateAssessmentWSResponse>('mod_workshop_update_assessment', params);
// Other errors ocurring.
CoreWS.throwOnFailedStatus(response, 'Update assessment failed');
}
/**
* Evaluates a submission (used by teachers for provide feedback or override the submission grade).
*
* @param workshopId Workshop ID.
* @param submissionId The submission id.
* @param courseId Course ID the workshop belongs to.
* @param feedbackText The feedback for the author.
* @param published Whether to publish the submission for other users.
* @param gradeOver The new submission grade (empty for no overriding the grade).
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when submission is evaluated if sent online,
* resolved with false if stored offline.
*/
async evaluateSubmission(
workshopId: number,
submissionId: number,
courseId: number,
feedbackText?: string,
published?: boolean,
gradeOver?: string,
siteId?: string,
): Promise<boolean> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a message to be synchronized later.
const storeOffline = (): Promise<boolean> => AddonModWorkshopOffline.saveEvaluateSubmission(
workshopId,
submissionId,
courseId,
feedbackText,
published,
gradeOver,
siteId,
).then(() => false);
// If we are editing an offline discussion, discard previous first.
await AddonModWorkshopOffline.deleteEvaluateSubmission(workshopId, submissionId, siteId);
if (!CoreApp.isOnline()) {
// App is offline, store the action.
return storeOffline();
}
try {
return await this.evaluateSubmissionOnline(submissionId, feedbackText, published, gradeOver, siteId);
} catch (error) {
if (CoreUtils.isWebServiceError(error)) {
// The WebService has thrown an error or offline not supported, reject.
throw error;
}
// Couldn't connect to server, store in offline.
return storeOffline();
}
}
/**
* Evaluates a submission (used by teachers for provide feedback or override the submission grade).
* It will fail if offline or cannot connect.
*
* @param submissionId The submission id.
* @param feedbackText The feedback for the author.
* @param published Whether to publish the submission for other users.
* @param gradeOver The new submission grade (empty for no overriding the grade).
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the submission is evaluated.
*/
async evaluateSubmissionOnline(
submissionId: number,
feedbackText?: string,
published?: boolean,
gradeOver?: string,
siteId?: string,
): Promise<boolean> {
const site = await CoreSites.getSite(siteId);
const params: AddonModWorkshopEvaluateSubmissionWSParams = {
submissionid: submissionId,
feedbacktext: feedbackText || '',
feedbackformat: defaultTextFormat,
published: published,
gradeover: gradeOver,
};
const response = await site.write<CoreStatusWithWarningsWSResponse>('mod_workshop_evaluate_submission', params);
// Other errors ocurring.
CoreWS.throwOnFailedStatus(response, 'Evaluate submission failed');
return true;
}
/**
* Evaluates an assessment (used by teachers for provide feedback to the reviewer).
*
* @param workshopId Workshop ID.
* @param assessmentId The assessment id.
* @param courseId Course ID the workshop belongs to.
* @param feedbackText The feedback for the reviewer.
* @param weight The new weight for the assessment.
* @param gradingGradeOver The new grading grade (empty for no overriding the grade).
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when assessment is evaluated if sent online,
* resolved with false if stored offline.
*/
async evaluateAssessment(
workshopId: number,
assessmentId: number,
courseId: number,
feedbackText?: string,
weight = 0,
gradingGradeOver?: string,
siteId?: string,
): Promise<boolean> {
siteId = siteId || CoreSites.getCurrentSiteId();
// Convenience function to store a message to be synchronized later.
const storeOffline = (): Promise<boolean> => AddonModWorkshopOffline.saveEvaluateAssessment(
workshopId,
assessmentId,
courseId,
feedbackText,
weight,
gradingGradeOver,
siteId,
).then(() => false);
// If we are editing an offline discussion, discard previous first.
await AddonModWorkshopOffline.deleteEvaluateAssessment(workshopId, assessmentId, siteId);
if (!CoreApp.isOnline()) {
// App is offline, store the action.
return storeOffline();
}
try {
return await this.evaluateAssessmentOnline(assessmentId, feedbackText, weight, gradingGradeOver, siteId);
} catch (error) {
if (!CoreUtils.isWebServiceError(error)) {
// Couldn't connect to server, store in offline.
return storeOffline();
}
// The WebService has thrown an error or offline not supported, reject.
throw error;
}
}
/**
* Evaluates an assessment (used by teachers for provide feedback to the reviewer). It will fail if offline or cannot connect.
*
* @param assessmentId The assessment id.
* @param feedbackText The feedback for the reviewer.
* @param weight The new weight for the assessment.
* @param gradingGradeOver The new grading grade (empty for no overriding the grade).
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the assessment is evaluated.
*/
async evaluateAssessmentOnline(
assessmentId: number,
feedbackText?: string,
weight?: number,
gradingGradeOver?: string,
siteId?: string,
): Promise<boolean> {
const site = await CoreSites.getSite(siteId);
const params: AddonModWorkshopEvaluateAssessmentWSParams = {
assessmentid: assessmentId,
feedbacktext: feedbackText || '',
feedbackformat: defaultTextFormat,
weight: weight,
gradinggradeover: gradingGradeOver,
};
const response = await site.write<CoreStatusWithWarningsWSResponse>('mod_workshop_evaluate_assessment', params);
// Other errors ocurring.
CoreWS.throwOnFailedStatus(response, 'Evaluate assessment failed');
return true;
}
/**
* Invalidate the prefetched content except files.
*
* @param moduleId The module ID.
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promised resolved when content is invalidated.
*/
async invalidateContent(moduleId: number, courseId: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const workshop = await this.getWorkshop(courseId, moduleId, {
readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE,
siteId,
});
await this.invalidateContentById(workshop.id, courseId, siteId);
}
/**
* Invalidate the prefetched content except files using the activityId.
*
* @param workshopId Workshop ID.
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when content is invalidated.
*/
async invalidateContentById(workshopId: number, courseId: number, siteId?: string): Promise<void> {
siteId = siteId || CoreSites.getCurrentSiteId();
const promises = [
// Do not invalidate workshop data before getting workshop info, we need it!
this.invalidateWorkshopData(courseId, siteId),
this.invalidateWorkshopWSData(workshopId, siteId),
];
await Promise.all(promises);
}
/**
* Report the workshop as being viewed.
*
* @param id Workshop ID.
* @param name Name of the workshop.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS call is successful.
*/
async logView(id: number, name?: string, siteId?: string): Promise<void> {
const params: AddonModWorkshopViewWorkshopWSParams = {
workshopid: id,
};
await CoreCourseLogHelper.logSingle(
'mod_workshop_view_workshop',
params,
AddonModWorkshopProvider.COMPONENT,
id,
name,
'workshop',
{},
siteId,
);
}
/**
* Report the workshop submission as being viewed.
*
* @param id Submission ID.
* @param workshopId Workshop ID.
* @param name Name of the workshop.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS call is successful.
*/
async logViewSubmission(id: number, workshopId: number, name?: string, siteId?: string): Promise<void> {
const params: AddonModWorkshopViewSubmissionWSParams = {
submissionid: id,
};
await CoreCourseLogHelper.logSingle(
'mod_workshop_view_submission',
params,
AddonModWorkshopProvider.COMPONENT,
workshopId,
name,
'workshop',
params,
siteId,
);
}
}
export const AddonModWorkshop = makeSingleton(AddonModWorkshopProvider);
/**
* Params of mod_workshop_view_workshop WS.
*/
type AddonModWorkshopViewWorkshopWSParams = {
workshopid: number; // Workshop instance id.
};
/**
* Params of mod_workshop_view_submission WS.
*/
type AddonModWorkshopViewSubmissionWSParams = {
submissionid: number; // Submission id.
};
/**
* Params of mod_workshop_get_workshops_by_courses WS.
*/
type AddonModWorkshopGetWorkshopsByCoursesWSParams = {
courseids?: number[]; // Array of course ids.
};
/**
* Data returned by mod_workshop_get_workshops_by_courses WS.
*/
type AddonModWorkshopGetWorkshopsByCoursesWSResponse = {
workshops: AddonModWorkshopData[];
warnings?: CoreWSExternalWarning[];
};
export type AddonModWorkshopData = {
id: number; // The primary key of the record.
course: number; // Course id this workshop is part of.
name: string; // Workshop name.
intro: string; // Workshop introduction text.
introformat?: CoreTextFormat; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
instructauthors?: string; // Instructions for the submission phase.
instructauthorsformat?: CoreTextFormat; // Instructauthors format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
instructreviewers?: string; // Instructions for the assessment phase.
instructreviewersformat?: CoreTextFormat; // Instructreviewers format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
timemodified?: number; // The timestamp when the module was modified.
phase: AddonModWorkshopPhase; // The current phase of workshop.
useexamples?: boolean; // Optional feature: students practise evaluating on example submissions from teacher.
usepeerassessment?: boolean; // Optional feature: students perform peer assessment of others' work.
useselfassessment?: boolean; // Optional feature: students perform self assessment of their own work.
grade?: number; // The maximum grade for submission.
gradinggrade?: number; // The maximum grade for assessment.
strategy?: string; // The type of the current grading strategy used in this workshop.
evaluation?: string; // The recently used grading evaluation method.
gradedecimals?: number; // Number of digits that should be shown after the decimal point when displaying grades.
submissiontypetext?: AddonModWorkshopSubmissionType; // Indicates whether text is required as part of each submission.
// 0 for no, 1 for optional, 2 for required.
submissiontypefile?: AddonModWorkshopSubmissionType; // Indicates whether a file upload is required as part of each submission.
// 0 for no, 1 for optional, 2 for required.
nattachments?: number; // Maximum number of submission attachments.
submissionfiletypes?: string; // Comma separated list of file extensions.
latesubmissions?: boolean; // Allow submitting the work after the deadline.
maxbytes?: number; // Maximum size of the one attached file.
examplesmode?: AddonModWorkshopExampleMode; // 0 = example assessments are voluntary,
// 1 = examples must be assessed before submission,
// 2 = examples are available after own submission and must be assessed before peer/self assessment phase.
submissionstart?: number; // 0 = will be started manually, greater than 0 the timestamp of the start of the submission phase.
submissionend?: number; // 0 = will be closed manually, greater than 0 the timestamp of the end of the submission phase.
assessmentstart?: number; // 0 = will be started manually, greater than 0 the timestamp of the start of the assessment phase.
assessmentend?: number; // 0 = will be closed manually, greater than 0 the timestamp of the end of the assessment phase.
phaseswitchassessment?: boolean; // Automatically switch to the assessment phase after the submissions deadline.
conclusion?: string; // A text to be displayed at the end of the workshop.
conclusionformat?: CoreTextFormat; // Conclusion format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
overallfeedbackmode?: AddonModWorkshopOverallFeedbackMode; // Mode of the overall feedback support.
overallfeedbackfiles?: number; // Number of allowed attachments to the overall feedback.
overallfeedbackfiletypes?: string; // Comma separated list of file extensions.
overallfeedbackmaxbytes?: number; // Maximum size of one file attached to the overall feedback.
coursemodule: number; // Coursemodule.
introfiles: CoreWSExternalFile[]; // Introfiles.
instructauthorsfiles?: CoreWSExternalFile[]; // Instructauthorsfiles.
instructreviewersfiles?: CoreWSExternalFile[]; // Instructreviewersfiles.
conclusionfiles?: CoreWSExternalFile[]; // Conclusionfiles.
};
/**
* Params of mod_workshop_get_workshop_access_information WS.
*/
type AddonModWorkshopGetWorkshopAccessInformationWSParams = {
workshopid: number; // Workshop instance id.
};
/**
* Data returned by mod_workshop_get_workshop_access_information WS.
*/
export type AddonModWorkshopGetWorkshopAccessInformationWSResponse = {
creatingsubmissionallowed: boolean; // Is the given user allowed to create their submission?.
modifyingsubmissionallowed: boolean; // Is the user allowed to modify his existing submission?.
assessingallowed: boolean; // Is the user allowed to create/edit his assessments?.
assessingexamplesallowed: boolean; // Are reviewers allowed to create/edit their assessments of the example submissions?.
examplesassessedbeforesubmission: boolean; // Whether the given user has assessed all his required examples before submission
// (always true if there are not examples to assess or not configured to check before submission).
examplesassessedbeforeassessment: boolean; // Whether the given user has assessed all his required examples before assessment
// (always true if there are not examples to assessor not configured to check before assessment).
canview: boolean; // Whether the user has the capability mod/workshop:view allowed.
canaddinstance: boolean; // Whether the user has the capability mod/workshop:addinstance allowed.
canswitchphase: boolean; // Whether the user has the capability mod/workshop:switchphase allowed.
caneditdimensions: boolean; // Whether the user has the capability mod/workshop:editdimensions allowed.
cansubmit: boolean; // Whether the user has the capability mod/workshop:submit allowed.
canpeerassess: boolean; // Whether the user has the capability mod/workshop:peerassess allowed.
canmanageexamples: boolean; // Whether the user has the capability mod/workshop:manageexamples allowed.
canallocate: boolean; // Whether the user has the capability mod/workshop:allocate allowed.
canpublishsubmissions: boolean; // Whether the user has the capability mod/workshop:publishsubmissions allowed.
canviewauthornames: boolean; // Whether the user has the capability mod/workshop:viewauthornames allowed.
canviewreviewernames: boolean; // Whether the user has the capability mod/workshop:viewreviewernames allowed.
canviewallsubmissions: boolean; // Whether the user has the capability mod/workshop:viewallsubmissions allowed.
canviewpublishedsubmissions: boolean; // Whether the user has the capability mod/workshop:viewpublishedsubmissions allowed.
canviewauthorpublished: boolean; // Whether the user has the capability mod/workshop:viewauthorpublished allowed.
canviewallassessments: boolean; // Whether the user has the capability mod/workshop:viewallassessments allowed.
canoverridegrades: boolean; // Whether the user has the capability mod/workshop:overridegrades allowed.
canignoredeadlines: boolean; // Whether the user has the capability mod/workshop:ignoredeadlines allowed.
candeletesubmissions: boolean; // Whether the user has the capability mod/workshop:deletesubmissions allowed.
canexportsubmissions: boolean; // Whether the user has the capability mod/workshop:exportsubmissions allowed.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_workshop_get_user_plan WS.
*/
type AddonModWorkshopGetUserPlanWSParams = {
workshopid: number; // Workshop instance id.
userid?: number; // User id (empty or 0 for current user).
};
/**
* Data returned by mod_workshop_get_user_plan WS.
*/
type AddonModWorkshopGetUserPlanWSResponse = {
userplan: {
phases: AddonModWorkshopPhaseData[];
examples: {
id: number; // Example submission id.
title: string; // Example submission title.
assessmentid: number; // Example submission assessment id.
grade: number; // The submission grade.
gradinggrade: number; // The assessment grade.
}[];
};
warnings?: CoreWSExternalWarning[];
};
export type AddonModWorkshopPhaseData = {
code: AddonModWorkshopPhase; // Phase code.
title: string; // Phase title.
active: boolean; // Whether is the active task.
tasks: AddonModWorkshopPhaseTaskData[];
actions: AddonModWorkshopPhaseActionData[];
};
export type AddonModWorkshopPhaseTaskData = {
code: string; // Task code.
title: string; // Task title.
link: string; // Link to task.
details?: string; // Task details.
completed: string; // Completion information (maybe empty, maybe a boolean or generic info).
};
export type AddonModWorkshopPhaseActionData = {
type?: string; // Action type.
label?: string; // Action label.
url: string; // Link to action.
method?: string; // Get or post.
};
/**
* Params of mod_workshop_get_submissions WS.
*/
type AddonModWorkshopGetSubmissionsWSParams = {
workshopid: number; // Workshop instance id.
userid?: number; // Get submissions done by this user. Use 0 or empty for the current user.
groupid?: number; // Group id, 0 means that the function will determine the user group.
// It will return submissions done by users in the given group.
page?: number; // The page of records to return.
perpage?: number; // The number of records to return per page.
};
/**
* Data returned by mod_workshop_get_submissions WS.
*/
type AddonModWorkshopGetSubmissionsWSResponse = {
submissions: AddonModWorkshopSubmissionData[];
totalcount: number; // Total count of submissions.
totalfilesize: number; // Total size (bytes) of the files attached to all the submissions (even the ones not returned due
// to pagination).
warnings?: CoreWSExternalWarning[];
};
export type AddonModWorkshopSubmissionData = {
id: number; // The primary key of the record.
workshopid: number; // The id of the workshop instance.
example: boolean; // Is this submission an example from teacher.
authorid: number; // The author of the submission.
timecreated: number; // Timestamp when the work was submitted for the first time.
timemodified: number; // Timestamp when the submission has been updated.
title: string; // The submission title.
content: string; // Submission text.
contentformat?: CoreTextFormat; // Content format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
contenttrust: number; // The trust mode of the data.
attachment: number; // Used by File API file_postupdate_standard_filemanager.
grade?: number; // Aggregated grade for the submission. The grade is a decimal number from interval 0..100.
// If NULL then the grade for submission has not been aggregated yet.
gradeover?: number; // Grade for the submission manually overridden by a teacher. Grade is always from interval 0..100.
// If NULL then the grade is not overriden.
gradeoverby?: number; // The id of the user who has overridden the grade for submission.
feedbackauthor?: string; // Teacher comment/feedback for the author of the submission, for example describing the reasons
// for the grade overriding.
feedbackauthorformat?: CoreTextFormat; // Feedbackauthor format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
timegraded?: number; // The timestamp when grade or gradeover was recently modified.
published: boolean; // Shall the submission be available to other when the workshop is closed.
late: number; // Has this submission been submitted after the deadline or during the assessment phase?.
contentfiles?: CoreWSExternalFile[]; // Contentfiles.
attachmentfiles?: CoreWSExternalFile[]; // Attachmentfiles.
};
/**
* Params of mod_workshop_get_submission WS.
*/
type AddonModWorkshopGetSubmissionWSParams = {
submissionid: number; // Submission id.
};
/**
* Data returned by mod_workshop_get_submission WS.
*/
type AddonModWorkshopGetSubmissionWSResponse = {
submission: AddonModWorkshopSubmissionData;
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_workshop_get_grades WS.
*/
type AddonModWorkshopGetGradesWSParams = {
workshopid: number; // Workshop instance id.
userid?: number; // User id (empty or 0 for current user).
};
/**
* Data returned by mod_workshop_get_grades WS.
*/
export type AddonModWorkshopGetGradesWSResponse = {
assessmentrawgrade?: number; // The assessment raw (numeric) grade.
assessmentlongstrgrade?: string; // The assessment string grade.
assessmentgradehidden?: boolean; // Whether the grade is hidden or not.
submissionrawgrade?: number; // The submission raw (numeric) grade.
submissionlongstrgrade?: string; // The submission string grade.
submissiongradehidden?: boolean; // Whether the grade is hidden or not.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_workshop_get_grades_report WS.
*/
type AddonModWorkshopGetGradesReportWSParams = {
workshopid: number; // Workshop instance id.
groupid?: number; // Group id, 0 means that the function will determine the user group.
sortby?: string; // Sort by this element:
// lastname, firstname, submissiontitle, submissionmodified, submissiongrade, gradinggrade.
sortdirection?: string; // Sort direction: ASC or DESC.
page?: number; // The page of records to return.
perpage?: number; // The number of records to return per page.
};
/**
* Data returned by mod_workshop_get_grades_report WS.
*/
type AddonModWorkshopGetGradesReportWSResponse = {
report: AddonModWorkshoGradesReportData;
warnings?: CoreWSExternalWarning[];
};
export type AddonModWorkshoGradesReportData = {
grades: AddonModWorkshopGradesData[];
totalcount: number; // Number of total submissions.
};
export type AddonModWorkshopGradesData = {
userid: number; // The id of the user being displayed in the report.
submissionid: number; // Submission id.
submissiontitle: string; // Submission title.
submissionmodified: number; // Timestamp submission was updated.
submissiongrade?: number; // Aggregated grade for the submission.
gradinggrade?: number; // Computed grade for the assessment.
submissiongradeover?: number; // Grade for the assessment overrided by the teacher.
submissiongradeoverby?: number; // The id of the user who overrided the grade.
submissionpublished?: number; // Whether is a submission published.
reviewedby?: AddonModWorkshopReviewer[]; // The users who reviewed the user submission.
reviewerof?: AddonModWorkshopReviewer[]; // The assessments the user reviewed.
};
export type AddonModWorkshopReviewer = {
userid: number; // The id of the user (0 when is configured to do not display names).
assessmentid: number; // The id of the assessment.
submissionid: number; // The id of the submission assessed.
grade: number; // The grade for submission.
gradinggrade: number; // The grade for assessment.
gradinggradeover: number; // The aggregated grade overrided.
weight: number; // The weight of the assessment for aggregation.
};
/**
* Params of mod_workshop_get_submission_assessments WS.
*/
type AddonModWorkshopGetSubmissionAssessmentsWSParams = {
submissionid: number; // Submission id.
};
/**
* Data returned by mod_workshop_get_submission_assessments and mod_workshop_get_reviewer_assessments WS.
*/
type AddonModWorkshopGetAssessmentsWSResponse = {
assessments: AddonModWorkshopSubmissionAssessmentData[];
warnings?: CoreWSExternalWarning[];
};
export type AddonModWorkshopSubmissionAssessmentData = {
id: number; // The primary key of the record.
submissionid: number; // The id of the assessed submission.
reviewerid: number; // The id of the reviewer who makes this assessment.
weight: number; // The weight of the assessment for the purposes of aggregation.
timecreated: number; // If 0 then the assessment was allocated but the reviewer has not assessed yet.
// If greater than 0 then the timestamp of when the reviewer assessed for the first time.
timemodified: number; // If 0 then the assessment was allocated but the reviewer has not assessed yet.
// If greater than 0 then the timestamp of when the reviewer assessed for the last time.
grade?: number; // The aggregated grade for submission suggested by the reviewer.
// The grade 0..100 is computed from the values assigned to the assessment dimensions fields.
// If NULL then it has not been aggregated yet.
gradinggrade?: number; // The computed grade 0..100 for this assessment. If NULL then it has not been computed yet.
gradinggradeover?: number; // Grade for the assessment manually overridden by a teacher.
// Grade is always from interval 0..100. If NULL then the grade is not overriden.
gradinggradeoverby: number; // The id of the user who has overridden the grade for submission.
feedbackauthor: string; // The comment/feedback from the reviewer for the author.
feedbackauthorformat?: CoreTextFormat; // Feedbackauthor format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
feedbackauthorattachment: number; // Are there some files attached to the feedbackauthor field?
// Sets to 1 by file_postupdate_standard_filemanager().
feedbackreviewer?: string; // The comment/feedback from the teacher for the reviewer.
// For example the reason why the grade for assessment was overridden.
feedbackreviewerformat?: CoreTextFormat; // Feedbackreviewer format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
feedbackcontentfiles: CoreWSExternalFile[]; // Feedbackcontentfiles.
feedbackattachmentfiles: CoreWSExternalFile[]; // Feedbackattachmentfiles.
};
/**
* Params of mod_workshop_get_reviewer_assessments WS.
*/
type AddonModWorkshopGetReviewerAssessmentsWSParams = {
workshopid: number; // Workshop instance id.
userid?: number; // User id who did the assessment review (empty or 0 for current user).
};
/**
* Params of mod_workshop_get_assessment WS.
*/
type AddonModWorkshopGetAssessmentWSParams = {
assessmentid: number; // Assessment id.
};
/**
* Data returned by mod_workshop_get_assessment WS.
*/
type AddonModWorkshopGetAssessmentWSResponse = {
assessment: AddonModWorkshopSubmissionAssessmentData;
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_workshop_get_assessment_form_definition WS.
*/
type AddonModWorkshopGetAssessmentFormDefinitionWSParams = {
assessmentid: number; // Assessment id.
mode?: AddonModWorkshopAssessmentMode; // The form mode (assessment or preview).
};
/**
* Data returned by mod_workshop_get_assessment_form_definition WS.
*/
type AddonModWorkshopGetAssessmentFormDefinitionWSResponse = {
dimenssionscount: number; // The number of dimenssions used by the form.
descriptionfiles: CoreWSExternalFile[];
options: { // The form options.
name: string; // Option name.
value: string; // Option value.
}[];
fields: AddonModWorkshopGetAssessmentFormFieldData[]; // The form fields.
current: AddonModWorkshopGetAssessmentFormFieldData[]; // The current field values.
dimensionsinfo: { // The dimensions general information.
id: number; // Dimension id.
min: number; // Minimum grade for the dimension.
max: number; // Maximum grade for the dimension.
weight: string; // The weight of the dimension.
scale?: string; // Scale items (if used).
}[];
warnings?: CoreWSExternalWarning[];
};
export type AddonModWorkshopGetAssessmentFormDefinitionData =
Omit<AddonModWorkshopGetAssessmentFormDefinitionWSResponse, 'fields'|'options'|'current'> & {
options?: {[name: string]: string} ;
fields: AddonModWorkshopGetAssessmentFormFieldsParsedData[]; // The form fields.
current: AddonModWorkshopGetAssessmentFormFieldsParsedData[]; // The current field values.
};
export type AddonModWorkshopGetAssessmentFormFieldData = {
name: string; // Field name.
value: string; // Field default value.
};
export type AddonModWorkshopGetAssessmentFormFieldsParsedData = (
Record<string, string> &
{
number?: number; // eslint-disable-line id-blacklist
grades?: CoreGradesMenuItem[];
grade?: number | string;
fields?: (Record<string, string> & {
number: number; // eslint-disable-line id-blacklist
})[];
}
);
/**
* Common options with a user ID.
*/
export type AddonModWorkshopUserOptions = CoreCourseCommonModWSOptions & {
userId?: number; // User ID. If not defined, current user.
};
/**
* Common options with a group ID.
*/
export type AddonModWorkshopGroupOptions = CoreCourseCommonModWSOptions & {
groupId?: number; // Group id, 0 or not defined means that the function will determine the user group.
};
/**
* Options to pass to getSubmissions.
*/
export type AddonModWorkshopGetSubmissionsOptions = AddonModWorkshopUserOptions & AddonModWorkshopGroupOptions;
/**
* Options to pass to fetchAllGradeReports.
*/
export type AddonModWorkshopFetchAllGradesReportOptions = AddonModWorkshopGroupOptions & {
perPage?: number; // Records per page to return. Default AddonModWorkshopProvider.PER_PAGE.
};
/**
* Options to pass to getGradesReport.
*/
export type AddonModWorkshopGetGradesReportOptions = AddonModWorkshopFetchAllGradesReportOptions & {
page?: number; // Page of records to return. Default 0.
};
/**
* Options to pass to getAssessmentForm.
*/
export type AddonModWorkshopGetAssessmentFormOptions = CoreCourseCommonModWSOptions & {
mode?: AddonModWorkshopAssessmentMode; // Mode assessment (default) or preview. Defaults to 'assessment'.
};
/**
* Params of mod_workshop_update_assessment WS.
*/
type AddonModWorkshopUpdateAssessmentWSParams = {
assessmentid: number; // Assessment id.
data: AddonModWorkshopAssessmentFieldData[]; // Assessment data.
};
export type AddonModWorkshopAssessmentFieldData = {
name: string; // The assessment data (use WS get_assessment_form_definition for obtaining the data to sent).
// Apart from that data, you can optionally send:
// feedbackauthor (str); the feedback for the submission author
// feedbackauthorformat (int); the format of the feedbackauthor
// feedbackauthorinlineattachmentsid (int); the draft file area for the editor attachments
// feedbackauthorattachmentsid (int); the draft file area id for the feedback attachments.
value: string; // The value of the option.
};
/**
* Data returned by mod_workshop_update_assessment WS.
*/
type AddonModWorkshopUpdateAssessmentWSResponse = {
status: boolean; // Status: true if the assessment was added or updated false otherwise.
rawgrade?: number; // Raw percentual grade (0.00000 to 100.00000) for submission.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_workshop_evaluate_submission WS.
*/
type AddonModWorkshopEvaluateSubmissionWSParams = {
submissionid: number; // Submission id.
feedbacktext?: string; // The feedback for the author.
feedbackformat?: CoreTextFormat; // The feedback format for text.
published?: boolean; // Publish the submission for others?.
gradeover?: string; // The new submission grade.
};
/**
* Params of mod_workshop_evaluate_assessment WS.
*/
type AddonModWorkshopEvaluateAssessmentWSParams = {
assessmentid: number; // Assessment id.
feedbacktext?: string; // The feedback for the reviewer.
feedbackformat?: CoreTextFormat; // The feedback format for text.
weight?: number; // The new weight for the assessment.
gradinggradeover?: string; // The new grading grade.
};
/**
* Params of mod_workshop_delete_submission WS.
*/
type AddonModWorkshopDeleteSubmissionWSParams = {
submissionid: number; // Submission id.
};
/**
* Params of mod_workshop_add_submission WS.
*/
type AddonModWorkshopAddSubmissionWSParams = {
workshopid: number; // Workshop id.
title: string; // Submission title.
content?: string; // Submission text content.
contentformat?: number; // The format used for the content.
inlineattachmentsid?: number; // The draft file area id for inline attachments in the content.
attachmentsid?: number; // The draft file area id for attachments.
};
/**
* Data returned by mod_workshop_add_submission WS.
*/
type AddonModWorkshopAddSubmissionWSResponse = {
status: boolean; // True if the submission was created false otherwise.
submissionid?: number; // New workshop submission id.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_workshop_update_submission WS.
*/
type AddonModWorkshopUpdateSubmissionWSParams = {
submissionid: number; // Submission id.
title: string; // Submission title.
content?: string; // Submission text content.
contentformat?: number; // The format used for the content.
inlineattachmentsid?: number; // The draft file area id for inline attachments in the content.
attachmentsid?: number; // The draft file area id for attachments.
};
export type AddonModWorkshopSubmissionChangedEventData = {
workshopId: number;
submissionId?: number;
};
export type AddonModWorkshopAssessmentSavedChangedEventData = {
workshopId: number;
assessmentId: number;
userId: number;
};
export type AddonModWorkshopAssessmentInvalidatedChangedEventData = null; | the_stack |
import { AnyFunction } from '@vue-cesium/utils/types'
/**
* Creates tweens for camera flights.
* <br /><br />
* Mouse interaction is disabled during flights.
*
* @private
*/
class CameraFlightPath {
static createTween(scene, options) {
const { Cartesian2, Cartesian3, defaultValue, defined, DeveloperError, EasingFunction, Math: CesiumMath, SceneMode } = Cesium
options = defaultValue(options, {})
let destination = options.destination
// >>includeStart('debug', pragmas.debug);
if (!defined(scene)) {
throw new DeveloperError('scene is required.')
}
if (!defined(destination)) {
throw new DeveloperError('destination is required.')
}
// >>includeEnd('debug');
const mode = scene.mode
if (mode === SceneMode.MORPHING) {
return emptyFlight()
}
const convert = defaultValue(options.convert, true)
const projection = scene.mapProjection
const ellipsoid = projection.ellipsoid
const maximumHeight = options.maximumHeight
const flyOverLongitude = options.flyOverLongitude
const flyOverLongitudeWeight = options.flyOverLongitudeWeight
const pitchAdjustHeight = options.pitchAdjustHeight
let easingFunction = options.easingFunction
if (convert && mode !== SceneMode.SCENE3D) {
ellipsoid.cartesianToCartographic(destination, scratchCartographic)
destination = projection.project(scratchCartographic, scratchDestination)
}
const camera = scene.camera
const transform = options.endTransform
if (defined(transform)) {
camera._setTransform(transform)
}
let duration = options.duration
if (!defined(duration)) {
duration = Math.ceil(Cartesian3.distance(camera.position, destination) / 1000000.0) + 2.0
duration = Math.min(duration, 3.0)
}
const heading = defaultValue(options.heading, 0.0)
const pitch = defaultValue(options.pitch, -CesiumMath.PI_OVER_TWO)
const roll = defaultValue(options.roll, 0.0)
const controller = scene.screenSpaceCameraController
controller.enableInputs = false
const complete = wrapCallback(controller, options.complete)
const cancel = wrapCallback(controller, options.cancel)
const frustum = camera.frustum
let empty = scene.mode === SceneMode.SCENE2D
empty = empty && Cartesian2.equalsEpsilon(camera.position, destination, CesiumMath.EPSILON6)
empty =
empty && CesiumMath.equalsEpsilon(Math.max(frustum.right - frustum.left, frustum.top - frustum.bottom), destination.z, CesiumMath.EPSILON6)
empty = empty || (scene.mode !== SceneMode.SCENE2D && Cartesian3.equalsEpsilon(destination, camera.position, CesiumMath.EPSILON10))
empty =
empty &&
CesiumMath.equalsEpsilon(CesiumMath.negativePiToPi(heading), CesiumMath.negativePiToPi(camera.heading), CesiumMath.EPSILON10) &&
CesiumMath.equalsEpsilon(CesiumMath.negativePiToPi(pitch), CesiumMath.negativePiToPi(camera.pitch), CesiumMath.EPSILON10) &&
CesiumMath.equalsEpsilon(CesiumMath.negativePiToPi(roll), CesiumMath.negativePiToPi(camera.roll), CesiumMath.EPSILON10)
if (empty) {
return emptyFlight(complete, cancel)
}
const updateFunctions = new Array(4)
updateFunctions[SceneMode.SCENE2D] = createUpdate2D
updateFunctions[SceneMode.SCENE3D] = createUpdate3D
updateFunctions[SceneMode.COLUMBUS_VIEW] = createUpdateCV
if (duration <= 0.0) {
const newOnComplete = function () {
const update = updateFunctions[mode](
scene,
1.0,
destination,
heading,
pitch,
roll,
maximumHeight,
flyOverLongitude,
flyOverLongitudeWeight,
pitchAdjustHeight
)
update({ time: 1.0 })
if (typeof complete === 'function') {
complete()
}
}
return emptyFlight(newOnComplete, cancel)
}
const update = updateFunctions[mode](
scene,
duration,
destination,
heading,
pitch,
roll,
maximumHeight,
flyOverLongitude,
flyOverLongitudeWeight,
pitchAdjustHeight
)
if (!defined(easingFunction)) {
const startHeight = camera.positionCartographic.height
const endHeight = mode === SceneMode.SCENE3D ? ellipsoid.cartesianToCartographic(destination).height : destination.z
if (startHeight > endHeight && startHeight > 11500.0) {
easingFunction = EasingFunction.CUBIC_OUT
} else {
easingFunction = EasingFunction.QUINTIC_IN_OUT
}
}
return {
duration: duration,
easingFunction: easingFunction,
startObject: {
time: 0.0
},
stopObject: {
time: duration
},
update: update,
complete: complete,
cancel: cancel
}
}
}
function getAltitude(frustum, dx, dy) {
const { PerspectiveFrustum, PerspectiveOffCenterFrustum } = Cesium
let near
let top
let right
if (frustum instanceof PerspectiveFrustum) {
const tanTheta = Math.tan(0.5 * frustum.fovy)
near = frustum.near
top = frustum.near * tanTheta
right = frustum.aspectRatio * top
return Math.max((dx * near) / right, (dy * near) / top)
} else if (frustum instanceof PerspectiveOffCenterFrustum) {
near = frustum.near
top = frustum.top
right = frustum.right
return Math.max((dx * near) / right, (dy * near) / top)
}
return Math.max(dx, dy)
}
const scratchCart: any = {}
const scratchCart2: any = {}
function createPitchFunction(startPitch, endPitch, heightFunction, pitchAdjustHeight) {
const { defined, Math: CesiumMath } = Cesium
if (defined(pitchAdjustHeight) && heightFunction(0.5) > pitchAdjustHeight) {
const startHeight = heightFunction(0.0)
const endHeight = heightFunction(1.0)
const middleHeight = heightFunction(0.5)
const d1 = middleHeight - startHeight
const d2 = middleHeight - endHeight
return function (time) {
const altitude = heightFunction(time)
if (time <= 0.5) {
const t1 = (altitude - startHeight) / d1
return CesiumMath.lerp(startPitch, -CesiumMath.PI_OVER_TWO, t1)
}
const t2 = (altitude - endHeight) / d2
return CesiumMath.lerp(-CesiumMath.PI_OVER_TWO, endPitch, 1 - t2)
}
}
return function (time) {
return CesiumMath.lerp(startPitch, endPitch, time)
}
}
function createHeightFunction(
camera: Cesium.Camera,
destination: Cesium.Cartesian3,
startHeight: number,
endHeight: number,
optionAltitude
): AnyFunction<any> {
const { Cartesian3, defined, Math: CesiumMath } = Cesium
let altitude = optionAltitude
const maxHeight = Math.max(startHeight, endHeight)
if (!defined(altitude)) {
const start = camera.position
const end = destination
const up = camera.up
const right = camera.right
const frustum = camera.frustum
const diff = Cartesian3.subtract(start, end, scratchCart)
const verticalDistance = Cartesian3.magnitude(Cartesian3.multiplyByScalar(up, Cartesian3.dot(diff, up), scratchCart2))
const horizontalDistance = Cartesian3.magnitude(Cartesian3.multiplyByScalar(right, Cartesian3.dot(diff, right), scratchCart2))
altitude = Math.min(getAltitude(frustum, verticalDistance, horizontalDistance) * 0.2, 1000000000.0)
}
if (maxHeight < altitude) {
const power = 8.0
const factor = 1000000.0
const s = -Math.pow((altitude - startHeight) * factor, 1.0 / power)
const e = Math.pow((altitude - endHeight) * factor, 1.0 / power)
return function (t) {
const x = t * (e - s) + s
return -Math.pow(x, power) / factor + altitude
}
}
return function (t) {
return CesiumMath.lerp(startHeight, endHeight, t)
}
}
function adjustAngleForLERP(startAngle: number, endAngle: number) {
const { Math: CesiumMath } = Cesium
if (CesiumMath.equalsEpsilon(startAngle, CesiumMath.TWO_PI, CesiumMath.EPSILON11)) {
startAngle = 0.0
}
if (endAngle > startAngle + Math.PI) {
startAngle += CesiumMath.TWO_PI
} else if (endAngle < startAngle - Math.PI) {
startAngle -= CesiumMath.TWO_PI
}
return startAngle
}
const scratchStart: any = {}
function createUpdateCV(
scene: Cesium.Scene,
duration: number,
destination: Cesium.Cartesian3,
heading: number,
pitch: number,
roll: number,
optionAltitude
) {
const { Cartesian2, Cartesian3, Math: CesiumMath } = Cesium
const camera = scene.camera
const start = Cartesian3.clone(camera.position, scratchStart)
const startPitch = camera.pitch
const startHeading = adjustAngleForLERP(camera.heading, heading)
const startRoll = adjustAngleForLERP(camera.roll, roll)
const heightFunction = createHeightFunction(camera, destination, start.z, destination.z, optionAltitude)
function update(value) {
const time = value.time / duration
camera.setView({
orientation: {
heading: CesiumMath.lerp(startHeading, heading, time),
pitch: CesiumMath.lerp(startPitch, pitch, time),
roll: CesiumMath.lerp(startRoll, roll, time)
}
})
Cartesian2.lerp(start, destination, time, camera.position)
camera.position.z = heightFunction(time)
}
return update
}
function useLongestFlight(startCart, destCart) {
const { Math: CesiumMath } = Cesium
if (startCart.longitude < destCart.longitude) {
startCart.longitude += CesiumMath.TWO_PI
} else {
destCart.longitude += CesiumMath.TWO_PI
}
}
function useShortestFlight(startCart, destCart) {
const { Math: CesiumMath } = Cesium
const diff = startCart.longitude - destCart.longitude
if (diff < -CesiumMath.PI) {
startCart.longitude += CesiumMath.TWO_PI
} else if (diff > CesiumMath.PI) {
destCart.longitude += CesiumMath.TWO_PI
}
}
const scratchStartCart: any = {}
const scratchEndCart: any = {}
function createUpdate3D(
scene: Cesium.Scene,
duration,
destination,
heading,
pitch,
roll,
optionAltitude,
optionFlyOverLongitude,
optionFlyOverLongitudeWeight,
optionPitchAdjustHeight
) {
const { Cartesian3, Cartographic, defined, Math: CesiumMath } = Cesium
const camera = scene.camera
const projection = scene.mapProjection
const ellipsoid = projection.ellipsoid
const startCart = Cartographic.clone(camera.positionCartographic, scratchStartCart)
const startPitch = camera.pitch
const startHeading = adjustAngleForLERP(camera.heading, heading)
const startRoll = adjustAngleForLERP(camera.roll, roll)
const destCart = ellipsoid.cartesianToCartographic(destination, scratchEndCart)
startCart.longitude = CesiumMath.zeroToTwoPi(startCart.longitude)
destCart.longitude = CesiumMath.zeroToTwoPi(destCart.longitude)
let useLongFlight = false
if (defined(optionFlyOverLongitude)) {
const hitLon = CesiumMath.zeroToTwoPi(optionFlyOverLongitude)
const lonMin = Math.min(startCart.longitude, destCart.longitude)
const lonMax = Math.max(startCart.longitude, destCart.longitude)
const hitInside = hitLon >= lonMin && hitLon <= lonMax
if (defined(optionFlyOverLongitudeWeight)) {
// Distance inside (0...2Pi)
const din = Math.abs(startCart.longitude - destCart.longitude)
// Distance outside (0...2Pi)
const dot = CesiumMath.TWO_PI - din
const hitDistance = hitInside ? din : dot
const offDistance = hitInside ? dot : din
if (hitDistance < offDistance * optionFlyOverLongitudeWeight && !hitInside) {
useLongFlight = true
}
} else if (!hitInside) {
useLongFlight = true
}
}
if (useLongFlight) {
useLongestFlight(startCart, destCart)
} else {
useShortestFlight(startCart, destCart)
}
const heightFunction = createHeightFunction(camera, destination, startCart.height, destCart.height, optionAltitude)
const pitchFunction = createPitchFunction(startPitch, pitch, heightFunction, optionPitchAdjustHeight)
// Isolate scope for update function.
// to have local copies of vars used in lerp
// Othervise, if you call nex
// createUpdate3D (createAnimationTween)
// before you played animation, variables will be overwriten.
function isolateUpdateFunction() {
const startLongitude = startCart.longitude
const destLongitude = destCart.longitude
const startLatitude = startCart.latitude
const destLatitude = destCart.latitude
return function update(value) {
const time = value.time / duration
const position = Cartesian3.fromRadians(
CesiumMath.lerp(startLongitude, destLongitude, time),
CesiumMath.lerp(startLatitude, destLatitude, time),
heightFunction(time),
scene.globe.ellipsoid
)
camera.setView({
destination: position,
orientation: {
heading: CesiumMath.lerp(startHeading, heading, time),
pitch: pitchFunction(time),
roll: CesiumMath.lerp(startRoll, roll, time)
}
})
}
}
return isolateUpdateFunction()
}
function createUpdate2D(scene, duration, destination, heading, pitch, roll, optionAltitude) {
const { Cartesian2, Cartesian3, Math: CesiumMath } = Cesium
const camera = scene.camera
const start = Cartesian3.clone(camera.position, scratchStart)
const startHeading = adjustAngleForLERP(camera.heading, heading)
const startHeight = camera.frustum.right - camera.frustum.left
const heightFunction = createHeightFunction(camera, destination, startHeight, destination.z, optionAltitude)
function update(value) {
const time = value.time / duration
camera.setView({
orientation: {
heading: CesiumMath.lerp(startHeading, heading, time)
}
})
Cartesian2.lerp(start, destination, time, camera.position)
const zoom = heightFunction(time)
const frustum = camera.frustum
const ratio = frustum.top / frustum.right
const incrementAmount = (zoom - (frustum.right - frustum.left)) * 0.5
frustum.right += incrementAmount
frustum.left -= incrementAmount
frustum.top = ratio * frustum.right
frustum.bottom = -frustum.top
}
return update
}
const scratchCartographic = {}
const scratchDestination = {}
function emptyFlight(complete?, cancel?) {
return {
startObject: {},
stopObject: {},
duration: 0.0,
complete: complete,
cancel: cancel
}
}
function wrapCallback(controller, cb) {
function wrapped() {
if (typeof cb === 'function') {
cb()
}
controller.enableInputs = true
}
return wrapped
}
export default CameraFlightPath | the_stack |
jest.mock("../../src/promise/cancellablePromise", () => ({
useCancellablePromise: jest.fn()
}));
import {
useWorkerFunction,
createBlobUrl,
inlineWorkExecution
} from "../../src/web/workerFunction";
import { NO_OP } from "../../src";
import { ref } from "../../src/api";
import { nextTick } from "../utils";
import { useCancellablePromise } from "../../src/promise/cancellablePromise";
const mockBlob = (fn: jest.Mock<any, any>) => {
class BlobMocked {
script: any;
type: any;
constructor(...args: any[]) {
fn(...args);
this.script = args[0];
this.type = args[1];
}
}
Object.defineProperty(window, "Blob", {
writable: true,
configurable: true,
value: BlobMocked
});
Object.defineProperty(global, "Blob", {
writable: true,
configurable: true,
value: BlobMocked
});
return fn;
};
const mockWorker = (
c: {
constructor: jest.Mock<any, any>;
addEventListener: jest.Mock<any, any>;
postMessage: jest.Mock<any, any>;
terminate: jest.Mock<any, any>;
} = {
constructor: jest.fn(),
addEventListener: jest.fn(),
postMessage: jest.fn(),
terminate: jest.fn()
}
) => {
class WorkerMock {
cb: {
error: (e: ErrorEvent) => void;
message: (e: MessageEvent) => void;
} = {} as any;
constructor(...args: any[]) {
c.constructor(...args);
}
addEventListener = c.addEventListener.mockImplementation(
(s: keyof WorkerMock["cb"], cb: any) => {
this.cb[s] = cb;
}
);
postMessage = c.postMessage;
terminate = c.terminate;
}
const _worker = window.Worker;
beforeAll(() => {
Object.defineProperty(window, "Worker", {
writable: true,
configurable: true,
value: WorkerMock
});
Object.defineProperty(global, "Worker", {
writable: true,
configurable: true,
value: WorkerMock
});
});
afterAll(() => {
Object.defineProperty(window, "Worker", {
writable: true,
configurable: true,
value: _worker
});
Object.defineProperty(global, "Worker", {
writable: true,
configurable: true,
value: _worker
});
});
const mockClear = () => {
Object.keys(c).map((x: keyof typeof c) => c[x].mockClear());
};
return {
...c,
mockClear
};
};
describe("worker function", () => {
const postMessageFn = jest
.spyOn(window, "postMessage")
.mockImplementation(x => x);
const blobConstructorFn = mockBlob(
jest.fn()
).mockImplementation((script, type) => [script, type]);
const createObjectUrlSpy = jest.fn(x => x);
const revokeObjectURLSpy = jest.fn(x => x);
URL.createObjectURL = createObjectUrlSpy;
URL.revokeObjectURL = revokeObjectURLSpy;
const workerMock = mockWorker();
const cancellablePromiseFn = useCancellablePromise as jest.Mock;
beforeEach(() => {
postMessageFn.mockClear();
createObjectUrlSpy.mockClear();
blobConstructorFn.mockClear();
workerMock.mockClear();
cancellablePromiseFn.mockClear();
cancellablePromiseFn.mockImplementation(p => ({ exec: p }));
});
describe("inlineWorkExecution", () => {
const toArgs = (...args: any[]) => [...args];
it("should return a function", () => {
expect(inlineWorkExecution(NO_OP)).toBeInstanceOf(Function);
});
it("should handle non-promise based factory", async () => {
const v = { a: 1 };
const e = inlineWorkExecution((a: any) => a);
const r = await e({
data: toArgs(v)
} as any);
expect(r).toMatchObject([true, v]);
expect(postMessageFn).toHaveBeenCalledWith([true, v]);
});
it("should handle promise based factory", async () => {
const v = { a: 1 };
const e = inlineWorkExecution((a: any) => Promise.resolve(a));
const r = await e({
data: toArgs(v)
} as any);
expect(r).toMatchObject([true, v]);
expect(postMessageFn).toHaveBeenCalledWith([true, v]);
});
it("should call factory with the `e.data`", async () => {
const v = { a: 1 };
const factory = jest.fn(x => x);
const e = inlineWorkExecution(factory);
await e({
data: toArgs(v)
} as any);
expect(factory).toHaveBeenCalledWith(v);
});
it("should call factory with multiple arguments the `e.data`", async () => {
const factory = jest.fn((...args) => args);
const e = inlineWorkExecution(factory);
await e({
data: toArgs(1, 2, 3)
} as any);
expect(factory).toHaveBeenCalledWith(1, 2, 3);
expect(postMessageFn).toHaveBeenCalledWith([true, [1, 2, 3]]);
});
it("should be able to call the function if `e.data` is empty or undefined", async () => {
const factory = jest.fn();
const e = inlineWorkExecution(factory);
const r = await e({
data: undefined
} as any);
expect(r).toStrictEqual([true, undefined]);
expect(factory).toHaveBeenCalledWith();
expect(postMessageFn).toHaveBeenCalledWith([true, undefined]);
});
it("should return [false, Error] on exception", async () => {
const error = new Error("test");
const factory = jest.fn(() => {
throw error;
});
const e = inlineWorkExecution(factory);
const r = await e({
data: toArgs(1, 2, 3)
} as any);
expect(r).toStrictEqual([false, error]);
expect(factory).toHaveBeenCalledWith(1, 2, 3);
expect(postMessageFn).toHaveBeenCalledWith([false, error]);
});
it("should return [false, Error] on promised exception", async () => {
const error = new Error("test");
const factory = jest.fn(
() =>
new Promise((_, rej) => {
rej(error);
})
);
const e = inlineWorkExecution(factory);
const r = await e({
data: toArgs(1, 2, 3)
} as any);
expect(r).toStrictEqual([false, error]);
expect(factory).toHaveBeenCalledWith(1, 2, 3);
expect(postMessageFn).toHaveBeenCalledWith([false, error]);
});
});
describe("createBlobUrl", () => {
beforeEach(() => {});
it("should create a blob and return objectUrl", () => {
const fn = (a: any) => {
return a + a;
};
expect(createBlobUrl(fn, [])).toMatchObject({
script: ["", "onmessage=", expect.stringContaining(fn.toString())],
type: {
type: "text/javascript"
}
});
});
it("should add 1 dependency to the blob", () => {
const fn = (a: any) => {
return a + a;
};
expect(createBlobUrl(fn, ["https://mydep.mydepen.my-com"])).toMatchObject(
{
script: [
`importScripts("https://mydep.mydepen.my-com");`,
"onmessage=",
expect.stringContaining(fn.toString())
],
type: {
type: "text/javascript"
}
}
);
});
it("should create the correct blobScript", () => {
const fn = (a: any) => {
return a + a;
};
expect(
createBlobUrl(fn, [
"https://mydep.mydepen.my-com",
"https://mydep.mydepen.my-com",
"https://mydep.mydepen.my-com"
])
).toMatchObject({
script: [
`importScripts("https://mydep.mydepen.my-com","https://mydep.mydepen.my-com","https://mydep.mydepen.my-com");`,
"onmessage=",
expect.stringContaining(fn.toString())
],
type: {
type: "text/javascript"
}
});
});
});
describe("useWorkerFunction", () => {
it("should create cancellablePromise and return it", () => {
const p = {};
cancellablePromiseFn.mockImplementationOnce(() => p);
expect(useWorkerFunction(NO_OP as any)).toBe(p);
expect(useCancellablePromise).toHaveBeenCalledWith(expect.any(Function), {
lazy: true,
throwException: true
});
});
it("should create worker", async () => {
const dependencies = ["test"];
const { exec } = useWorkerFunction(NO_OP as any, { dependencies });
expect(exec).toBeInstanceOf(Function);
const p = exec();
expect(p).toBeInstanceOf(Promise);
expect(createObjectUrlSpy).toHaveBeenCalledTimes(1);
expect(workerMock.constructor).toHaveBeenCalledTimes(1);
expect(workerMock.addEventListener).toHaveBeenCalledTimes(2);
expect(workerMock.postMessage).toHaveBeenCalledWith([]);
// new worker should have been created
exec(1, 2, 3);
expect(createObjectUrlSpy).toHaveBeenCalledTimes(2);
expect(workerMock.constructor).toHaveBeenCalledTimes(2);
expect(workerMock.addEventListener).toHaveBeenCalledTimes(4);
expect(workerMock.postMessage).toHaveBeenLastCalledWith([1, 2, 3]);
});
it("should get the function return", async () => {
const { exec } = useWorkerFunction(NO_OP as any);
expect(exec).toBeInstanceOf(Function);
const p = exec();
const expected = { a: 1 };
// message
workerMock.addEventListener.mock.calls[0][1]({
data: [true, expected]
});
expect(p).resolves.toBe(expected);
workerMock.mockClear();
expect(exec()).rejects.toBe(expected);
// message
workerMock.addEventListener.mock.calls[0][1]({
data: [false, expected]
});
workerMock.mockClear();
expect(exec()).rejects.toBe(expected);
// message
workerMock.addEventListener.mock.calls[1][1](expected);
});
describe("terminate", () => {
test("on success", async () => {
const { exec } = useWorkerFunction(NO_OP as any);
expect(exec).toBeInstanceOf(Function);
const p = exec();
const expected = { a: 1 };
// message
workerMock.addEventListener.mock.calls[0][1]({
data: [true, expected]
});
await p;
expect(workerMock.terminate).toHaveBeenCalled();
expect(revokeObjectURLSpy).toHaveBeenCalled();
});
describe("cancel", () => {
test("calling cancel()", async () => {
cancellablePromiseFn.mockImplementationOnce(p => ({
exec: p,
cancelled: ref(false)
}));
const { exec, cancelled } = useWorkerFunction(NO_OP as any);
const p = exec();
expect(p).resolves.toBeUndefined();
cancelled.value = true;
await nextTick();
expect(await p).toBeUndefined();
expect(workerMock.terminate).toHaveBeenCalled();
});
test("if the last argument is ref<boolean> becomes false", async () => {
cancellablePromiseFn.mockImplementationOnce(p => ({
exec: p,
cancelled: ref(false)
}));
const cancel = ref(false);
const { exec } = useWorkerFunction(NO_OP as any);
const p = exec(cancel);
expect(p).resolves.toBeUndefined();
cancel.value = true;
await nextTick();
expect(workerMock.terminate).toHaveBeenCalled();
});
test("last argument is boolean, not ref boolean", async () => {
cancellablePromiseFn.mockImplementationOnce(p => ({
exec: p,
cancelled: ref(false)
}));
let cancel = false;
const { exec, cancelled } = useWorkerFunction(NO_OP as any);
const p = exec(cancel);
expect(p).resolves.toBeUndefined();
cancel = true;
await nextTick();
expect(workerMock.terminate).not.toHaveBeenCalled();
cancelled.value = true;
await nextTick();
expect(workerMock.terminate).toHaveBeenCalled();
});
test("last argument extra argument is ref<true>", async () => {
cancellablePromiseFn.mockImplementationOnce(p => ({
exec: p,
cancelled: ref(false)
}));
const cancel = ref(true);
const { exec, cancelled } = useWorkerFunction(NO_OP as any);
const p = exec(cancel);
await nextTick();
expect(p).resolves.toBeUndefined();
cancel.value = false;
await nextTick();
expect(workerMock.terminate).not.toHaveBeenCalled();
// this cancel is not tracked so it shouldn't affect
cancel.value = true;
await nextTick();
expect(workerMock.terminate).not.toHaveBeenCalled();
cancelled.value = true;
await nextTick();
expect(workerMock.terminate).toHaveBeenCalled();
});
test("last argument is ref<boolean>", async () => {
cancellablePromiseFn.mockImplementationOnce(p => ({
exec: p,
cancelled: ref(false)
}));
const cancel = ref(false);
const { exec, cancelled } = useWorkerFunction((a: any) => {
return Promise.resolve(true);
});
let p = exec(cancel);
expect(p).resolves.toBeUndefined();
cancel.value = true;
await nextTick();
expect(workerMock.terminate).not.toHaveBeenCalled();
cancelled.value = true;
await nextTick();
expect(workerMock.terminate).toHaveBeenCalled();
// adding extra argument
p = (exec as any)(1, cancel);
expect(p).resolves.toBeUndefined();
cancel.value = true;
await nextTick();
expect(workerMock.terminate).toHaveBeenCalled();
await nextTick();
expect(workerMock.terminate).toHaveBeenCalled();
});
test("on timeout", async () => {
jest.useFakeTimers();
try {
const cancelled = ref(false);
cancellablePromiseFn.mockImplementationOnce(p => ({
exec: p,
cancel: jest
.fn()
.mockImplementation(() => (cancelled.value = false)),
cancelled
}));
const { exec, cancel } = useWorkerFunction(NO_OP as any, {
timeout: 40
});
const p = exec();
expect(p).resolves.toBeUndefined();
jest.runTimersToTime(50);
await nextTick();
cancelled.value = true;
expect(await p).toBeUndefined();
expect(workerMock.terminate).toHaveBeenCalled();
expect(cancel).toHaveBeenCalledWith(
`[WebWorker] timeout after 40ms`
);
} finally {
jest.useRealTimers();
}
});
});
});
});
}); | the_stack |
import {
bytesAsString,
DefaultSerializer,
Optional,
Serializer,
stringAsBytes,
WeakValueMap,
} from "../util";
import {
Collab,
CollabEventsRecord,
ICollabParent,
InitToken,
MessageMeta,
Message,
} from "../core";
import { LazyMutCMapSave } from "../../generated/proto_compiled";
// Import AbstractCMapCollab from its specific file;
// with whole-folder imports, AbstractCMapCObject and LazyMutCMap
// create a circular dependency between constructions
// and data_types.
import { AbstractCMapCollab } from "../data_types/abstract_map";
/**
* A CMap of mutable values where every key is
* implicitly always present, although only nontrivial
* values are actually stored in memory.
*
* Alternatively, you can think of this like a [[CObject]]
* with one property/child per key (potentially infinitely
* many). Like a [[CObject]], it makes sense for general
* Collabs, not just CRDTs.
*
* The "always exists" nature means that, unlike in
* [[DeletingMutCMap]] and [[ArchivingMutCMap]], there
* is no conflict when two users concurrently "create"
* values with the same key. Instead, they are just accessing
* the same value. If they perform operations on that
* value concurrently, then those operations will all
* apply to the value, effectively merging their changes.
*
* ## Laziness
*
* The name "LazyMap" references the [Apache Commons
* LazyMap](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/LazyMap.html).
* That map likewise creates values on demand using a
* factory method, to give the impression that all
* keys are always present.
*
* ## Key Presence
*
* For the
* purpose of the iterators and has, a key is considered
* to be present in the map if its value is nontrivial,
* specifically, if value.canGC() returns false.
* Note that this implies that a just-added key may
* not be present in the map. This unusual semantics
* is necessary because the map does not necessarily
* maintain all elements internally, only the nontrivial
* ones, and so the iterators are unable to consistently return
* all trivial elements.
*
* [[delete]] and [[clear]] throw errors (grow-only semantics).
* [[set]] has no effect; it just returns the same value
* as [[get]].
*
* "Set" and "Delete" events respect these key presence
* rules: "Set" is emitted for a key when its value
* goes from trivial to nontrivial, and "Delete"
* is emitted when its vale goes from nontrivial to trivial.
* Since this is a bit weird, we expect these events to
* be used rarely.
*
* Since a value can be created without emitting a
* "Set" event (in case it remains trivial), you should
* register event handlers on values in `valueConstructor`,
* not in a "Set" handler.
*
* ## Garbage Collection
*
* A value may be garbage collected if:
* (1) `value.canGC` returns false ([[Collab.canGC]])
* (2) There are no other references to the value.
*
* In this case, the JavaScript garbage collector is
* allowed to reclaim the value. If the value is
* referenced later (either by calling [[get]] locally
* or because it receives a message), then it is
* recreated using `valueConstructor`. This is okay
* by the contract of [[Collab.canGC]].
*/
export class LazyMutCMap<K, C extends Collab>
extends AbstractCMapCollab<K, C, []>
implements ICollabParent
{
private readonly nontrivialMap: Map<string, C> = new Map();
private readonly trivialMap: WeakValueMap<string, C> = new WeakValueMap();
/**
* @param valueConstructor Used to construct the
* value with the given key. For each key, the constructed values
* must be the same on all replicas, i.e., the
* same class and constructor arguments.
*/
constructor(
initToken: InitToken,
private readonly valueConstructor: (valueInitToken: InitToken, key: K) => C,
private readonly keySerializer: Serializer<K> = DefaultSerializer.getInstance()
) {
super(initToken);
}
private keyAsString(key: K) {
return bytesAsString(this.keySerializer.serialize(key));
}
private stringAsKey(str: string) {
return this.keySerializer.deserialize(stringAsBytes(str));
}
private getInternal(
key: K,
keyString: string,
inLoad: boolean
): [value: C, nontrivial: boolean] {
let value = this.nontrivialMap.get(keyString);
if (value === undefined) {
// Check the backup map
value = this.trivialMap.get(keyString);
if (value === undefined) {
// Create it.
value = this.valueConstructor(new InitToken(keyString, this), key);
if (inLoad) {
// We are in this.load.
// So, value.load will be called by this.load
// right after the value is returned;
// we don't need to do it here.
// Also, we can assume value will be nontrivial once
// it is recursively loaded, since save only
// returns the nontrivial children.
this.nontrivialMap.set(keyString, value);
} else {
// We assume that [[load]] has already finished, since this map
// isn't supposed to be used (e.g. calling [[get]]) until then.
// Thus value will never be loaded directly (by [[load]]), so
// we need to indicate that loading was skipped.
value.load(Optional.empty());
// The value starts trivial; if it becomes nontrivial
// due to a message, receive will move
// it to nontrivialMap.
this.trivialMap.set(keyString, value);
}
return [value, false];
}
return [value, false];
} else return [value, true];
}
childSend(child: Collab<CollabEventsRecord>, messagePath: Message[]): void {
if (child.parent !== this) {
throw new Error(`childSend called by non-child: ${child}`);
}
messagePath.push(child.name);
this.send(messagePath);
}
/**
* No added context.
*
* @return undefined
*/
getAddedContext(_key: symbol): unknown {
return undefined;
}
private inReceiveKeyStr?: string = undefined;
private inReceiveValue?: C = undefined;
receive(messagePath: Message[], meta: MessageMeta): void {
const keyString = <string>messagePath[messagePath.length - 1];
this.inReceiveKeyStr = keyString;
try {
// Message for a child
const key = this.stringAsKey(keyString);
const [value, nontrivialStart] = this.getInternal(key, keyString, false);
this.inReceiveValue = value;
messagePath.length--;
value.receive(messagePath, meta);
// If the value became GC-able, move it to the
// backup map
if (nontrivialStart && value.canGC()) {
this.nontrivialMap.delete(keyString);
this.trivialMap.set(keyString, value);
this.emit("Delete", {
key,
deletedValue: value,
meta,
});
}
// If the value became nontrivial, move it to the
// main map
else if (!nontrivialStart && !value.canGC()) {
this.trivialMap.delete(keyString);
this.nontrivialMap.set(keyString, value);
this.emit("Set", {
key,
// Empty to emphasize that the previous value was
// not present.
previousValue: Optional.empty<C>(),
meta,
});
// We don't dispatch Set events when the value
// is not new because there can only ever be one
// value at a given key.
// An exception is replacement due to GC-ing, but
// we consider such values "the same"; if users care
// about the distinction (e.g. because they need
// to register event handlers), they should do so
// in valueConstructor, not on Set events.
}
} finally {
this.inReceiveKeyStr = undefined;
this.inReceiveValue = undefined;
}
}
set(key: K): C {
// No-op, just return the value
return this.get(key);
}
/**
* Unsupported (throws error).
*/
delete(_key: K): void {
throw new Error("Unsupported operation: delete");
}
/**
* Unsupported (throws error).
*/
clear(): void {
throw new Error("Unsupported operation: delete");
}
/**
* Note: returns the value even if has = false, so
* that it's possible to get it, and so that common
* get! idioms work. getIfPresent does the usual
* get semantics.
* @param key [description]
* @return [description]
*/
get(key: K): C {
return this.getInternal(key, this.keyAsString(key), false)[0];
}
getIfPresent(key: K): C | undefined {
const str = this.keyAsString(key);
if (this.inReceiveKeyStr === str) {
// The state of nontrivialMap cannot be relied
// upon, since it hasn't been recalculated yet.
// Instead, use canGC directly.
if (!this.inReceiveValue!.canGC()) {
return this.inReceiveValue!;
} else return undefined;
}
return this.nontrivialMap.get(this.keyAsString(key));
}
has(key: K): boolean {
const str = this.keyAsString(key);
if (this.inReceiveKeyStr === str) {
// The state of nontrivialMap cannot be relied
// upon, since it hasn't been recalculated yet.
// Instead, use canGC directly.
return !this.inReceiveValue!.canGC();
} else return this.nontrivialMap.has(str);
}
hasValue(value: C): boolean {
return this.owns(value) && !value.canGC();
}
/**
* Returns true if value is owned by this
* map, i.e., it is an output of this.get.
*/
owns(value: C): boolean {
return value.parent === this;
}
get size(): number {
return this.nontrivialMap.size;
}
*entries(): IterableIterator<[K, C]> {
// Note: this doesn't check inReceiveValue. Should document.
for (const [keyStr, value] of this.nontrivialMap) {
yield [this.stringAsKey(keyStr), value];
}
}
values(): IterableIterator<C> {
// Override for efficiency.
// Note: this doesn't check inReceiveValue. Should document.
return this.nontrivialMap.values();
}
/**
* Returns the unique key associated to a value owned
* by this map. If
* the value is not owned by this map, returns undefined.
*
* @param searchElement The value to locate in this map.
*/
keyOf(searchElement: C): K | undefined {
if (!this.owns(searchElement)) return undefined;
return this.stringAsKey(searchElement.name);
}
save(): Uint8Array {
const childSaves: { [name: string]: Uint8Array } = {};
// Only need to save nontrivial children, since trivial
// children are in their initial states.
for (const [name, child] of this.nontrivialMap) {
childSaves[name] = child.save();
}
const saveMessage = LazyMutCMapSave.create({
childSaves,
});
return LazyMutCMapSave.encode(saveMessage).finish();
}
load(saveData: Optional<Uint8Array>): void {
if (!saveData.isPresent) {
// No children to notify.
return;
}
const saveMessage = LazyMutCMapSave.decode(saveData.get());
for (const [name, childSave] of Object.entries(saveMessage.childSaves)) {
const child = this.getInternal(this.stringAsKey(name), name, true)[0];
child.load(Optional.of(childSave));
}
}
getDescendant(namePath: string[]): Collab | undefined {
if (namePath.length === 0) return this;
const name = namePath[namePath.length - 1];
const child = this.getInternal(this.stringAsKey(name), name, false)[0];
namePath.length--;
return child.getDescendant(namePath);
}
canGC() {
/*
* We don't need to check here that the backup
* map is nonempty (which would be expensive):
* each value points to us (due to Collab.parent),
* so we will only be forgotten by a containing
* implicit map if all of our children have no
* references to them, which is equivalent to the
* backup map being empty(able).
*/
return this.nontrivialMap.size === 0;
}
} | the_stack |
import { WebElement, By, Locator } from "selenium-webdriver";
import { ByExtended, XpathBuilder } from "./selenium-utils";
import { TestUtils } from "./test-utils";
import { WaitUtils } from "./wait-utils";
import * as Assert from "assert";
export abstract class ACElement {
private _id: string;
private _underlyingElement?: WebElement = undefined;
private _container?: ACContainer;
protected constructor(underlyingElement: WebElement | string, container?: ACContainer) {
if (typeof underlyingElement === "string") {
this._id = underlyingElement;
} else {
this._underlyingElement = underlyingElement;
}
this._container = container;
}
public get id(): string {
return this._id;
}
public get underlyingElement(): WebElement | undefined {
return this._underlyingElement;
}
protected set underlyingElement(underlyingElement: WebElement | undefined) {
this._underlyingElement = underlyingElement;
}
public get container(): ACContainer | undefined {
return this._container;
}
abstract ensureUnderlyingElement(className?: string): Promise<void>;
elementWasFound(): boolean {
return (this.underlyingElement !== undefined);
}
async getCssPropertyValue(propertyName: string): Promise<string | undefined> {
if (this.elementWasFound()) {
return await TestUtils.getInstance().getCssPropertyValueForElement(this.underlyingElement!, propertyName);
} else {
return undefined;
}
}
async elementIsVisible(): Promise<boolean> {
return (await this.underlyingElement?.getAttribute("visible") === "true") || (await this.underlyingElement!.isDisplayed());
}
async elementIsCssVisible(): Promise<boolean> {
return (await this.getCssPropertyValue("visibility") === "visible");
}
async getChildrenHtml(): Promise<string> {
return (await this.underlyingElement!.getAttribute("innerHtml"));
}
async getHtml(): Promise<string> {
return (await this.underlyingElement!.getAttribute("outerHtml"));
}
}
export abstract class ACActionableElement extends ACElement {
async click()
{
await TestUtils.getInstance().clearInputs();
await this.underlyingElement?.click();
}
}
export class Input extends ACElement {
protected div: WebElement;
protected label?: WebElement;
protected errorMessage?: WebElement;
async setData(data: string): Promise<void> {
await this.underlyingElement?.click();
await this.underlyingElement?.sendKeys(data);
}
override async ensureUnderlyingElement(className?: string): Promise<void> {
this.div = await TestUtils.getInstance().getInputContainer(this.id, this.container);
this.underlyingElement = await TestUtils.getInstance().getInput(className!, this.div);
await this.getLabel();
}
hasLabel(): boolean {
return (this.label !== undefined);
}
async getLabel(): Promise<string | undefined> {
await this.ensureLabel();
return await this.label?.getText();
}
async getErrorMessage(): Promise<string | undefined> {
await this.ensureErrorMessage();
return this.errorMessage?.getText();
}
async isRequired(): Promise<boolean> {
return await this.classListContains(this.underlyingElement!, "ac-input-required");
}
async validationFailed(): Promise<boolean> {
return await this.classListContains(this.underlyingElement!, "ac-input-validation-failed");
}
async classListContains(element: WebElement, classToQuery: string): Promise<boolean> {
return (await element.getAttribute("class")).split(" ").includes(classToQuery);
}
async ensureLabel(): Promise<void> {
const htmlInputId: string = await this.underlyingElement!.getAttribute("id");
const labels: WebElement[] = await this.div.findElements(By.xpath(new XpathBuilder().setTagName("label").addAttributeEquals("for", htmlInputId).buildXpath()));
this.label = (labels.length > 0) ? labels[0] : undefined;
}
async ensureErrorMessage(): Promise<void> {
if (await this.validationFailed()) {
this.errorMessage = await this.div.findElement(By.id(await this.getErrorMessageId()));
}
}
protected async getErrorMessageId(): Promise<string> {
const ariaLabeledBy = await this.underlyingElement!.getAttribute("aria-labelledby");
let labels: string[] = ariaLabeledBy.split(" ");
Assert.strictEqual(labels.length, 2, `Labels contains more than two labels ${labels}`);
labels.splice(labels.indexOf(await this.label!.getAttribute("id")), 1);
Assert.strictEqual(labels.length, 1, `Labels contains more than one label ${labels}`);
return labels[0];
}
async getChildrenHtml(): Promise<string> {
return (await this.div.getAttribute("innerHtml"));
}
async getHtml(): Promise<string> {
return (await this.div.getAttribute("outerHtml"));
}
}
export class ACTypeableInput extends Input {
async isFocused(): Promise<boolean> {
if (this.elementWasFound()) {
const inputId: string = await this.underlyingElement!.getAttribute("id");
const activeElementId: string = await TestUtils.getInstance().driver.switchTo().activeElement().getAttribute("id");
return (inputId === activeElementId);
}
return false;
}
}
export class ACInputText extends ACTypeableInput {
static async getInputWithId(id: string, container?: ACContainer): Promise<ACInputText> {
const input = new ACInputText(id, container);
await input.ensureUnderlyingElement("ac-textInput");
return input;
}
}
export class ACInputDate extends ACTypeableInput {
static async getInputWithId(id: string, container?: ACContainer): Promise<ACInputDate> {
const input = new ACInputDate(id, container);
await input.ensureUnderlyingElement("ac-dateInput");
return input;
}
async setDate(year: number, month: number, day: number) {
await this.setData(month.toString().padStart(2, "0") + day.toString().padStart(2, "0") + year.toString());
}
}
export class ACInputTime extends ACTypeableInput {
static async getInputWithId(id: string, container?: ACContainer): Promise<ACInputTime> {
const input = new ACInputTime(id, container);
await input.ensureUnderlyingElement("ac-timeInput");
return input;
}
async setTime(hour: number, minute: number) {
const meridian: string = (hour >= 12) ? "PM" : "AM";
await this.setData(hour.toString().padStart(2, "0") + minute.toString().padStart(2, "0") + meridian);
}
}
export class ACInputNumber extends ACTypeableInput {
static async getInputWithId(id: string, container?: ACContainer): Promise<ACInputNumber> {
const input = new ACInputNumber(id, container);
await input.ensureUnderlyingElement("ac-numberInput");
return input;
}
}
export class ACInputChoiceSet extends Input
{
isExpanded: boolean = false;
isMultiSelect: boolean = false;
underlyingExpandedElements: WebElement[];
private constructor(id: string, isExpanded: boolean, isMultiSelect: boolean, container?: ACContainer) {
super(id, container);
this.isExpanded = isExpanded;
this.isMultiSelect = isMultiSelect;
}
override async ensureUnderlyingElement(className?: string): Promise<void> {
this.div = await TestUtils.getInstance().getInputContainer(this.id, this.container);
if (!this.isExpanded) {
await this.getCompactChoiceSet(this.id, this.container);
}
else {
await this.getExpandedChoiceSet(this.id, this.container);
}
}
private async getCompactChoiceSet(id: string, container?: ACContainer): Promise<void> {
this.underlyingElement = await this.div.findElement(By.className("ac-choiceSetInput-compact"));
}
private async getExpandedChoiceSet(id: string, container?: ACContainer): Promise<void> {
if (this.isMultiSelect) {
this.underlyingElement = await this.div.findElement(ByExtended.containsClass("ac-choiceSetInput-multiSelect"));
} else {
this.underlyingElement = await this.div.findElement(ByExtended.containsClass("ac-choiceSetInput-expanded"));
}
this.underlyingExpandedElements = await TestUtils.getInstance().getElementsWithName(id, container);
}
static async getInputWithId(id: string, isExpanded: boolean, isMultiSelect: boolean, container?: ACContainer): Promise<ACInputChoiceSet> {
const input = new ACInputChoiceSet(id, isExpanded, isMultiSelect, container);
await input.ensureUnderlyingElement();
return input;
}
override async setData(data: string): Promise<void> {
if (this.elementWasFound()) {
if (this.isExpanded) {
if (this.isMultiSelect) {
const options: string[] = data.split(",");
for (const choice of this.underlyingExpandedElements)
{
const choiceValue = await choice.getAttribute("aria-label");
const choiceIsSelected: boolean = await choice.isSelected();
// if the choice has to be selected and it's not selected, click it
// or if the choice must not be selected but is selected, click it
if ((options.includes(choiceValue) && !choiceIsSelected) ||
(!options.includes(choiceValue) && choiceIsSelected)) {
await choice.click();
}
}
}
else
{
for (const choice of this.underlyingExpandedElements)
{
const choiceValue = await choice.getAttribute("aria-label");
if (choiceValue === data) {
await choice.click();
}
}
}
} else {
let underlyingElement: WebElement = this.underlyingElement!;
await underlyingElement.click();
let option = await underlyingElement.findElement(By.xpath(`//*[@aria-label='${data}']`));
await option.click();
}
}
}
override elementWasFound(): boolean {
if (this.isExpanded) {
return this.underlyingExpandedElements.length > 0;
}
else {
return super.elementWasFound();
}
}
override async getErrorMessageId(): Promise<string> {
if (this.isExpanded) {
const ariaLabeledBy = await this.underlyingExpandedElements[0].getAttribute("aria-labelledby");
const choiceId = await this.underlyingExpandedElements[0].getAttribute("id");
let labels: string[] = ariaLabeledBy.split(" ");
Assert.strictEqual(labels.length, 3, `Labels contains more than three labels ${labels}`);
labels.splice(labels.indexOf(await this.label!.getAttribute("id")), 1);
labels.splice(labels.indexOf(await this.getIdOfLabel(choiceId)), 1);
Assert.strictEqual(labels.length, 1, `Labels contains more than one label ${labels}`);
return labels[0];
} else {
return super.getErrorMessageId();
}
}
private async getIdOfLabel(choiceId: string): Promise<string> {
const label: WebElement = await this.div.findElement(By.xpath(new XpathBuilder().setTagName("label").addAttributeEquals("for", choiceId).buildXpath()));
return await label.getAttribute("id");
}
}
export class ACInputToggle extends Input {
static async getInputWithId(id: string, container?: ACContainer): Promise<ACInputToggle> {
const input = new ACInputToggle(id, container);
await input.ensureUnderlyingElement("ac-toggleInput");
return input;
}
override async setData(data: string): Promise<void> {
if (this.elementWasFound()) {
if (data === "set") {
await this.set();
}
else if (data === "unset") {
await this.unset();
}
else {
await this.toggle();
}
}
}
async set(): Promise<void> {
const isInputSelected: boolean = await this.underlyingElement!.isSelected();
if (!isInputSelected) {
await this.toggle();
}
}
async unset(): Promise<void> {
const isInputSelected: boolean = await this.underlyingElement!.isSelected();
if (isInputSelected) {
await this.toggle();
}
}
async toggle(): Promise<void> {
await this.underlyingElement?.click();
}
}
export class ACContainer extends ACActionableElement {
static async getContainer(id: string): Promise<ACContainer> {
return new ACContainer(id);
}
static async getContainerWithAction(tooltip: string, parentContainer?: ACContainer): Promise<ACContainer> {
const container = new ACContainer(tooltip, parentContainer);
await container.ensureUnderlyingElement();
return container;
}
override async ensureUnderlyingElement(className?: string): Promise<void> {
this.underlyingElement = await TestUtils.getInstance().tryGetContainerWithAction(this.id, this.container);
}
}
// Currently Column and ColumnSet behave just as container (except columnset having a different class name),
// leaving the empty classes for code clarity when used
export class ACColumn extends ACContainer {}
export class ACColumnSet extends ACContainer {}
export class ACCard extends ACContainer {
private index: number = 0;
constructor(underlyingElement: string, index?: number) {
super(underlyingElement);
if (index !== undefined) {
this.index = index;
}
}
static async getCard(index?: number): Promise<ACCard> {
const card = new ACCard("", index);
await card.ensureUnderlyingElement("ac-adaptiveCard");
return card;
}
override async ensureUnderlyingElement(className?: string): Promise<void> {
const cardList = await TestUtils.getInstance().getElementsWithClass(className!);
this.underlyingElement = cardList[this.index];
}
}
export class ACImage extends ACActionableElement {
static async getImage(title: string, container?: ACContainer): Promise<ACImage>
{
const image = new ACImage(title, container);
await image.ensureUnderlyingElement("ac-image");
return image;
}
override async ensureUnderlyingElement(className?: string): Promise<void> {
this.underlyingElement = await TestUtils.getInstance().getImageWithTitle(this.id, className!, this.container);
}
async getSrc(): Promise<string> {
return await this.underlyingElement!.getAttribute("src");
}
}
export class ACAction extends ACActionableElement {
static async clickOnActionWithTitle(title: string): Promise<void>
{
let action: ACAction = await this.getActionWithTitle(title);
await action.click();
}
static async getActionWithTitle(title: string): Promise<ACAction>
{
let action = new ACAction(title);
await action.ensureUnderlyingElement();
return action;
}
override async ensureUnderlyingElement(className?: string): Promise<void> {
this.underlyingElement = await TestUtils.getInstance().tryGetActionWithTitle(this.id);
}
}
// As currently there's only one carousel per card is supported then this tests are simpler
export class ACCarousel {
private constructor(){}
static async clickOnLeftArrow()
{
const leftArrow = await TestUtils.getInstance().driver.findElement(By.className("ac-carousel-left"));
await leftArrow.click();
}
static async clickOnRightArrow()
{
const leftArrow = await TestUtils.getInstance().driver.findElement(By.className("ac-carousel-right"));
await leftArrow.click();
}
static async isPageVisible(pageId: string): Promise<Boolean>
{
let anyPageIsVisible = false;
// Due to how the swiper library is made, the first and last pages are duplicated, if we were to use the regular
// getElementWithId method we would retrieve the duplicated slide, so we have to get the second element with that id
const pages = await TestUtils.getInstance().getElementsWithId(pageId);
for (const page of pages)
{
const pageVisibility = await TestUtils.getInstance().getCssPropertyValueForElement(page, "visibility");
anyPageIsVisible = anyPageIsVisible || (pageVisibility === "visible")
}
return anyPageIsVisible;
}
static async getPageDirection(pageId: string): Promise<string>
{
const pageElement = await TestUtils.getInstance().getElementWithId(pageId);
// The actual direction is provided to a id-less div under the page, so
// we query for that value
const pageContainer = await pageElement.findElement(By.xpath("./*"));
const pageDirection = await pageContainer.getAttribute("dir");
return pageDirection;
}
// This is a helper method to handle the odd scenario of the carousel not behaving correctly
// when clicking an arrow while the carousel is moving
static async waitForAnimationsToEnd(): Promise<void>
{
await WaitUtils.waitFor(1000);
}
} | the_stack |
import { TokenStr } from "../models/common";
import { User } from "../models/user";
//import { getOriginPrivateDirectory } from "native-file-system-adapter";
//import cacheAdapter from "native-file-system-adapter/src/adapters/cache";
export interface ISettingsStorage {
// eslint-disable-next-line no-unused-vars
set(key: string, value: any): Promise<void>;
// eslint-disable-next-line no-unused-vars
get(key: string): Promise<any>;
// eslint-disable-next-line no-unused-vars
remove(key: string): Promise<void>;
}
class DocumentSettings implements ISettingsStorage {
set(key: string, value: any): Promise<void> {
Office.context.document.settings.set(key, value);
return this.save();
}
get(key: string): Promise<any> {
const value = Office.context.document.settings.get(key);
return Promise.resolve(value);
}
remove(key: string): Promise<void> {
Office.context.document.settings.remove(key);
return this.save();
}
private save(): Promise<void> {
const promise = new Promise<void>((resolve, reject) => {
Office.context.document.settings.saveAsync(function (asyncResult) {
if (asyncResult.status == Office.AsyncResultStatus.Failed) {
// reject('Settings save failed. Error: ' + asyncResult.error.message);
reject(asyncResult.error.message);
} else {
resolve();
}
});
});
return promise;
}
}
// class FileSettings implements ISettingsStorage {
// private fileHandle;
// private dirHandle;
// private async createFile(): Promise<void> {
// console.log("create file");
// this.dirHandle = await getOriginPrivateDirectory(cacheAdapter);
// this.fileHandle = await this.dirHandle.getFileHandle("userInfo.txt", { create: true });
// }
// async set(key: string, value: any): Promise<void> {
// console.log("set key");
// if (!this.fileHandle) {
// await this.createFile();
// }
// const obj = { key: value };
// const blob = new Blob([JSON.stringify(obj)], { type: "text/plain" });
// var writer = this.fileHandle.createWritable();
// await writer.write(blob);
// await writer.close();
// }
// async get(key: string): Promise<any> {
// const file = await this.fileHandle.getFile();
// const contents = await file.text();
// const object = JSON.parse(contents);
// const value = object.userInfoObject[key];
// return Promise.resolve(value);
// }
// // eslint-disable-next-line no-unused-vars
// async remove(key: string): Promise<void> {
// await this.dirHandle.removeEntry("userInfo.txt");
// }
// }
abstract class StorageSettings implements ISettingsStorage {
protected storage: Storage;
constructor(storage: Storage) {
this.storage = storage;
}
set(key: string, value: any): Promise<void> {
this.storage.setItem(key, JSON.stringify(value));
return Promise.resolve();
}
get(key: string): Promise<any> {
const valueJson = this.storage.getItem(key);
if (valueJson === "") {
return Promise.resolve("");
}
if (valueJson) {
const retVal = JSON.parse(valueJson);
return Promise.resolve(retVal);
}
return Promise.resolve(null);
}
remove(key: string): Promise<void> {
this.storage.removeItem(key);
return Promise.resolve();
}
}
class LocalStorageSettings extends StorageSettings {
constructor() {
super(window.localStorage);
}
}
class SessionStorageSettings extends StorageSettings {
constructor() {
super(window.sessionStorage);
}
}
class IndexedDBSettings {
protected db: IDBDatabase;
private database: string;
private version: number;
constructor(database: string) {
this.database = database;
}
async createObjectStore(tableNames: string[], keyPath: any[]): Promise<void> {
try {
return new Promise((resolve, reject) => {
//Create or open the database
//await this.db.close();
this.version++;
var request = indexedDB.open(this.database, this.version);
request.onblocked = (e) => {
console.log(e.target);
};
//on upgrade needed, create object store
request.onupgradeneeded = async (e) => {
this.db = (<IDBOpenDBRequest>e.target).result;
tableNames.map(async (tableName, i) => {
await this.db.createObjectStore(tableName, { keyPath: keyPath[i] });
});
};
//on success
request.onsuccess = (e) => {
this.db = (<IDBOpenDBRequest>e.target).result;
this.version = this.db.version;
resolve();
};
//on error
request.onerror = (e) => {
console.log((<IDBOpenDBRequest>e.target).error);
reject();
};
});
} catch (e) {
console.error(e.message);
return;
}
}
async open(): Promise<boolean> {
try {
//Open database
//ONLY FOR TESTS
//await indexedDB.deleteDatabase(this.database);
var request = indexedDB.open(this.database);
//on upgrade needed, create object store
request.onupgradeneeded = async (e) => {
this.db = (<IDBOpenDBRequest>e.target).result;
await this.db.createObjectStore("userInfo", { keyPath: "keyName" });
await this.db.createObjectStore("tablePrimaryKeys", { keyPath: "tableID" });
await this.db.createObjectStore("tableNames", { keyPath: "tableName" });
this.version = e.newVersion;
};
var dbOpened: boolean = await new Promise((resolve, reject) => {
//on success
request.onsuccess = async (e) => {
this.db = (<IDBOpenDBRequest>e.target).result;
var onSuccess = true;
this.version = this.db.version;
console.log("Database version: " + this.version);
resolve(onSuccess);
};
//on error
request.onerror = (e) => {
console.log((<IDBOpenDBRequest>e.target).error);
reject(false);
};
});
return dbOpened;
} catch (error) {
return;
}
}
close(): Promise<void> {
return new Promise((resolve, reject) => {
try {
this.db.close();
resolve();
} catch {
reject();
}
});
}
async set(tableName: string, record: any): Promise<void> {
const tx = this.db.transaction(tableName, "readwrite");
const store = tx.objectStore(tableName);
store.put(record);
}
async get(tableName: string, key: any): Promise<any> {
var record = await new Promise((resolve, reject) => {
const tx = this.db.transaction(tableName, "readonly");
const store = tx.objectStore(tableName);
const request = store.get(key);
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = () => {
reject(request.error);
};
});
return record;
}
async count(tableName: string, key?: any): Promise<number> {
var recordCount: number = await new Promise((resolve, reject) => {
const tx = this.db.transaction(tableName, "readonly");
const store = tx.objectStore(tableName);
const request = store.count(key);
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = () => {
reject(request.error);
};
});
return recordCount;
}
async remove(tableName: string, key: string): Promise<void> {
const tx = this.db.transaction(tableName, "readwrite");
const store = tx.objectStore(tableName);
const result = await store.get(key);
if (!result) {
console.log("Key not found", key);
}
await store.delete(key);
console.log("Data Deleted", key);
return;
}
}
const documentSettings: ISettingsStorage = new DocumentSettings();
// eslint-disable-next-line no-unused-vars
const localStorageSettings: ISettingsStorage = new LocalStorageSettings();
const sessionStorageSettings: ISettingsStorage = new SessionStorageSettings();
//const fileSettings: ISettingsStorage = new FileSettings();
class Settings {
private readonly NAME = "__docSettings";
async getRefreshToken(): Promise<TokenStr | null> {
const value = await documentSettings.get(this.NAME);
return (value && (value["refreshToken"] as TokenStr)) || null;
}
async getUser(): Promise<User | null> {
const value = await documentSettings.get(this.NAME);
return (value && (value["user"] as User)) || null;
}
async setTokenAndUser(token: TokenStr, user: User): Promise<void> {
const settingObj = (await documentSettings.get(this.NAME)) || {};
settingObj["refreshToken"] = token;
settingObj["user"] = user;
await documentSettings.set(this.NAME, settingObj);
}
async removeTokenAndUser(): Promise<void> {
const settingObj = (await documentSettings.get(this.NAME)) || {};
delete settingObj["refreshToken"];
delete settingObj["user"];
await documentSettings.set(this.NAME, settingObj);
}
}
class SessionSettings {
async getRefreshToken(): Promise<TokenStr | null> {
const value = await sessionStorageSettings.get("refreshToken");
return (value as TokenStr) || null;
}
async getUser(): Promise<User | null> {
const value = await sessionStorageSettings.get("user");
return (value as User) || null;
}
async setTokenAndUser(token: TokenStr, user: User): Promise<void> {
await sessionStorageSettings.set("refreshToken", token);
await sessionStorageSettings.set("user", user);
}
async removeTokenAndUser(): Promise<void> {
await sessionStorageSettings.remove("refreshToken");
await sessionStorageSettings.remove("user");
}
}
// class FileStorageSettings {
// async getRefreshToken(): Promise<TokenStr | null> {
// const value = await fileSettings.get("refreshToken");
// return (value as TokenStr) || null;
// }
// async getUser(): Promise<User | null> {
// const value = await fileSettings.get("user");
// return (value as User) || null;
// }
// async setTokenAndUser(token: TokenStr, user: User): Promise<void> {
// const userInfoObject = {
// refreshToken: token,
// user: user,
// };
// console.log("set user info");
// await fileSettings.set("userInfo", userInfoObject);
// }
// async removeTokenAndUser(): Promise<void> {
// await fileSettings.remove("userInfo");
// }
// }
/*class DiskStorageSettings {
constructor() {
openSync("./userInfo.json", 'r', 0o600)
}
async getRefreshToken(): Promise<TokenStr | null> {
try {
var fileContent = readFileSync("./userInfo.json");
var value = JSON.parse(fileContent.toString()).user;
return (value as TokenStr) || null;
} catch (error) {
console.log(error);
}
}
async getUser(): Promise<User | null> {
try {
var fileContent = readFileSync("./userInfo.json");
var value = JSON.parse(fileContent.toString()).user;
return (value as User) || null;
} catch (error) {
console.log(error);
}
}
async setTokenAndUser(token: TokenStr, user: User): Promise<void> {
try {
const UserInfo = {
refreshToken: token,
user: user,
};
const data = JSON.stringify(UserInfo);
writeFileSync("./userInfo.json", data, { mode: 0o600 });
} catch (error) {
console.log(error);
}
}
async removeTokenAndUser(): Promise<void> {
try {
unlinkSync("./userInfo.json");
} catch (error) {
console.log(error);
}
}
}*/
export const settings = new Settings();
export const indexedDatabase = new IndexedDBSettings("BaselineDB");
export const sessionSettings = new SessionSettings();
//export const diskStorage = new DiskStorageSettings();
//export const fileStore = new FileStorageSettings(); | the_stack |
import { Inject,Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { ConfigService } from './config.service';
import { AuthService } from './auth.service';
import { UtilsService } from './utils.service';
import { VmdirService } from './vmdir.service';
import { DOCUMENT } from '@angular/platform-browser';
import { IdentitySourceService } from './identitysources.service';
@Component({
moduleId: module.id,
selector: 'home',
templateUrl: './home.component.html',
})
export class HomeComponent {
private error:any = '';
signedInUser:string = '';
tenantName:string = '';
role:string = '';
containerHeight;
signedIn:boolean = false;
showError:boolean = false;
loginURL:string = '';
displayComponents:boolean = false;
allTenants:any;
isSystemTenant:boolean = false;
rightMenuOpen:boolean = false;
constructor(@Inject(DOCUMENT) private document: any, private authService:AuthService, private vmdirService:VmdirService, private identitySourceService:IdentitySourceService, private utilsService: UtilsService, private configService: ConfigService, private activatedRoute: ActivatedRoute){
}
ngOnInit(){
console.log('sessionStorage:');
console.log(window.sessionStorage);
this.authenticateUser()
this.containerHeight = window.innerHeight * 90 / 100;
console.log(window.innerHeight);
console.log(this.containerHeight);
}
openRightMenu(){
let rightMenu = this.document.getElementById("rightMenu");
rightMenu.style.display = "block";
this.rightMenuOpen = true;
}
closeRightMenu() {
this.document.getElementById("rightMenu").style.display = "none";
this.rightMenuOpen = false;
}
closeSideBar($event:any){
if($event.target.id != 'slideOut'){
let rightMenu = this.document.getElementById("rightMenu");
if(this.rightMenuOpen && $event.target.id != 'rightMenu' ){
this.closeRightMenu();
}
}
}
openIDM(){
let idmUri = "/lightwaveui/idm"
window.location.href = idmUri;
}
redirectToAuthorizeUrl(server:string, OIDCClientID:string, tenantName:string, obj?:any){
let clientHost:string[];
if(obj){
clientHost = obj.getHostName(location.href);
}else{
clientHost = this.getHostName(location.href);
}
let hostName = clientHost[0];
let redirectURI = "https://" + hostName + "/lwraftui";
let openIdConnectURI = "https://" + server + "/openidconnect/oidc/authorize/" + tenantName
let args = "?response_type=id_token%20token&response_mode=fragment&client_id=" +
OIDCClientID +
"&redirect_uri=" + redirectURI +"&state=_state_lmn_&nonce=_nonce_lmn_&scope=openid%20rs_admin_server%20rs_post";
let authorizeUrl = openIdConnectURI + args;
window.location.href = authorizeUrl;
}
readConfigFile(file, object, callback) {
let rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.status == 200) {
if(rawFile.readyState === 4){
callback(rawFile.responseText, object);
}
}else{
let errAlert = document.getElementById("errorAlert")
errAlert.style.display = 'block'
errAlert.innerHTML = "<b>Error!</b> Unable to open lwraft-ui. Missing configuration"
}
}
rawFile.send(null);
}
authenticateUser(){
let jsonData
this.readConfigFile("config/lwraftui.json", this, function(data, obj){
let jsonData:any = {};
jsonData = JSON.parse(data);
let lightwaveServer="", post:any = {}, tenant="", oidcId="" ;
if(jsonData.LightwaveServer && jsonData.LightwaveServer.length > 0){
lightwaveServer = jsonData.LightwaveServer
}
if(jsonData.PostServer){
if(jsonData.PostServer.host && jsonData.PostServer.host.length > 0){
post.host = jsonData.PostServer.host
}
if(jsonData.PostServer.port){
post.port = jsonData.PostServer.port
}
}
if(jsonData.Tenant && jsonData.Tenant.length > 0)
{
tenant = jsonData.Tenant
}
if(jsonData.OIDCClientID && jsonData.OIDCClientID.length > 0)
{
oidcId = jsonData.OIDCClientID
}
if(oidcId.length === 0 || post.host.length === 0 || lightwaveServer.length === 0 || tenant.length === 0){
var errAlert = document.getElementById("errorAlert")
errAlert.style.display = 'block'
errAlert.innerHTML = "<b>Error!</b> Unable to open lightwaveui. Missing/incorrect configuration"
}
let hash:string = window.location.hash;
let access_token, id_token, state, token_type, expires_in;
let curUser:any = sessionStorage.getItem('currentUser');
var queryParams = {};
if(hash.length > 0){
hash = hash.substr(1);
var paramsArr = hash.split('&');
for (var i = 0;i < paramsArr.length; i ++){
var key = paramsArr[i].split('=')[0];
var val = paramsArr[i].split('=')[1];
queryParams[key] = val;
}
access_token = queryParams['access_token'];
id_token = queryParams['id_token'];
state = queryParams['state'];
token_type = queryParams['token_type'];
expires_in = queryParams['expires_in'];
}
// If redirected after successful login, set context and load the UI.
if(hash.length && access_token && id_token && state && token_type && expires_in){
window.sessionStorage.currentUser = 'logout';
obj.configService.currentUser = null;
obj.displayComponents = true;
obj.setcontext(id_token, access_token, token_type, expires_in, state, post);
return;
}
// else , is a valid session available ? If yes, load the UI else redirect to authorize URL to login to server.
if (window.sessionStorage.currentUser && window.sessionStorage.currentUser != 'logout'){
let curUserObj = JSON.parse(curUser);
if(curUserObj && curUserObj.server && curUserObj.server.host === post.host && curUserObj.tenant === tenant){
obj.configService = curUserObj;
obj.displayComponents = true;
obj.loadFromSession();
}else{
window.sessionStorage.currentUser = 'logout';
obj.configService = null;
obj.redirectToAuthorizeUrl(lightwaveServer, oidcId, tenant, obj);
}
}else{
obj.redirectToAuthorizeUrl(lightwaveServer, oidcId, tenant, obj);
}
});
}
getHostName(url:string){
let parts = url.split('://');
let protocol = parts[0];
let server_uri = parts[1]
let server_with_port = server_uri.split('/')[0];
let serverArr = server_with_port.split(':');
let server, port = "443";
if(serverArr.length > 1){
port = serverArr[1];
}
server = serverArr[0];
return [server,port];
}
readQueryParams(params:string, post:any):Boolean{
let curUser:any = sessionStorage.getItem('currentUser');
let paramsArr, idToken, accessToken, state, tokenType, expiresIn;
if(params){
let paramsArr = params.split('&');
idToken = paramsArr[1].split('=')[1];
accessToken = paramsArr[0].split('=')[1];
state = paramsArr[2].split('=')[1];
tokenType = paramsArr[3].split('=')[1];
expiresIn = paramsArr[4].split('=')[1];
}
if(curUser == 'logout'){
this.configService.currentUser = null;
if(accessToken && idToken){
this.displayComponents = true;
this.setcontext(idToken, accessToken, tokenType, expiresIn, state, post);
}else{
return false
}
}else{
if(curUser){// session is valid, load from session.
curUser = JSON.parse(curUser);
this.displayComponents = true;
this.configService.currentUser = curUser;
this.loadFromSession();
}else{ // No session in progress
if(accessToken && idToken){ // load from query parameters if available
this.displayComponents = true;
this.setcontext(idToken, accessToken, tokenType, expiresIn, state, post);
}else{ // No fragments present either.
return false;
}
}
}
return true;
}
loadFromSession(){
let curSession = JSON.parse(window.sessionStorage.currentUser);
this.signedInUser = curSession.first_name;
this.role = curSession.role;
this.tenantName = curSession.tenant;
this.configService.currentUser = curSession;
if(window.location.href.indexOf('#') != -1){
window.location.href = window.location.href.split('#')[0];
}
this.signedIn = true;
}
setcontext(id_token, access_token, token_type, expires_in, state, post:any) {
let decodedJwt:any = this.utilsService.decodeJWT(id_token);
let decodedAccessJwt:any = this.utilsService.decodeJWT(access_token);
let server = this.getHostName(decodedJwt.header.iss);
let currentUser:any = {};
let client = this.getHostName(location.href);
currentUser.server = {};
currentUser.server.host = post.host;
currentUser.server.port = post.port;
currentUser.lightwave_server = server[0].concat(":", server[1])
currentUser.client = {};
currentUser.client.host = client[0].concat(":", client[1]);
currentUser.server.protocol = "https";
currentUser.tenant = decodedJwt.header.tenant;
currentUser.username = decodedJwt.header.sub;
currentUser.first_name = decodedJwt.header.given_name;
currentUser.last_name = decodedJwt.header.family_name;
currentUser.role = decodedAccessJwt.header.admin_server_role;
currentUser.token = {};
currentUser.token.id_token = id_token;
currentUser.token.access_token = access_token;
currentUser.token.expires_in = expires_in;
currentUser.token.token_type = token_type;
currentUser.isSystemTenant = false;
currentUser.token.state = state;
this.configService.currentUser = currentUser;
window.sessionStorage.currentUser = JSON.stringify(this.configService.currentUser);
this.loadFromSession();
}
handleLogout(){
this.authService.logout(this.configService.currentUser.lightwave_server);
}
} | the_stack |
import assert = require('assert');
import {} from 'mocha';
// import * as path from 'path';
import {DictionaryMapUtility, Span} from '@microsoft/bf-dispatcher';
import {Label} from '@microsoft/bf-dispatcher';
import {LabelType} from '@microsoft/bf-dispatcher';
import {Result} from '@microsoft/bf-dispatcher';
import {ILabelArrayAndMap} from '@microsoft/bf-dispatcher';
import {PredictionStructureWithScoreLabelString} from '@microsoft/bf-dispatcher';
import {PredictionType} from '@microsoft/bf-dispatcher';
import {OrchestratorBaseModel} from '../src/basemodel';
// import {OrchestratorHelper} from '../src/orchestratorhelper';
import {Utility} from '../src/utility';
import {Utility as UtilityDispatcher} from '@microsoft/bf-dispatcher';
// NOTE: "orchestrator_test_3_layer" is an aka.ms alias for the 3 layer model "pretrained.20200924.microsoft.dte.00.03.en.onnx"
// https://aka.ms/orchestrator_test_3_layer === https://aka.ms/pretrained.20200924.microsoft.dte.00.03.en.onnx
// We are using an alias so we don't count downloads of this model during unit test runs
const DefaultTestModelId: string = 'orchestrator_test_3_layer';
export class UnitTestHelper {
public static getDefaultFunctionalTestTimeout(): number {
return 3000000;
}
public static getDefaultUnitTestTimeout(): number {
return 100000;
}
public static getDefaultUnitTestDebuggingLogFlag(): boolean {
return false;
}
public static getDefaultUnitTestCleanUpFlag(): boolean {
return true;
}
public static getIgnoreFlag(): boolean {
return false;
}
public static async downloadModelFileForTest(
baseModelPath: string,
onProgress: any = OrchestratorBaseModel.defaultHandler,
onFinish: any = OrchestratorBaseModel.defaultHandler,
basemodelId: string = ''): Promise<void> {
if (basemodelId.length === 0) {
basemodelId = DefaultTestModelId;
}
Utility.debuggingLog('UnitTestHelper.downloadModelFileForTest() entering');
Utility.debuggingLog(`UnitTestHelper.downloadModelFileForTest(), basemodelId=${basemodelId}`);
Utility.debuggingLog(`UnitTestHelper.downloadModelFileForTest(), baseModelPath=${baseModelPath}`);
if (!Utility.exists(baseModelPath)) {
Utility.debuggingLog('UnitTestHelper.downloadModelFileForTest(), ready to call OrchestratorBaseModel.getAsync()');
await OrchestratorBaseModel.getAsync(
baseModelPath,
basemodelId,
onProgress,
onFinish);
Utility.debuggingLog('UnitTestHelper.downloadModelFileForTest(), finished calling OrchestratorBaseModel.getAsync()');
}
Utility.debuggingLog('UnitTestHelper.downloadModelFile() leaving');
}
}
describe('Test Suite - utility', () => {
it('Test.0300 Utility.generateAmbiguousStatisticsAndHtmlTable()', function () {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultUnitTestTimeout());
const predictionStructureWithScoreLabelStringArray: PredictionStructureWithScoreLabelString[] = [];
const ambiguousClosenessThreshold: number = 0.2;
const unknownLabelPredictionThreshold: number = 0;
predictionStructureWithScoreLabelStringArray.push(new PredictionStructureWithScoreLabelString(
'hello world', // text: string,
PredictionType.TruePositive, // labelsPredictedEvaluation: number,
['greeting'], // labels: string[],
'greeting', // labelsConcatenated: string,
'', // labelsConcatenatedToHtmlTable: string,
[0], // labelsIndexes: number[],
['greeting'], // labelsPredicted: string[],
'greeting', // labelsPredictedConcatenated: string,
'', // labelsPredictedConcatenatedToHtmlTable: string,
[0], // labelsPredictedIndexes: number[],
0.8, // labelsPredictedScore: number,
['closest-greeting'], // labelsPredictedClosestText: string[],
[new Result(new Label(LabelType.Intent, 'greeting', new Span(0, 0)), 0.8, 'closest-greeting'),
new Result(new Label(LabelType.Intent, 'None', new Span(0, 0)), 0.79, 'closest-None')], // scoreResultArray: Result[],
[0.8, 0.75], // scoreArray: number[],
'', // predictedScoreStructureHtmlTable: string,
'', // labelsScoreStructureHtmlTable: string
));
const scoringAmbiguousResult: {
'scoringAmbiguousUtterancesArrays': string[][];
'scoringAmbiguousUtterancesArraysHtml': string;
'scoringAmbiguousUtteranceSimpleArrays': string[][];
} = Utility.generateAmbiguousStatisticsAndHtmlTable<string>(
predictionStructureWithScoreLabelStringArray,
ambiguousClosenessThreshold,
unknownLabelPredictionThreshold);
UtilityDispatcher.debuggingLog(`scoringAmbiguousUtterancesArraysHtml.length=${scoringAmbiguousResult.scoringAmbiguousUtterancesArraysHtml.length}`);
UtilityDispatcher.debuggingLog(`scoringAmbiguousUtteranceSimpleArrays=${scoringAmbiguousResult.scoringAmbiguousUtteranceSimpleArrays}`);
UtilityDispatcher.debuggingLog(`scoringAmbiguousUtterancesArrays=${scoringAmbiguousResult.scoringAmbiguousUtterancesArrays}`);
assert.strictEqual(scoringAmbiguousResult.scoringAmbiguousUtterancesArraysHtml.length, 818);
assert.strictEqual(scoringAmbiguousResult.scoringAmbiguousUtteranceSimpleArrays.length, 1);
assert.strictEqual(scoringAmbiguousResult.scoringAmbiguousUtterancesArrays.length, 1);
});
it('Test.0200 Utility.buildStringIdNumberValueDictionaryFromStringArray()', function () {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultUnitTestTimeout());
const labels: string[] = ['A', 'B', 'C'];
const labelArrayAndMap: ILabelArrayAndMap =
Utility.buildStringIdNumberValueDictionaryFromStringArray(labels);
Utility.debuggingLog(`labelArrayAndMap.stringArray=${labelArrayAndMap.stringArray}`);
Utility.debuggingLog(`labelArrayAndMap.stringMap=${labelArrayAndMap.stringMap}`);
const stringArrayLength: number = labelArrayAndMap.stringArray.length;
assert.ok(stringArrayLength === 3);
if (!(Utility.UnknownLabel in labelArrayAndMap.stringMap)) {
labelArrayAndMap.stringArray.push(Utility.UnknownLabel);
labelArrayAndMap.stringMap.set(Utility.UnknownLabel, labelArrayAndMap.stringArray.length - 1);
// ---- NOTE ---- Somehow the code below cannot compile, as the compiler or linter
// ---- NOTE ---- thought that it's a contradiction against the '=== 3' assert.
const stringArrayLengthNew: number = labelArrayAndMap.stringArray.length;
assert.ok(stringArrayLengthNew === 4);
}
});
it('Test.0100 Utility.processUnknownSpuriousLabelsInUtteranceLabelsMap()', function () {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultUnitTestTimeout());
const utteranceLabelsMap: Map<string, Set<string>> = new Map<string, Set<string>>();
const utteranceLabelDuplicateMap: Map<string, Set<string>> = new Map<string, Set<string>>();
const utterance0: string = 'hi';
const labelArray0: string[] = ['greeting', 'chitchat'];
const labelSet0: Set<string> = new Set<string>(labelArray0);
utteranceLabelsMap.set(utterance0, labelSet0);
utteranceLabelDuplicateMap.set(utterance0, labelSet0);
const utterance1: string = 'A';
const labelArray1: string[] = ['greeting', '', 'unknown', 'none'];
const labelSet1: Set<string> = new Set<string>(labelArray1);
utteranceLabelsMap.set(utterance1, labelSet1);
utteranceLabelDuplicateMap.set(utterance1, labelSet1);
const utterance2: string = 'B';
const labelArray2: string[] = ['', 'unknown', 'none'];
const labelSet2: Set<string> = new Set<string>(labelArray2);
utteranceLabelsMap.set(utterance2, labelSet2);
utteranceLabelDuplicateMap.set(utterance2, labelSet2);
const utterance3: string = 'C';
const labelArray3: string[] = [];
const labelSet3: Set<string> = new Set<string>(labelArray3);
utteranceLabelsMap.set(utterance3, labelSet3);
utteranceLabelDuplicateMap.set(utterance3, labelSet3);
const utteranceLabels: {
'utteranceLabelsMap': Map<string, Set<string>>;
'utteranceLabelDuplicateMap': Map<string, Set<string>>; } = {
utteranceLabelsMap,
utteranceLabelDuplicateMap};
Utility.debuggingLog(
`utteranceLabelsMap-B=${DictionaryMapUtility.jsonStringifyStringKeyGenericSetNativeMapArrayValue(utteranceLabelsMap)}`);
Utility.debuggingLog(
`utteranceLabelDuplicateMap-B=${DictionaryMapUtility.jsonStringifyStringKeyGenericSetNativeMapArrayValue(utteranceLabelDuplicateMap)}`);
Utility.processUnknownSpuriousLabelsInUtteranceLabelsMap(
utteranceLabels);
Utility.debuggingLog(
`utteranceLabelsMap=A=${DictionaryMapUtility.jsonStringifyStringKeyGenericSetNativeMapArrayValue(utteranceLabelsMap)}`);
Utility.debuggingLog(
`utteranceLabelDuplicateMap-A=${DictionaryMapUtility.jsonStringifyStringKeyGenericSetNativeMapArrayValue(utteranceLabelDuplicateMap)}`);
assert.ok((utteranceLabelsMap.get('hi') as Set<string>).size === 2);
assert.ok((utteranceLabelsMap.get('A') as Set<string>).size === 1);
assert.ok((utteranceLabelsMap.get('A') as Set<string>).has('greeting'));
assert.ok((utteranceLabelsMap.get('B') as Set<string>).size === 1);
assert.ok((utteranceLabelsMap.get('B') as Set<string>).has(Utility.UnknownLabel));
assert.ok((utteranceLabelsMap.get('C') as Set<string>).size === 1);
assert.ok((utteranceLabelsMap.get('C') as Set<string>).has(Utility.UnknownLabel));
assert.ok((utteranceLabelDuplicateMap.get('hi') as Set<string>).size === 2);
assert.ok((utteranceLabelDuplicateMap.get('A') as Set<string>).size === 1);
assert.ok((utteranceLabelDuplicateMap.get('A') as Set<string>).has('greeting'));
assert.ok((utteranceLabelDuplicateMap.get('B') as Set<string>).size === 1);
assert.ok((utteranceLabelDuplicateMap.get('B') as Set<string>).has(Utility.UnknownLabel));
assert.ok((utteranceLabelDuplicateMap.get('C') as Set<string>).size === 1);
assert.ok((utteranceLabelDuplicateMap.get('C') as Set<string>).has(Utility.UnknownLabel));
});
it('Test.0101 Utility.processUnknownSpuriousLabelsInUtteranceLabelsMapUsingLabelSet()', function () {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultUnitTestTimeout());
const utteranceLabelsMap: Map<string, Set<string>> = new Map<string, Set<string>>();
const utteranceLabelDuplicateMap: Map<string, Set<string>> = new Map<string, Set<string>>();
const utterance0: string = 'hi';
const labelArray0: string[] = ['greeting', 'chitchat'];
const labelSet0: Set<string> = new Set<string>(labelArray0);
utteranceLabelsMap.set(utterance0, labelSet0);
utteranceLabelDuplicateMap.set(utterance0, labelSet0);
const utterance1: string = 'A';
const labelArray1: string[] = ['greeting', '', 'unknown', 'none'];
const labelSet1: Set<string> = new Set<string>(labelArray1);
utteranceLabelsMap.set(utterance1, labelSet1);
utteranceLabelDuplicateMap.set(utterance1, labelSet1);
const utterance2: string = 'B';
const labelArray2: string[] = ['', 'unknown', 'none'];
const labelSet2: Set<string> = new Set<string>(labelArray2);
utteranceLabelsMap.set(utterance2, labelSet2);
utteranceLabelDuplicateMap.set(utterance2, labelSet2);
const utterance3: string = 'C';
const labelArray3: string[] = [];
const labelSet3: Set<string> = new Set<string>(labelArray3);
utteranceLabelsMap.set(utterance3, labelSet3);
utteranceLabelDuplicateMap.set(utterance3, labelSet3);
const labelSet: Set<string> = new Set<string>(['greeting']);
const utteranceLabels: {
'utteranceLabelsMap': Map<string, Set<string>>;
'utteranceLabelDuplicateMap': Map<string, Set<string>>; } = {
utteranceLabelsMap,
utteranceLabelDuplicateMap};
Utility.debuggingLog(
`utteranceLabelsMap-B=${DictionaryMapUtility.jsonStringifyStringKeyGenericSetNativeMapArrayValue(utteranceLabelsMap)}`);
Utility.debuggingLog(
`utteranceLabelDuplicateMap-B=${DictionaryMapUtility.jsonStringifyStringKeyGenericSetNativeMapArrayValue(utteranceLabelDuplicateMap)}`);
Utility.processUnknownSpuriousLabelsInUtteranceLabelsMapUsingLabelSet(
utteranceLabels,
labelSet);
Utility.debuggingLog(
`utteranceLabelsMap=A=${DictionaryMapUtility.jsonStringifyStringKeyGenericSetNativeMapArrayValue(utteranceLabelsMap)}`);
Utility.debuggingLog(
`utteranceLabelDuplicateMap-A=${DictionaryMapUtility.jsonStringifyStringKeyGenericSetNativeMapArrayValue(utteranceLabelDuplicateMap)}`);
assert.ok((utteranceLabelsMap.get('hi') as Set<string>).size === 1);
assert.ok((utteranceLabelsMap.get('hi') as Set<string>).has('greeting'));
assert.ok((utteranceLabelsMap.get('A') as Set<string>).size === 1);
assert.ok((utteranceLabelsMap.get('A') as Set<string>).has('greeting'));
assert.ok((utteranceLabelsMap.get('B') as Set<string>).size === 1);
assert.ok((utteranceLabelsMap.get('B') as Set<string>).has(Utility.UnknownLabel));
assert.ok((utteranceLabelsMap.get('C') as Set<string>).size === 1);
assert.ok((utteranceLabelsMap.get('C') as Set<string>).has(Utility.UnknownLabel));
assert.ok((utteranceLabelDuplicateMap.get('hi') as Set<string>).size === 1);
assert.ok((utteranceLabelDuplicateMap.get('hi') as Set<string>).has('greeting'));
assert.ok((utteranceLabelDuplicateMap.get('A') as Set<string>).size === 1);
assert.ok((utteranceLabelDuplicateMap.get('A') as Set<string>).has('greeting'));
assert.ok((utteranceLabelDuplicateMap.get('B') as Set<string>).size === 1);
assert.ok((utteranceLabelDuplicateMap.get('B') as Set<string>).has(Utility.UnknownLabel));
assert.ok((utteranceLabelDuplicateMap.get('C') as Set<string>).size === 1);
assert.ok((utteranceLabelDuplicateMap.get('C') as Set<string>).has(Utility.UnknownLabel));
});
it('Test.0000 Utility.exists()', function () {
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultUnitTestTimeout());
Utility.debuggingLog(`process.cwd()=${process.cwd()}`);
const doesExist: boolean = Utility.exists('resources/data/Columnar/Email.txt');
Utility.debuggingLog(`doesExist=${doesExist}`);
assert.ok(doesExist);
});
}); | the_stack |
import {
allContentsKind,
asContentsKind,
ColumnSortOrientation,
Comparison,
ComparisonFilterDescription,
ContentsKind,
ConvertColumnInfo,
CreateColumnJSMapInfo,
IColumnDescription,
kindIsString,
RecordOrder,
RemoteObjectId,
StringFilterDescription,
StringColumnFilterDescription, AggregateDescription, CountWithConfidence, DataKinds, SaveAsArgs, LoadedTable, Empty
} from "../javaBridge";
import {OnCompleteReceiver} from "../rpc";
import {SchemaClass} from "../schemaClass";
import {BigTableView} from "../modules";
import {Dialog, FieldKind, saveAs} from "../ui/dialog";
import {FullPage, PageTitle} from "../ui/fullPage";
import {SubMenu, TopMenuItem} from "../ui/menu";
import {SpecialChars, ViewKind} from "../ui/ui";
import {
cloneToSet,
Converters, getUUID,
ICancellable,
significantDigits,
} from "../util";
import {HeavyHittersReceiver, HeavyHittersView} from "./heavyHittersView";
import {DataRangesReceiver} from "./dataRangesReceiver";
import {TableOperationCompleted} from "../modules";
import {ErrorReporter} from "../ui/errReporter";
import {TableMeta, ReceiverCommonArgs} from "../ui/receiver";
import {GeoMapReceiver} from "./geoView";
/**
* A base class for TableView and SchemaView.
*/
export abstract class TSViewBase extends BigTableView {
protected defaultProvenance: string;
protected constructor(
remoteObjectId: RemoteObjectId,
meta: TableMeta,
page: FullPage,
viewKind: ViewKind) {
super(remoteObjectId, meta, page, viewKind);
}
/**
* Get the list of the column names for the columns that are selected.
* These are columns in the underlying data table.
*/
public abstract getSelectedColNames(): string[];
/**
* Get the number of columns that are selected.
* These are columns in the underlying data table.
*/
public abstract getSelectedColCount(): number;
protected hasGeo(colName: string): boolean {
for (const geoInfo of this.meta.geoMetadata) {
if (geoInfo.columnName == colName)
return true;
}
return false;
}
/**
* Convert the data in a column to a different column kind.
*/
public convert(from: string, order: RecordOrder | null,
rowsDesired: number, aggregates: AggregateDescription[] | null): void {
const dialog = new ConverterDialog(from, this.getSchema());
dialog.setAction(
() => {
const colName = dialog.getColumnName("columnName");
const columnIndex = this.getSchema().columnIndex(colName);
if (columnIndex < 0) {
this.page.reportError(`Column name ${colName} not found.`);
return;
}
const kindStr = dialog.getFieldValue("newKind");
const kind: ContentsKind = asContentsKind(kindStr);
const keep = dialog.getBooleanValue("keep");
const newColName = keep ?
dialog.getFieldValue("newColumnName") :
colName;
if (keep && this.getSchema().columnIndex(newColName) >= 0) {
this.page.reportError(`Column name ${newColName} already exists in table.`);
return;
}
const args: ConvertColumnInfo = {
colName,
newColName: newColName,
newKind: kind,
columnIndex: columnIndex,
};
const rr = this.createStreamingRpcRequest<string>("convertColumn", args);
const cd: IColumnDescription = {
kind: kind,
name: newColName,
};
const o = order != null ? order.clone() : null;
if (o != null)
o.addColumn({columnDescription: cd, isAscending: true});
let schema: SchemaClass = this.getSchema();
if (!keep) {
const initial = schema.length;
schema = schema.filter((c) => c.name != colName);
console.assert(schema.length < initial);
}
schema = schema.insert(cd, columnIndex);
const meta: TableMeta = { schema: schema, rowCount: this.meta.rowCount, geoMetadata: this.meta.geoMetadata };
rr.invoke(new TableOperationCompleted(this.page, rr, meta,
o, rowsDesired, aggregates));
});
dialog.show();
}
protected exportSchema(): void {
saveAs("schema.json", JSON.stringify(this.getSchema().schema));
}
protected geo(column: IColumnDescription): void {
const rr = this.createGeoRequest(column);
const args: ReceiverCommonArgs = {
title: new PageTitle("Count of " + column.name,
this.defaultProvenance),
remoteObject: this,
...this.meta,
originalPage: this.page,
options: { chartKind: "Map", reusePage: false }
};
const rec = new GeoMapReceiver(args, column, rr, null);
rr.invoke(rec);
}
public renameColumn(): void {
const cols = this.getSelectedColNames();
if (cols.length !== 1) {
this.page.reportError("Select only 1 column to rename");
return;
}
const colName = cols[0];
const dialog = new Dialog("Rename column", "Choose a new name for column " + colName);
const name = dialog.addTextField("name", "New name",
FieldKind.String, colName, "New name to use for column");
name.required = true;
dialog.setAction(() => {
const from = colName;
const to = dialog.getFieldValue("name");
if (this.getSchema().find(to) != null) {
this.page.reportError("Cannot rename column to " + to + " since the name is already used.");
return;
}
this.doRenameColumn(from, to);
});
dialog.show();
}
protected abstract doRenameColumn(from: string, to: string): void;
public saveAs(schema: SchemaClass, fileKind: DataKinds): void {
const dialog = new Dialog("Save as " + fileKind + " files",
"Describe the set of files where data will be saved.");
const label = fileKind == "db" ? "Table" : "Folder";
const value = fileKind == "db" ? "table" : "/";
const help = fileKind == "db" ? "Table to save data to" :
"All files will be written to this folder on each of the remote machines.";
const folder = dialog.addTextField("folderName", label, FieldKind.String, value, help);
folder.required = true;
dialog.setCacheTitle("saveAsDialog");
dialog.setAction(() => {
const folderName = dialog.getFieldValue("folderName");
const directory = fileKind == "db" ? "T" + getUUID().replace(/-/g, '') : folderName;
const args: SaveAsArgs = {
folder: directory,
fileKind,
schema: schema.schema,
};
const rr = this.createStreamingRpcRequest<Empty>("saveAs", args);
const renderer = new SaveReceiver(this.page, args, folderName, rr);
rr.invoke(renderer);
});
dialog.show();
}
public createJSColumnDialog(order: RecordOrder | null, tableRowsDesired: number,
aggregates: AggregateDescription[] | null): void {
const dialog = new Dialog(
"Create new column", "Specify a JavaScript function which computes the values in a new column.");
const name = dialog.addTextField(
"outColName", "Column name", FieldKind.String, null, "Name to use for the generated column.");
name.required = true;
dialog.addSelectField(
"outColKind", "Data type", allContentsKind, "String",
"Type of data in the generated column.");
dialog.addMultiLineTextField("function", "Function",
null, "function map(row) {\nreturn row['col'];\n}", null,
"A JavaScript function named 'map' that computes the values for each row of the generated column." +
"The function has a single argument 'row'. The row is a JavaScript map that can be indexed with " +
"a column name (a string) and which produces a value.");
dialog.setCacheTitle("CreateJSDialog");
dialog.setAction(() => this.createJSColumn(dialog, order, tableRowsDesired, aggregates));
dialog.show();
}
private createJSColumn(dialog: Dialog, order: RecordOrder | null,
tableRowsDesired: number, aggregates: AggregateDescription[] | null): void {
const col = dialog.getFieldValue("outColName");
if (this.getSchema().find(col) != null) {
this.page.reportError("Column " + col + " already exists");
return;
}
const kind = dialog.getFieldValue("outColKind");
const fun = dialog.getFieldValue("function");
const selColumns = cloneToSet(this.getSelectedColNames());
const subSchema = this.getSchema().filter((c) => selColumns.has(c.name));
const arg: CreateColumnJSMapInfo = {
jsFunction: fun,
outputColumn: col,
outputKind: asContentsKind(kind),
schema: subSchema.schema,
};
const rr = this.createJSCreateColumnRequest(arg);
const cd: IColumnDescription = {
kind: arg.outputKind,
name: col,
};
const schema = this.getSchema().append(cd);
const o = order != null ? order.clone() : null;
if (o != null)
o.addColumn({columnDescription: cd, isAscending: true});
const rec = new TableOperationCompleted(
this.page, rr, { rowCount: this.meta.rowCount, schema, geoMetadata: this.meta.geoMetadata },
o, tableRowsDesired, aggregates);
rr.invoke(rec);
}
protected chart(cds: IColumnDescription[], chartKind: ViewKind): void {
const exact = this.isPrivate(); // If private, do not sample
const cols = chartKind === "Heatmap" ? cds.slice(0,2) : cds;
if (this.isPrivate())
// Do not allow additional columns when displaying private datahrsy
cds = cds.slice(0,2);
const rr = this.createDataQuantilesRequest(cols, this.page, chartKind);
const buckets = cols.map(_ => 0);
rr.invoke(new DataRangesReceiver(this, this.page, rr, this.meta,
buckets, cds, null, this.defaultProvenance, {
reusePage: false, relative: false,
chartKind: chartKind, exact: exact, stacked: true
}));
}
public two2ChartMenu(viewKind: ViewKind): void {
if (this.getSchema().length < 2) {
this.page.reportError("Could not find two columns that can be charted.");
return;
}
const allColumns = this.getSchema().allColumnNames();
const dia = new Dialog(viewKind,
"Display a " + viewKind + " of the data in two columns");
dia.addColumnSelectField("columnName0", "First column", allColumns, allColumns[0],
"First column (X axis)");
dia.addColumnSelectField("columnName1", "Second column", allColumns, allColumns[1],
"Second column " + (viewKind === "2DHistogram" ? "(Y axis)" : "(color)"));
dia.setAction(
() => {
const col0 = dia.getColumnName("columnName0");
const col1 = dia.getColumnName("columnName1");
if (col0 == null || col1 == null)
return;
if (col0 === col1) {
this.page.reportError("The two columns must be distinct");
return;
}
const colDesc = this.getSchema().getCheckedDescriptions([col0, col1]);
this.chart(colDesc, viewKind);
},
);
dia.show();
}
public trellisMenu(chartKind: ViewKind): void {
const count = chartKind == "TrellisHistogram" ? 2 : 3;
const allColumns = this.getSchema().allColumnNames();
const dia = new Dialog(chartKind,
"Display a " + chartKind);
dia.addColumnSelectField("columnName0", "First column", allColumns, allColumns[0],
"First column (X axis)");
const secCol = count === 2 ? "Column to group by" : "Second column ";
dia.addColumnSelectField("columnName1", secCol, allColumns, allColumns[1], secCol);
if (count === 3)
dia.addColumnSelectField("columnName2", "Column to group by", allColumns, allColumns[2],
"Column to group by");
dia.setAction(
() => {
const col0 = dia.getColumnName("columnName0");
const col1 = dia.getColumnName("columnName1");
if (col0 == null || col1 == null)
return;
if (col0 === col1) {
this.page.reportError("The columns must be distinct");
return;
}
const colNames = [col0, col1];
if (count === 3) {
const col2 = dia.getColumnName("columnName2");
if (col2 == null)
return;
if (col0 === col2 || col1 === col2) {
this.page.reportError("The columns must be distinct");
return;
}
colNames.push(col2);
}
const columnDescriptions = this.getSchema().getCheckedDescriptions(colNames);
this.chart(columnDescriptions, chartKind);
},
);
dia.show();
}
protected hLogLog(): void {
if (this.getSelectedColCount() !== 1) {
this.page.reportError("Only one column must be selected");
return;
}
const colName = this.getSelectedColNames()[0];
const rr = this.createHLogLogRequest(colName);
const rec = new CountReceiver(this.getPage(), rr, colName);
rr.invoke(rec);
}
public oneDHistogramMenu(): void {
const dia = new HistogramDialog(this.getSchema().allColumnNames());
dia.setAction(
() => {
const col = dia.getColumn();
const cds = this.getSchema().getCheckedDescriptions([col]);
this.chart(cds, "Histogram");
},
);
dia.show();
}
public saveAsMenu(): TopMenuItem {
return {
text: "Save as", help: "Save the data to persistent storage.", subMenu: new SubMenu([
{
text: "Save as ORC files...",
action: () => this.saveAs(this.getSchema(), "orc"),
help: "Save the data to a set of ORC files on the worker machines.",
}, {
text: "Save as CSV files...",
action: () => this.saveAs(this.getSchema(), "csv"),
help: "Save the data to a set of CSV files on the worker machines.",
}, {
text: "Save as DB table...",
action: () => this.saveAs(this.getSchema(), "db"),
help: "Save the data to a table in the original database.",
},
]),
};
}
public chartMenu(): TopMenuItem {
return {
text: "Chart", help: "Draw a chart", subMenu: new SubMenu([
{ text: "1D Histogram...", action: () => this.oneDHistogramMenu(),
help: "Draw a histogram of the data in one column."},
{ text: "2D Histogram...", action: () => this.two2ChartMenu("2DHistogram"),
help: "Draw a histogram of the data in two columns."},
{ text: "Quartiles...", action: () => this.two2ChartMenu("QuartileVector"),
help: "Draw a vector of quartiles."},
{ text: "Heatmap...", action: () => this.two2ChartMenu("Heatmap"),
help: "Draw a heatmap of the data in two columns."},
{ text: "Trellis histograms...", action: () => this.trellisMenu("TrellisHistogram"),
help: "Draw a Trellis plot of histograms."},
{ text: "Trellis 2D histograms...", action: () => this.trellisMenu("Trellis2DHistogram"),
help: "Draw a Trellis plot of 2D histograms."},
{ text: "Trellis heatmaps...", action: () => this.trellisMenu("TrellisHeatmap"),
help: "Draw a Trellis plot of heatmaps."},
{ text: "Trellis quartiles...", action: () => this.trellisMenu("TrellisQuartiles"),
help: "Draw a Trellis plot of quartile vectors."},
]),
};
}
/**
* Show a dialog to compare values on the specified column.
* @param colName Column name. If null the user will select the column.
* @param order Current record ordering; if null the data will be displayed in a schema view.
* @param tableRowsDesired Number of table rows to display.
* @param aggregates Aggregations that should be computed.
*/
protected showFilterDialog(
colName: string | null, order: RecordOrder | null, tableRowsDesired: number,
aggregates: AggregateDescription[] | null): void {
const cd = this.getSchema().find(colName)!;
const ef = new FilterDialog(cd, this.getSchema());
ef.setAction(() => {
const rowFilter = ef.getFilter();
const strFilter = rowFilter.stringFilterDescription;
const desc = this.getSchema().find(rowFilter.colName)!;
let o = null;
if (order != null) {
o = order.clone();
const so: ColumnSortOrientation = {
columnDescription: desc,
isAscending: true,
};
o.addColumn(so);
}
const rr = this.createFilterColumnRequest(rowFilter);
let provenance = "Filtered " + rowFilter.colName + Converters.stringFilterDescription(strFilter);
const newPage = this.dataset.newPage(new PageTitle(this.page.title.format, provenance), this.page);
rr.invoke(new TableOperationCompleted(newPage, rr, this.meta,
o, tableRowsDesired, aggregates));
});
ef.show();
}
/**
* Show a dialog to compare values on the specified column.
* @param colName Column name. If null the user will select the column.
* @param order Current record ordering.
* @param tableRowsDesired Number of table rows to display.
* @param aggregates Aggregations that should be computed.
*/
protected showCompareDialog(
colName: string | null, order: RecordOrder | null, tableRowsDesired: number,
aggregates: AggregateDescription[] | null): void {
const cfd = new ComparisonFilterDialog(colName, this.getSchema(), this.page.getErrorReporter());
cfd.setAction(() => this.runComparisonFilter(
cfd.getFilter(), order, tableRowsDesired, aggregates));
cfd.show();
}
protected runComparisonFilter(
filter: ComparisonFilterDescription | null, order: RecordOrder | null,
tableRowsDesired: number, aggregates: AggregateDescription[] | null): void {
if (filter == null)
// Some error occurred
return;
const so: ColumnSortOrientation = {
columnDescription: filter.column, isAscending: true,
};
let o = null;
if (order != null) {
o = order.clone();
if (!o.find(filter.column.name))
o.addColumn(so);
}
const rr = this.createFilterComparisonRequest(filter);
const provenance = Converters.comparisonFilterDescription(filter);
const newPage = this.dataset.newPage(new PageTitle(this.page.title.format, provenance), this.page);
rr.invoke(new TableOperationCompleted(newPage, rr, this.meta,
o, tableRowsDesired, aggregates));
}
protected runHeavyHitters(percent: number): void {
if (percent == null || percent < HeavyHittersView.min || percent > 100) {
this.page.reportError("Percentage must be between " + HeavyHittersView.min.toString() + " and 100");
return;
}
const isApprox: boolean = true;
const columnsShown: IColumnDescription[] = [];
this.getSelectedColNames().forEach((v) => {
const colDesc = this.getSchema().find(v)!;
columnsShown.push(colDesc);
});
const rr = this.createHeavyHittersRequest(
columnsShown, percent, this.meta.rowCount, HeavyHittersView.switchToMG);
rr.invoke(new HeavyHittersReceiver(
this.getPage(), this, rr, this.meta,
isApprox, percent, columnsShown, false));
}
protected heavyHittersDialog(): void {
let title = "Frequent Elements from ";
const cols: string[] = this.getSelectedColNames();
if (cols.length <= 1) {
title += " " + cols[0];
} else {
title += cols.length + " columns";
}
const d = new Dialog(title, "Find the most frequent values in the selected columns.");
const perc = d.addTextField("percent", "Threshold (%)", FieldKind.Double, "1",
"All values that appear in the dataset with a frequency above this value (as a percent) " +
"will be considered frequent elements. Must be a number between " + HeavyHittersView.minString +
" and 100%.");
perc.min = HeavyHittersView.minString;
perc.max = "100";
perc.required = true;
d.setAction(() => {
const amount = d.getFieldValueAsNumber("percent");
if (amount != null)
this.runHeavyHitters(amount);
});
d.setCacheTitle("HeavyHittersDialog");
d.show();
}
}
class FilterDialog extends Dialog {
/**
* Create a FilterDialog
* @param columnDescription Display name of the column that is being filtered.
* @param schema Schema of the data.
*/
constructor(private columnDescription: IColumnDescription, private schema: SchemaClass) {
super("Filter" + (columnDescription == null ? "" : (" " + columnDescription.name)),
"Eliminates data from a column according to its value.");
if (columnDescription == null) {
const cols = this.schema.allColumnNames();
if (cols.length === 0)
return;
this.addColumnSelectField("column", "Column", cols, null, "Column that is filtered");
}
this.addTextField("query", "Find", FieldKind.String, null, "Value to search");
this.addBooleanField("asSubString", "Match substrings", false, "Select "
+ "checkbox to allow matching the search query as a substring");
this.addBooleanField("asRegEx", "Treat as regular expression", false, "Select "
+ "checkbox to interpret the search query as a regular expression");
this.addBooleanField("caseSensitive", "Case Sensitive", false, "Select checkbox "
+ "to do a case sensitive search");
this.addBooleanField("complement", "Exclude matches", false, "Select checkbox to "
+ "filter out all matches");
this.setCacheTitle("FilterDialog");
}
public getFilter(): StringColumnFilterDescription {
const textQuery: string = this.getFieldValue("query");
if (this.columnDescription == null) {
const colName = this.getColumnName("column");
this.columnDescription = this.schema.find(colName)!;
}
const asSubString = this.getBooleanValue("asSubString");
const asRegEx = this.getBooleanValue("asRegEx");
const caseSensitive = this.getBooleanValue("caseSensitive");
const complement = this.getBooleanValue("complement");
const stringFilterDescription: StringFilterDescription = {
compareValue: textQuery,
asSubString: asSubString,
asRegEx: asRegEx,
caseSensitive: caseSensitive,
complement: complement,
};
return {
colName: this.columnDescription.name,
stringFilterDescription: stringFilterDescription,
};
}
}
class ComparisonFilterDialog extends Dialog {
private explanation: HTMLElement;
constructor(private colName: string | null,
private schema: SchemaClass,
private reporter: ErrorReporter) {
super("Compare " + (colName != null ? colName : ""),
"Compare values");
this.explanation = this.addText("Value == row[" +
(colName != null ? colName : "?") + "]");
if (colName == null) {
const cols = this.schema.allColumnNames();
if (cols.length === 0)
return;
const col = this.addColumnSelectField("column", "Column", cols, null, "Column that is filtered");
col.onchange = () => this.selectionChanged();
}
const val = this.addTextField("value", "Value", FieldKind.String, "?", "Value to compare");
val.onchange = () => this.selectionChanged();
val.required = true;
const op = this.addSelectField("operation", "Compare", ["==", "!=", "<", ">", "<=", ">="], "<",
"Operation that is used to compare; the value is used at the right in the comparison.");
op.onchange = () => this.selectionChanged();
this.setCacheTitle("ComparisonFilterDialog");
this.selectionChanged();
}
protected getColName(): string {
if (this.colName == null)
return this.getColumnName("column");
return this.colName;
}
protected selectionChanged(): void {
this.explanation.textContent = this.getFieldValue("value") + " " +
this.getFieldValue("operation") +
" row[" + this.getColName().toString() + "]";
}
public getFilter(): ComparisonFilterDescription | null {
const value: string = this.getFieldValue("value");
let doubleValue: number | null = null;
let endValue: number | null = null;
let colSelected;
if (this.colName == null) {
colSelected = this.getColumnName("column");
} else {
colSelected = this.colName;
}
const columnDescription = this.schema.find(colSelected);
if (columnDescription == null)
return null;
if (columnDescription.kind === "Date") {
const date = new Date(value);
if (date == null) {
this.reporter.reportError("Could not parse '" + value + "' as a date");
return null;
}
doubleValue = Converters.doubleFromDate(date);
} else if (columnDescription.kind === "LocalDate") {
const date = new Date(value);
if (date == null) {
this.reporter.reportError("Could not parse '" + value + "' as a date");
return null;
}
doubleValue = Converters.doubleFromLocalDate(date);
} else if (!kindIsString(columnDescription.kind)) {
doubleValue = parseFloat(value);
if (doubleValue == null) {
this.reporter.reportError("Could not parse '" + value + "' as a number");
return null;
}
} else if (columnDescription.kind == "Interval") {
const re = /\[([^:]*):([^\]]*)]/;
const m = value.match(re);
if (m == null) {
this.reporter.reportError("Could not parse '" + value + "' as an interval");
return null;
}
doubleValue = parseFloat(m[1]);
endValue = parseFloat(m[2]);
if (doubleValue == null || endValue == null) {
this.reporter.reportError("Could not parse '" + value + "' as an interval");
return null;
}
}
const comparison = this.getFieldValue("operation") as Comparison;
return {
column: columnDescription,
stringValue: kindIsString(columnDescription.kind) ? value : null,
doubleValue: doubleValue,
intervalEnd: endValue,
comparison,
};
}
}
class CountReceiver extends OnCompleteReceiver<CountWithConfidence> {
constructor(page: FullPage, operation: ICancellable<CountWithConfidence>,
protected colName: string) {
super(page, operation, "Estimate distinct count");
}
public run(data: CountWithConfidence): void {
const timeInMs = this.elapsedMilliseconds();
this.page.reportError("Distinct values in column \'" +
this.colName + "\' " + SpecialChars.approx + String(data.count) + "\n" +
"Operation took " + significantDigits(timeInMs / 1000) + " seconds");
}
}
class SaveReceiver extends OnCompleteReceiver<Empty> {
constructor(page: FullPage, protected args: SaveAsArgs, protected tableName: string, operation: ICancellable<Empty>) {
super(page, operation, "Save data");
}
public run(value: Empty): void {
if (this.args.fileKind == "db") {
// We have saved the data to files, now tell the database to load it
const args: LoadedTable = {
schema: this.args.schema!,
tempTableName: this.args.folder,
table: this.tableName
};
// Notice that we use the dataset remote object, and not the one that has
// invoked us.
const rr = this.page.dataset!.remoteObject.createStreamingRpcRequest<Empty>("loadGreenplumTable", args);
rr.chain(this.operation);
const rec = new SaveDbCompleteReceiver(this.page, rr);
rr.invoke(rec);
} else {
this.page.reportError("Save successful in " + significantDigits(this.elapsedMilliseconds() / 1000) + " seconds");
}
}
}
class SaveDbCompleteReceiver extends OnCompleteReceiver<Empty> {
constructor(page: FullPage, operation: ICancellable<Empty>) {
super(page, operation, "Load into database");
}
public run(value: Empty): void {
// If this runs the value is actually irrelevant, we have succeeded.
// The alternative is that an exception was thrown someplace.
this.page.reportError("Save successful in " + significantDigits(this.elapsedMilliseconds() / 1000) + " seconds");
}
}
/**
* A dialog to find out information about how to perform the conversion of the data in a column.
*/
export class ConverterDialog extends Dialog {
// noinspection TypeScriptFieldCanBeMadeReadonly
private columnNameFixed: boolean = false;
constructor(protected readonly colName: string,
protected readonly schema: SchemaClass) {
super("Convert column", "Creates a new column by converting the data in an existing column to a new type.");
const cn = this.addColumnSelectField("columnName", "Column: ", schema.allColumnNames(), colName,
"Column whose type is converted");
const nk = this.addSelectField("newKind", "Convert to: ",
allContentsKind, null,
"Type of data for the converted column.");
const check = this.addBooleanField("keep", "Keep original column", false,
"If true the original column will be kept");
const newNameField = this.addTextField(
"newColumnName", "New column name: ", FieldKind.String, colName,
"A name for the new column. The name must be different from all other column names.");
this.showField("newColumnName", false);
check.onchange = () => this.generateColumnName();
cn.onchange = () => this.generateColumnName();
nk.onchange = () => this.generateColumnName();
// If the user types a column name don't attempt to change it
newNameField.onchange = () => { this.columnNameFixed = true; };
this.generateColumnName();
}
private generateColumnName(): void {
const keep = this.getBooleanValue("keep");
this.showField("newColumnName", keep);
if (this.columnNameFixed)
return;
const cn = this.getColumnName("columnName");
const suffix = " (" + this.getFieldValue("newKind") + ")";
const nn = this.schema.uniqueColumnName(cn + suffix);
this.setFieldValue("newColumnName", nn);
}
}
export class HistogramDialog extends Dialog {
constructor(allColumns: string[]) {
super("1D histogram", "Display a 1D histogram of the data in a column");
this.addColumnSelectField("columnName", "Column", allColumns, null, "Column to histogram");
}
public getColumn(): string {
return this.getColumnName("columnName");
}
} | the_stack |
import 'chrome://resources/mojo/mojo/public/js/mojo_bindings_lite.js';
import {BookmarksApiProxyImpl} from 'chrome://read-later.top-chrome/side_panel/bookmarks_api_proxy.js';
import {BookmarksDragManager, DROP_POSITION_ATTR, DropPosition, overrideFolderOpenerTimeoutDelay} from 'chrome://read-later.top-chrome/side_panel/bookmarks_drag_manager.js';
import {BookmarksListElement, LOCAL_STORAGE_OPEN_FOLDERS_KEY} from 'chrome://read-later.top-chrome/side_panel/bookmarks_list.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {flushTasks} from 'chrome://webui-test/test_util.js';
import {TestBookmarksApiProxy} from './test_bookmarks_api_proxy.js';
suite('SidePanelBookmarkDragManagerTest', () => {
let delegate: BookmarksListElement;
const folders: chrome.bookmarks.BookmarkTreeNode[] = [{
id: '1',
title: 'Bookmarks bar',
parentId: '0',
children: [
{
id: '2',
title: 'Google',
parentId: '1',
url: 'http://google.com',
},
{
id: '3',
title: 'Google Docs',
parentId: '1',
url: 'http://docs.google.com',
},
{
id: '4',
title: 'My folder',
parentId: '1',
children: [{
id: '5',
title: 'My folder\'s child',
url: 'http://google.com',
parentId: '4',
}],
},
{
id: '5',
title: 'Closed folder',
parentId: '1',
children: [{
id: '6',
title: 'Closed folder\'s child',
url: 'http://google.com',
parentId: '5',
}],
},
],
}];
function getDraggableElements(): HTMLElement[] {
function getDraggableElementsInner(root: HTMLElement) {
const draggableElements: HTMLElement[] = [];
const children = root.shadowRoot!.querySelectorAll<HTMLElement>(
'bookmark-folder, .bookmark');
children.forEach(child => {
if (child.tagName === 'BOOKMARK-FOLDER') {
draggableElements.push(child.shadowRoot!.querySelector('#folder')!);
draggableElements.push(...getDraggableElementsInner(child));
} else {
draggableElements.push(child);
}
});
return draggableElements;
}
const rootFolder = delegate.shadowRoot!.querySelector('bookmark-folder')!;
return getDraggableElementsInner(rootFolder);
}
setup(async () => {
document.body.innerHTML = '';
loadTimeData.overrideValues({
bookmarksDragAndDropEnabled: true,
});
const bookmarksApi = new TestBookmarksApiProxy();
bookmarksApi.setFolders(JSON.parse(JSON.stringify(folders)));
BookmarksApiProxyImpl.setInstance(bookmarksApi);
window.localStorage[LOCAL_STORAGE_OPEN_FOLDERS_KEY] =
JSON.stringify(['1', '4']);
delegate = new BookmarksListElement();
new BookmarksDragManager(delegate);
document.body.appendChild(delegate);
await flushTasks();
});
test('DragStartCallsAPI', () => {
let calledIds, calledIndex, calledX, calledY;
let calledTouch = false;
chrome.bookmarkManagerPrivate.startDrag =
(ids: string[], index: number, touch: boolean, x: number,
y: number) => {
calledIds = ids;
calledIndex = index;
calledTouch = touch;
calledX = x;
calledY = y;
};
const draggableBookmark = getDraggableElements()[0]!;
draggableBookmark.dispatchEvent(new DragEvent(
'dragstart',
{bubbles: true, composed: true, clientX: 100, clientY: 200}));
assertDeepEquals(['2'], calledIds);
assertEquals(0, calledIndex);
assertFalse(calledTouch);
assertEquals(100, calledX);
assertEquals(200, calledY);
});
test('DragOverUpdatesAttributes', () => {
chrome.bookmarkManagerPrivate.startDrag = () => {};
const draggableElements = getDraggableElements();
const draggedBookmark = draggableElements[0]!;
draggedBookmark.dispatchEvent(new DragEvent(
'dragstart', {bubbles: true, composed: true, clientX: 0, clientY: 0}));
function assertDropPosition(
dragOverElement: HTMLElement, yRatio: number,
dropPosition: DropPosition) {
const dragOverRect = dragOverElement.getBoundingClientRect();
dragOverElement.dispatchEvent(new DragEvent('dragover', {
bubbles: true,
composed: true,
clientX: dragOverRect.left,
clientY: dragOverRect.top + (dragOverRect.height * yRatio),
}));
assertEquals(
dropPosition, dragOverElement.getAttribute(DROP_POSITION_ATTR));
}
const dragOverBookmark = draggableElements[1]!;
assertDropPosition(dragOverBookmark, 0.2, DropPosition.ABOVE);
assertDropPosition(dragOverBookmark, 0.5, DropPosition.ABOVE);
assertDropPosition(dragOverBookmark, 0.8, DropPosition.BELOW);
const dragOverFolder = draggableElements[2]!;
assertDropPosition(dragOverFolder, 0.2, DropPosition.ABOVE);
assertDropPosition(dragOverFolder, 0.5, DropPosition.INTO);
delegate.isFolderOpen = () => false;
assertDropPosition(dragOverFolder, 0.8, DropPosition.BELOW);
delegate.isFolderOpen = () => true;
assertDropPosition(dragOverFolder, 0.8, DropPosition.INTO);
});
test('DragOverDescendant', async () => {
chrome.bookmarkManagerPrivate.startDrag = () => {};
const draggableElements = getDraggableElements();
const draggedFolder = draggableElements[2]!;
draggedFolder.dispatchEvent(new DragEvent(
'dragstart', {bubbles: true, composed: true, clientX: 0, clientY: 0}));
// Drag over self.
let dragOverRect = draggedFolder.getBoundingClientRect();
draggedFolder.dispatchEvent(new DragEvent('dragover', {
bubbles: true,
composed: true,
clientX: dragOverRect.left,
clientY: dragOverRect.top,
}));
assertEquals(null, draggedFolder.getAttribute(DROP_POSITION_ATTR));
const dragOverChild = draggableElements[3]!;
dragOverRect = dragOverChild.getBoundingClientRect();
dragOverChild.dispatchEvent(new DragEvent('dragover', {
bubbles: true,
composed: true,
clientX: dragOverRect.left,
clientY: dragOverRect.top,
}));
assertEquals(null, dragOverChild.getAttribute(DROP_POSITION_ATTR));
});
test('DropsIntoFolder', () => {
let calledId, calledIndex;
chrome.bookmarkManagerPrivate.startDrag = () => {};
chrome.bookmarkManagerPrivate.drop = (id, index) => {
calledId = id;
calledIndex = index;
};
const draggableElements = getDraggableElements();
const draggedBookmark = draggableElements[0]!;
draggedBookmark.dispatchEvent(new DragEvent(
'dragstart', {bubbles: true, composed: true, clientX: 0, clientY: 0}));
const dropFolder = draggableElements[2]!;
const dragOverRect = dropFolder.getBoundingClientRect();
dropFolder.dispatchEvent(new DragEvent('dragover', {
bubbles: true,
composed: true,
clientX: dragOverRect.left,
clientY: dragOverRect.top + (dragOverRect.height * .5),
}));
dropFolder.dispatchEvent(
new DragEvent('drop', {bubbles: true, composed: true}));
assertEquals('4', calledId);
assertEquals(undefined, calledIndex);
});
test('DropsBookmarksToReorder', () => {
let calledId, calledIndex;
chrome.bookmarkManagerPrivate.startDrag = () => {};
chrome.bookmarkManagerPrivate.drop = (id, index) => {
calledId = id;
calledIndex = index;
};
const draggableElements = getDraggableElements();
const draggedBookmark = draggableElements[2]!;
draggedBookmark.dispatchEvent(new DragEvent(
'dragstart', {bubbles: true, composed: true, clientX: 0, clientY: 0}));
const dragAboveBookmark = draggableElements[0]!;
const dragAboveRect = dragAboveBookmark.getBoundingClientRect();
dragAboveBookmark.dispatchEvent(new DragEvent('dragover', {
bubbles: true,
composed: true,
clientX: dragAboveRect.left,
clientY: dragAboveRect.top + (dragAboveRect.height * .1),
}));
dragAboveBookmark.dispatchEvent(
new DragEvent('drop', {bubbles: true, composed: true}));
assertEquals('1', calledId);
assertEquals(0, calledIndex);
draggedBookmark.dispatchEvent(new DragEvent(
'dragstart', {bubbles: true, composed: true, clientX: 0, clientY: 0}));
const dragBelowBookmark = draggableElements[1]!;
const dragBelowRect = dragBelowBookmark.getBoundingClientRect();
dragBelowBookmark.dispatchEvent(new DragEvent('dragover', {
bubbles: true,
composed: true,
clientX: dragBelowRect.left,
clientY: dragBelowRect.top + (dragBelowRect.height * .9),
}));
dragBelowBookmark.dispatchEvent(
new DragEvent('drop', {bubbles: true, composed: true}));
assertEquals('1', calledId);
assertEquals(2, calledIndex);
});
test('DragOverFolderAutoOpens', async () => {
overrideFolderOpenerTimeoutDelay(0);
chrome.bookmarkManagerPrivate.startDrag = () => {};
const draggableElements = getDraggableElements();
const draggedBookmark = draggableElements[0]!;
draggedBookmark.dispatchEvent(new DragEvent(
'dragstart', {bubbles: true, composed: true, clientX: 0, clientY: 0}));
const folderNode = folders[0]!.children![3]!;
const dragOverFolder = draggableElements[4]!;
const dragOverRect = dragOverFolder.getBoundingClientRect();
dragOverFolder.dispatchEvent(new DragEvent('dragover', {
bubbles: true,
composed: true,
clientX: dragOverRect.left,
clientY: dragOverRect.top + (dragOverRect.height * .5),
}));
assertFalse(delegate.isFolderOpen(folderNode));
// Drag over a new bookmark before the timeout runs out to ensure the
// timeout is canceled.
const newDragOverBookmark = draggableElements[3]!;
const newDragOverBookmarkRect = newDragOverBookmark.getBoundingClientRect();
newDragOverBookmark.dispatchEvent(new DragEvent('dragover', {
bubbles: true,
composed: true,
clientX: newDragOverBookmarkRect.left,
clientY:
newDragOverBookmarkRect.top + (newDragOverBookmarkRect.height * .5),
}));
await new Promise(resolve => setTimeout(resolve, 0));
assertFalse(delegate.isFolderOpen(folderNode));
// Drag back into closed folder and wait for the timeout to resolve.
dragOverFolder.dispatchEvent(new DragEvent('dragover', {
bubbles: true,
composed: true,
clientX: dragOverRect.left,
clientY: dragOverRect.top + (dragOverRect.height * .5),
}));
await new Promise(resolve => setTimeout(resolve, 0));
assertTrue(delegate.isFolderOpen(folderNode));
});
}); | the_stack |
import { Utils } from '../src/utils';
describe('gridstack utils', function() {
'use strict';
describe('setup of utils', function() {
it('should set gridstack Utils.', function() {
let utils = Utils;
expect(utils).not.toBeNull();
expect(typeof utils).toBe('function');
});
});
describe('test toBool', function() {
it('should return booleans.', function() {
expect(Utils.toBool(true)).toEqual(true);
expect(Utils.toBool(false)).toEqual(false);
});
it('should work with integer.', function() {
expect(Utils.toBool(1)).toEqual(true);
expect(Utils.toBool(0)).toEqual(false);
});
it('should work with Strings.', function() {
expect(Utils.toBool('')).toEqual(false);
expect(Utils.toBool('0')).toEqual(false);
expect(Utils.toBool('no')).toEqual(false);
expect(Utils.toBool('false')).toEqual(false);
expect(Utils.toBool('yes')).toEqual(true);
expect(Utils.toBool('yadda')).toEqual(true);
});
});
describe('test isIntercepted', function() {
let src = {x: 3, y: 2, w: 3, h: 2};
it('should intercept.', function() {
expect(Utils.isIntercepted(src, {x: 0, y: 0, w: 4, h: 3})).toEqual(true);
expect(Utils.isIntercepted(src, {x: 0, y: 0, w: 40, h: 30})).toEqual(true);
expect(Utils.isIntercepted(src, {x: 3, y: 2, w: 3, h: 2})).toEqual(true);
expect(Utils.isIntercepted(src, {x: 5, y: 3, w: 3, h: 2})).toEqual(true);
});
it('shouldn\'t intercept.', function() {
expect(Utils.isIntercepted(src, {x: 0, y: 0, w: 3, h: 2})).toEqual(false);
expect(Utils.isIntercepted(src, {x: 0, y: 0, w: 13, h: 2})).toEqual(false);
expect(Utils.isIntercepted(src, {x: 1, y: 4, w: 13, h: 2})).toEqual(false);
expect(Utils.isIntercepted(src, {x: 0, y: 3, w: 3, h: 2})).toEqual(false);
expect(Utils.isIntercepted(src, {x: 6, y: 3, w: 3, h: 2})).toEqual(false);
});
});
describe('test createStylesheet/removeStylesheet', function() {
it('should create/remove style DOM', function() {
let _id = 'test-123';
Utils.createStylesheet(_id);
let style = document.querySelector('STYLE[gs-style-id=' + _id + ']');
expect(style).not.toBe(null);
// expect(style.prop('tagName')).toEqual('STYLE');
Utils.removeStylesheet(_id)
style = document.querySelector('STYLE[gs-style-id=' + _id + ']');
expect(style).toBe(null);
});
});
describe('test parseHeight', function() {
it('should parse height value', function() {
expect(Utils.parseHeight(12)).toEqual(jasmine.objectContaining({h: 12, unit: 'px'}));
expect(Utils.parseHeight('12px')).toEqual(jasmine.objectContaining({h: 12, unit: 'px'}));
expect(Utils.parseHeight('12.3px')).toEqual(jasmine.objectContaining({h: 12.3, unit: 'px'}));
expect(Utils.parseHeight('12.3em')).toEqual(jasmine.objectContaining({h: 12.3, unit: 'em'}));
expect(Utils.parseHeight('12.3rem')).toEqual(jasmine.objectContaining({h: 12.3, unit: 'rem'}));
expect(Utils.parseHeight('12.3vh')).toEqual(jasmine.objectContaining({h: 12.3, unit: 'vh'}));
expect(Utils.parseHeight('12.3vw')).toEqual(jasmine.objectContaining({h: 12.3, unit: 'vw'}));
expect(Utils.parseHeight('12.3%')).toEqual(jasmine.objectContaining({h: 12.3, unit: '%'}));
expect(Utils.parseHeight('12.5')).toEqual(jasmine.objectContaining({h: 12.5, unit: 'px'}));
expect(function() { Utils.parseHeight('12.5 df'); }).toThrowError('Invalid height');
});
it('should parse negative height value', function() {
expect(Utils.parseHeight(-12)).toEqual(jasmine.objectContaining({h: -12, unit: 'px'}));
expect(Utils.parseHeight('-12px')).toEqual(jasmine.objectContaining({h: -12, unit: 'px'}));
expect(Utils.parseHeight('-12.3px')).toEqual(jasmine.objectContaining({h: -12.3, unit: 'px'}));
expect(Utils.parseHeight('-12.3em')).toEqual(jasmine.objectContaining({h: -12.3, unit: 'em'}));
expect(Utils.parseHeight('-12.3rem')).toEqual(jasmine.objectContaining({h: -12.3, unit: 'rem'}));
expect(Utils.parseHeight('-12.3vh')).toEqual(jasmine.objectContaining({h: -12.3, unit: 'vh'}));
expect(Utils.parseHeight('-12.3vw')).toEqual(jasmine.objectContaining({h: -12.3, unit: 'vw'}));
expect(Utils.parseHeight('-12.3%')).toEqual(jasmine.objectContaining({h: -12.3, unit: '%'}));
expect(Utils.parseHeight('-12.5')).toEqual(jasmine.objectContaining({h: -12.5, unit: 'px'}));
expect(function() { Utils.parseHeight('-12.5 df'); }).toThrowError('Invalid height');
});
});
describe('test defaults', function() {
it('should assign missing field or undefined', function() {
let src: any = {};
expect(src).toEqual({});
expect(Utils.defaults(src, {x: 1, y: 2})).toEqual({x: 1, y: 2});
expect(Utils.defaults(src, {x: 10})).toEqual({x: 1, y: 2});
src.w = undefined;
expect(src).toEqual({x: 1, y: 2, w: undefined});
expect(Utils.defaults(src, {x: 10, w: 3})).toEqual({x: 1, y: 2, w: 3});
expect(Utils.defaults(src, {h: undefined})).toEqual({x: 1, y: 2, w: 3, h: undefined});
src = {x: 1, y: 2, sub: {foo: 1, two: 2}};
expect(src).toEqual({x: 1, y: 2, sub: {foo: 1, two: 2}});
expect(Utils.defaults(src, {x: 10, w: 3})).toEqual({x: 1, y: 2, w: 3, sub: {foo: 1, two: 2}});
expect(Utils.defaults(src, {sub: {three: 3}})).toEqual({x: 1, y: 2, w: 3, sub: {foo: 1, two: 2, three: 3}});
});
});
describe('removePositioningStyles', function() {
it('should remove styles', function() {
let doc = document.implementation.createHTMLDocument();
doc.body.innerHTML = '<div style="position: absolute; left: 1; top: 2; w: 3; h: 4"></div>';
let el = doc.body.children[0] as HTMLElement;
expect(el.style.position).toEqual('absolute');
// expect(el.style.left).toEqual('1'); // not working!
Utils.removePositioningStyles(el);
expect(el.style.position).toEqual('');
// bogus test
expect(Utils.getScrollElement(el)).not.toBe(null);
// bogus test
Utils.updateScrollPosition(el, {top: 20}, 10);
});
});
describe('clone', () => {
const a: any = {first: 1, second: 'text'};
const b: any = {first: 1, second: {third: 3}};
const c: any = {first: 1, second: [1, 2, 3], third: { fourth: {fifth: 5}}};
it('Should have the same values', () => {
const z = Utils.clone(a);
expect(z).toEqual({first: 1, second: 'text'});
});
it('Should have 2 in first key, and original unchanged', () => {
const z = Utils.clone(a);
z.first = 2;
expect(a).toEqual({first: 1, second: 'text'});
expect(z).toEqual({first: 2, second: 'text'});
});
it('Should have new string in second key, and original unchanged', () => {
const z = Utils.clone(a);
z.second = 2;
expect(a).toEqual({first: 1, second: 'text'});
expect(z).toEqual({first: 1, second: 2});
});
it('new string in both cases - use cloneDeep instead', () => {
const z = Utils.clone(b);
z.second.third = 'share';
expect(b).toEqual({first: 1, second: {third: 'share'}});
expect(z).toEqual({first: 1, second: {third: 'share'}});
});
it('Array Should match', () => {
const z = Utils.clone(c);
expect(c).toEqual({first: 1, second: [1, 2, 3], third: { fourth: {fifth: 5}}});
expect(z).toEqual({first: 1, second: [1, 2, 3], third: { fourth: {fifth: 5}}});
});
it('Array[0] changed in both cases - use cloneDeep instead', () => {
const z = Utils.clone(c);
z.second[0] = 0;
expect(c).toEqual({first: 1, second: [0, 2, 3], third: { fourth: {fifth: 5}}});
expect(z).toEqual({first: 1, second: [0, 2, 3], third: { fourth: {fifth: 5}}});
});
it('fifth changed in both cases - use cloneDeep instead', () => {
const z = Utils.clone(c);
z.third.fourth.fifth = 'share';
expect(c).toEqual({first: 1, second: [0, 2, 3], third: { fourth: {fifth: 'share'}}});
expect(z).toEqual({first: 1, second: [0, 2, 3], third: { fourth: {fifth: 'share'}}});
});
});
describe('cloneDeep', () => {
// reset our test cases
const a: any = {first: 1, second: 'text'};
const b: any = {first: 1, second: {third: 3}};
const c: any = {first: 1, second: [1, 2, 3], third: { fourth: {fifth: 5}}};
const d: any = {first: [1, [2, 3], ['four', 'five', 'six']]};
const e: any = {first: 1, __skip: {second: 2}};
const f: any = {first: 1, _dontskip: {second: 2}};
it('Should have the same values', () => {
const z = Utils.cloneDeep(a);
expect(z).toEqual({first: 1, second: 'text'});
});
it('Should have 2 in first key, and original unchanged', () => {
const z = Utils.cloneDeep(a);
z.first = 2;
expect(a).toEqual({first: 1, second: 'text'});
expect(z).toEqual({first: 2, second: 'text'});
});
it('Should have new string in second key, and original unchanged', () => {
const z = Utils.cloneDeep(a);
z.second = 2;
expect(a).toEqual({first: 1, second: 'text'});
expect(z).toEqual({first: 1, second: 2});
});
it('Should have new string nested object, and original unchanged', () => {
const z = Utils.cloneDeep(b);
z.second.third = 'diff';
expect(b).toEqual({first: 1, second: {third: 3}});
expect(z).toEqual({first: 1, second: {third: 'diff'}});
});
it('Array Should match', () => {
const z = Utils.cloneDeep(c);
expect(c).toEqual({first: 1, second: [1, 2, 3], third: { fourth: {fifth: 5}}});
expect(z).toEqual({first: 1, second: [1, 2, 3], third: { fourth: {fifth: 5}}});
});
it('Array[0] changed in z only', () => {
const z = Utils.cloneDeep(c);
z.second[0] = 0;
expect(c).toEqual({first: 1, second: [1, 2, 3], third: { fourth: {fifth: 5}}});
expect(z).toEqual({first: 1, second: [0, 2, 3], third: { fourth: {fifth: 5}}});
});
it('nested firth element changed only in z', () => {
const z = Utils.cloneDeep(c);
z.third.fourth.fifth = 'diff';
expect(c).toEqual({first: 1, second: [1, 2, 3], third: { fourth: {fifth: 5}}});
expect(z).toEqual({first: 1, second: [1, 2, 3], third: { fourth: {fifth: 'diff'}}});
});
it('nested array only has one item changed', () => {
const z = Utils.cloneDeep(d);
z.first[1] = 'two';
z.first[2][2] = 6;
expect(d).toEqual({first: [1, [2, 3], ['four', 'five', 'six']]});
expect(z).toEqual({first: [1, 'two', ['four', 'five', 6]]});
});
it('skip __ items so it mods both instance', () => {
const z = Utils.cloneDeep(e);
z.__skip.second = 'two';
expect(e).toEqual({first: 1, __skip: {second: 'two'}}); // TODO support clone deep of function workaround
expect(z).toEqual({first: 1, __skip: {second: 'two'}});
});
it('correctly copy _ item', () => {
const z = Utils.cloneDeep(f);
z._dontskip.second = 'two';
expect(f).toEqual({first: 1, _dontskip: {second: 2}});
expect(z).toEqual({first: 1, _dontskip: {second: 'two'}});
});
});
}); | the_stack |
import _ = require('lodash');
import RX = require('reactxp');
import * as CommonStyles from '../CommonStyles';
import { AutoExecutableTest, TestResult, TestType } from '../Test';
const _styles = {
container: RX.Styles.createViewStyle({
flex: 1,
alignSelf: 'stretch',
flexDirection: 'column',
alignItems: 'flex-start'
}),
explainTextContainer: RX.Styles.createViewStyle({
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
margin: 12
}),
button: RX.Styles.createButtonStyle({
marginLeft: 20,
paddingHorizontal: 8,
paddingVertical: 4,
backgroundColor: '#eee',
borderWidth: 1,
borderColor: '#999',
borderRadius: 8
}),
buttonText: RX.Styles.createTextStyle({
fontSize: CommonStyles.generalFontSize
}),
explainText: RX.Styles.createTextStyle({
flex: -1,
fontSize: CommonStyles.generalFontSize,
color: CommonStyles.explainTextColor
}),
animationCanvas: RX.Styles.createViewStyle({
alignSelf: 'stretch',
flexDirection: 'row',
height: 120,
margin: 12,
backgroundColor: '#eee',
alignItems: 'center',
justifyContent: 'center'
}),
animatedImage: RX.Styles.createImageStyle({
height: 100,
width: 100
}),
animatedViewTest2: RX.Styles.createViewStyle({
height: 40,
width: 40,
backgroundColor: 'red'
}),
animatedText: RX.Styles.createTextStyle({
fontSize: 24,
fontWeight: 'bold',
fontStyle: 'italic',
color: 'blue'
}),
animatedViewTest4: RX.Styles.createViewStyle({
height: 40,
width: 40,
borderRadius: 20,
backgroundColor: 'green'
}),
limitBox: RX.Styles.createViewStyle({
width: 1,
height: 40,
backgroundColor: 'black'
})
};
const _test1Radius = 40;
const _test2Duration = 500;
const _test4Duration = 1000;
interface AnimationViewState {
isAutoRunning?: boolean;
isRunningTest1?: boolean;
isRunningTest2?: boolean;
isRunningTest3?: boolean;
isRunningTest4?: boolean;
}
const _testValue1 = 'A long test value for the text input box';
class AnimationView extends RX.Component<RX.CommonProps, AnimationViewState> {
private _isMounted = false;
private _testResult: TestResult | undefined;
private _testCompletion: ((result: TestResult) => void) | undefined;
private _nextTestStage = 0;
// Test 1 animation variables
private _test1Angle = 0;
private _test1OffsetH = new RX.Animated.Value(_test1Radius);
private _test1OffsetV = new RX.Animated.Value(0);
private _test1Animation = RX.Styles.createAnimatedImageStyle({
transform: [{
translateX: this._test1OffsetH
}, {
translateY: this._test1OffsetV
}]
});
// Test 2 animation variables
private _test2OffsetH = new RX.Animated.Value(-100);
private _test2Color = new RX.Animated.Value(0);
private _test2Animation = RX.Styles.createAnimatedViewStyle({
transform: [{
translateX: this._test2OffsetH
}],
backgroundColor: RX.Animated.interpolate(
this._test2Color, [0, 0.5, 1], ['red', 'blue', 'green'])
});
// Test 3 animation variables
private _test3Angle = new RX.Animated.Value(0);
private _test3Animation = RX.Styles.createAnimatedTextStyle({
transform: [{
rotate: RX.Animated.interpolate(this._test3Angle, [0, 1], ['0deg', '360deg'])
}, {
rotateZ: RX.Animated.interpolate(this._test3Angle, [0, 1], ['0deg', '90deg'])
}]
});
// Test 4 animation variables
private _test4OffsetH = new RX.Animated.Value(-100);
private _test4Animation = RX.Styles.createAnimatedViewStyle({
transform: [{
translateX: this._test4OffsetH
}]
});
constructor(props: RX.CommonProps) {
super(props);
this.state = {
isAutoRunning: false,
isRunningTest1: false,
isRunningTest2: false,
isRunningTest3: false,
isRunningTest4: false
};
}
componentDidMount() {
this._isMounted = true;
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
return (
<RX.View style={ _styles.container}>
<RX.View style={ _styles.explainTextContainer } key={ 'explanation1' }>
<RX.Text style={ _styles.explainText }>
{ 'A simple animation driven by JavaScript code.' }
</RX.Text>
<RX.Button
style={ _styles.button }
onPress={ this._runTest1 }
disabled={ this.state.isAutoRunning || this.state.isRunningTest1 }
>
<RX.Text style={ _styles.buttonText }>
{ 'Animate' }
</RX.Text>
</RX.Button>
</RX.View>
<RX.View style={ _styles.animationCanvas }>
<RX.Animated.Image
source={ 'https://microsoft.github.io/reactxp/img/tests/bulb.jpg' }
resizeMode={ 'contain' }
style={ [_styles.animatedImage, this._test1Animation] }
/>
</RX.View>
<RX.View style={ _styles.explainTextContainer } key={ 'explanation2' }>
<RX.Text style={ _styles.explainText }>
{ 'Animation of translation and color using parallel and serial animations.' }
</RX.Text>
<RX.Button
style={ _styles.button }
onPress={ this._runTest2 }
disabled={ this.state.isAutoRunning || this.state.isRunningTest2 }
>
<RX.Text style={ _styles.buttonText }>
{ 'Animate' }
</RX.Text>
</RX.Button>
</RX.View>
<RX.View style={ _styles.animationCanvas }>
<RX.Animated.View style={ [_styles.animatedViewTest2, this._test2Animation] }/>
</RX.View>
<RX.View style={ _styles.explainTextContainer } key={ 'explanation3' }>
<RX.Text style={ _styles.explainText }>
{ 'Rotation animation that uses 250ms delay and loop.' }
</RX.Text>
<RX.Button
style={ _styles.button }
onPress={ this._runTest3 }
disabled={ this.state.isAutoRunning || this.state.isRunningTest3 }
>
<RX.Text style={ _styles.buttonText }>
{ 'Animate' }
</RX.Text>
</RX.Button>
</RX.View>
<RX.View style={ _styles.animationCanvas }>
<RX.Animated.Text
style={ [_styles.animatedText, this._test3Animation] }
>
{ 'Cool Rotation!' }
</RX.Animated.Text>
</RX.View>
<RX.View style={ _styles.explainTextContainer } key={ 'explanation4' }>
<RX.Text style={ _styles.explainText }>
{ 'Animation that is interrupted. It should move halfway to the black line and back.' }
</RX.Text>
<RX.Button
style={ _styles.button }
onPress={ this._runTest4 }
disabled={ this.state.isAutoRunning || this.state.isRunningTest4 }
>
<RX.Text style={ _styles.buttonText }>
{ 'Animate' }
</RX.Text>
</RX.Button>
</RX.View>
<RX.View style={ _styles.animationCanvas }>
<RX.Animated.View style={ [_styles.animatedViewTest4, this._test4Animation] }/>
<RX.View style={ _styles.limitBox }/>
</RX.View>
</RX.View>
);
}
private _executeNextStage() {
// If we're not running in "auto" mode, don't run the next stage.
if (!this.state.isAutoRunning) {
return;
}
const testStages: (() => void)[] = [() => {
this._runTest1();
}, () => {
this._runTest2();
}, () => {
this._runTest3();
}, () => {
this._runTest4();
}];
// Are we done?
if (this._nextTestStage! >= testStages.length) {
this._testCompletion!(this._testResult!);
this._testCompletion = undefined;
this._testResult = undefined;
if (this._isMounted) {
this.setState({ isAutoRunning: false });
}
} else {
// Run the next stage after a brief delay.
_.delay(() => {
testStages[this._nextTestStage]();
this._nextTestStage++;
}, 200);
}
}
private _runTest1 = () => {
this._test1Angle = 0;
this.setState({ isRunningTest1: true });
let setNextValues = () => {
// Are we done?
if (this._test1Angle >= 2 * Math.PI) {
if (this._isMounted) {
this.setState({ isRunningTest1: false });
}
this._executeNextStage();
return;
}
// Update the values.
this._test1OffsetH.setValue(_test1Radius * Math.cos(this._test1Angle));
this._test1OffsetV.setValue(_test1Radius * Math.sin(this._test1Angle));
this._test1Angle += 2 * Math.PI / 36;
_.delay(() => {
setNextValues();
}, 1000 / 60);
};
setNextValues();
}
private _runTest2 = () => {
this.setState({ isRunningTest2: true });
let animation = RX.Animated.sequence([
RX.Animated.parallel([
RX.Animated.timing(this._test2Color, {
toValue: 1,
duration: _test2Duration,
easing: RX.Animated.Easing.InOut()
}),
RX.Animated.timing(this._test2OffsetH, {
toValue: 100,
duration: _test2Duration,
easing: RX.Animated.Easing.Linear()
})
]),
RX.Animated.parallel([
RX.Animated.timing(this._test2Color, {
toValue: 0,
duration: _test2Duration,
easing: RX.Animated.Easing.InOut()
}),
RX.Animated.timing(this._test2OffsetH, {
toValue: -100,
duration: _test2Duration,
easing: RX.Animated.Easing.Linear()
})
])
]);
animation.start(() => {
if (this._isMounted) {
this.setState({ isRunningTest2: false });
}
this._executeNextStage();
});
}
private _runTest3 = () => {
this.setState({ isRunningTest3: true });
let animation = RX.Animated.timing(this._test3Angle, {
toValue: 1,
duration: 250,
easing: RX.Animated.Easing.Linear(),
delay: 250,
loop: {
restartFrom: 0
}
});
animation.start();
// Allow it to run for a while.
_.delay(() => {
animation.stop();
this._test3Angle.setValue(0);
if (this._isMounted) {
this.setState({ isRunningTest3: false });
}
this._executeNextStage();
}, 2000);
}
private _runTest4 = () => {
this.setState({ isRunningTest4: true });
let animation = RX.Animated.timing(this._test4OffsetH, {
toValue: 0,
duration: _test4Duration,
easing: RX.Animated.Easing.Linear()
});
let isFinished: boolean|undefined;
let wasCompletionCalled = false;
animation.start(completeInfo => {
if (isFinished !== undefined) {
this._testResult!.errors.push('Completion callback "finished" called multiple times');
}
isFinished = completeInfo.finished;
wasCompletionCalled = true;
});
// Set a timer for half-way through the animation. This will
// stop the animation and start it again in the opposite direction.
_.delay(() => {
if (this._isMounted) {
animation.stop();
// Make sure the completion was executed and the "finished" parameter was false.
if (!wasCompletionCalled) {
this._testResult!.errors.push('Completion callback was not called when animation was stopped');
} else if (isFinished === undefined || isFinished !== false) {
this._testResult!.errors.push('Completion callback "finished" parameter was not false as expected');
}
RX.Animated.timing(this._test4OffsetH, {
toValue: -100,
duration: _test4Duration / 2,
easing: RX.Animated.Easing.Linear()
}).start(completeInfo => {
if (!completeInfo.finished) {
this._testResult!.errors.push('Completion callback "finished" parameter was not true as expected');
}
if (this._isMounted) {
this.setState({ isRunningTest4: false });
}
this._executeNextStage();
});
}
}, _test4Duration / 2);
}
execute(complete: (result: TestResult) => void): void {
this._nextTestStage = 0;
this._testResult = new TestResult();
this._testCompletion = complete;
this.setState({ isAutoRunning: true });
// Kick off the first stage. Defer to make sure
// setState above has taken effect.
_.defer(() => {
this._executeNextStage();
});
}
}
class AnimationTest implements AutoExecutableTest {
getPath(): string {
return 'APIs/Animation';
}
getTestType(): TestType {
return TestType.AutoExecutable;
}
render(onMount: (component: any) => void): RX.Types.ReactNode {
return (
<AnimationView ref={ onMount }/>
);
}
execute(component: any, complete: (result: TestResult) => void): void {
let animationView = component as AnimationView;
animationView.execute(complete);
}
}
export default new AnimationTest(); | the_stack |
import { EventEmitter } from '../deps/@jspm/core@1.1.0/nodelibs/events.js';
import { Migrator } from '../migrate/Migrator.js';
import Seeder from '../seed/Seeder.js';
import FunctionHelper from '../functionhelper.js';
import QueryInterface from '../query/methods.js';
import _ from '../deps/lodash@4.17.15/index.js';
const merge = _.merge;
import batchInsert from './batchInsert.js';
// Javascript does not officially support "callable objects". Instead,
// you must create a regular Function and inject properties/methods
// into it. In other words: you can't leverage Prototype Inheritance
// to share the property/method definitions.
//
// To work around this, we're creating an Object Property Definition.
// This allow us to quickly inject everything into the `knex` function
// via the `Object.defineProperties(..)` function. More importantly,
// it allows the same definitions to be shared across `knex` instances.
const KNEX_PROPERTY_DEFINITIONS = {
client: {
get() {
return this.context.client;
},
set(client) {
this.context.client = client;
},
configurable: true,
},
userParams: {
get() {
return this.context.userParams;
},
set(userParams) {
this.context.userParams = userParams;
},
configurable: true,
},
schema: {
get() {
return this.client.schemaBuilder();
},
configurable: true,
},
migrate: {
get() {
return new Migrator(this);
},
configurable: true,
},
seed: {
get() {
return new Seeder(this);
},
configurable: true,
},
fn: {
get() {
return new FunctionHelper(this.client);
},
configurable: true,
},
};
// `knex` instances serve as proxies around `context` objects. So, calling
// any of these methods on the `knex` instance will forward the call to
// the `knex.context` object. This ensures that `this` will correctly refer
// to `context` within each of these methods.
const CONTEXT_METHODS = [
'raw',
'batchInsert',
'transaction',
'transactionProvider',
'initialize',
'destroy',
'ref',
'withUserParams',
'queryBuilder',
'disableProcessing',
'enableProcessing',
];
for (const m of CONTEXT_METHODS) {
KNEX_PROPERTY_DEFINITIONS[m] = {
value: function (...args) {
return this.context[m](...args);
},
configurable: true,
};
}
function makeKnex(client) {
// The object we're potentially using to kick off an initial chain.
function knex(tableName, options) {
return createQueryBuilder(knex.context, tableName, options);
}
redefineProperties(knex, client);
return knex;
}
function initContext(knexFn) {
const knexContext = knexFn.context || {};
Object.assign(knexContext, {
queryBuilder() {
return this.client.queryBuilder();
},
raw() {
return this.client.raw.apply(this.client, arguments);
},
batchInsert(table, batch, chunkSize = 1000) {
return batchInsert(this, table, batch, chunkSize);
},
// Creates a new transaction.
// If container is provided, returns a promise for when the transaction is resolved.
// If container is not provided, returns a promise with a transaction that is resolved
// when transaction is ready to be used.
transaction(container, _config) {
const config = Object.assign({}, _config);
config.userParams = this.userParams || {};
if (config.doNotRejectOnRollback === undefined) {
// Backwards-compatibility: default value changes depending upon
// whether or not a `container` was provided.
config.doNotRejectOnRollback = !container;
}
return this._transaction(container, config);
},
// Internal method that actually establishes the Transaction. It makes no assumptions
// about the `config` or `outerTx`, and expects the caller to handle these details.
_transaction(container, config, outerTx = null) {
if (container) {
const trx = this.client.transaction(container, config, outerTx);
return trx;
} else {
return new Promise((resolve, reject) => {
const trx = this.client.transaction(resolve, config, outerTx);
trx.catch(reject);
});
}
},
transactionProvider(config) {
let trx;
return () => {
if (!trx) {
trx = this.transaction(undefined, config);
}
return trx;
};
},
// Typically never needed, initializes the pool for a knex client.
initialize(config) {
return this.client.initializePool(config);
},
// Convenience method for tearing down the pool.
destroy(callback) {
return this.client.destroy(callback);
},
ref(ref) {
return this.client.ref(ref);
},
// Do not document this as public API until naming and API is improved for general consumption
// This method exists to disable processing of internal queries in migrations
disableProcessing() {
if (this.userParams.isProcessingDisabled) {
return;
}
this.userParams.wrapIdentifier = this.client.config.wrapIdentifier;
this.userParams.postProcessResponse = this.client.config.postProcessResponse;
this.client.config.wrapIdentifier = null;
this.client.config.postProcessResponse = null;
this.userParams.isProcessingDisabled = true;
},
// Do not document this as public API until naming and API is improved for general consumption
// This method exists to enable execution of non-internal queries with consistent identifier naming in migrations
enableProcessing() {
if (!this.userParams.isProcessingDisabled) {
return;
}
this.client.config.wrapIdentifier = this.userParams.wrapIdentifier;
this.client.config.postProcessResponse = this.userParams.postProcessResponse;
this.userParams.isProcessingDisabled = false;
},
withUserParams(params) {
const knexClone = shallowCloneFunction(knexFn); // We need to include getters in our clone
if (this.client) {
knexClone.client = Object.create(this.client.constructor.prototype); // Clone client to avoid leaking listeners that are set on it
merge(knexClone.client, this.client);
knexClone.client.config = Object.assign({}, this.client.config); // Clone client config to make sure they can be modified independently
}
redefineProperties(knexClone, knexClone.client);
_copyEventListeners('query', knexFn, knexClone);
_copyEventListeners('query-error', knexFn, knexClone);
_copyEventListeners('query-response', knexFn, knexClone);
_copyEventListeners('start', knexFn, knexClone);
knexClone.userParams = params;
return knexClone;
},
});
if (!knexFn.context) {
knexFn.context = knexContext;
}
}
function _copyEventListeners(eventName, sourceKnex, targetKnex) {
const listeners = sourceKnex.listeners(eventName);
listeners.forEach((listener) => {
targetKnex.on(eventName, listener);
});
}
function redefineProperties(knex, client) {
// Allow chaining methods from the root object, before
// any other information is specified.
//
// TODO: `QueryBuilder.extend(..)` allows new QueryBuilder
// methods to be introduced via external components.
// As a side-effect, it also pushes the new method names
// into the `QueryInterface` array.
//
// The Problem: due to the way the code is currently
// structured, these new methods cannot be retroactively
// injected into existing `knex` instances! As a result,
// some `knex` instances will support the methods, and
// others will not.
//
// We should revisit this once we figure out the desired
// behavior / usage. For instance: do we really want to
// allow external components to directly manipulate `knex`
// data structures? Or, should we come up w/ a different
// approach that avoids side-effects / mutation?
//
// (FYI: I noticed this issue because I attempted to integrate
// this logic directly into the `KNEX_PROPERTY_DEFINITIONS`
// construction. However, `KNEX_PROPERTY_DEFINITIONS` is
// constructed before any `knex` instances are created.
// As a result, the method extensions were missing from all
// `knex` instances.)
QueryInterface.forEach(function (method) {
knex[method] = function () {
const builder = this.queryBuilder();
return builder[method].apply(builder, arguments);
};
});
Object.defineProperties(knex, KNEX_PROPERTY_DEFINITIONS);
initContext(knex);
knex.client = client;
// TODO: It looks like this field is never actually used.
// It should probably be removed in a future PR.
knex.client.makeKnex = makeKnex;
knex.userParams = {};
// Hook up the "knex" object as an EventEmitter.
const ee = new EventEmitter();
for (const key in ee) {
knex[key] = ee[key];
}
// Unfortunately, something seems to be broken in Node 6 and removing events from a clone also mutates original Knex,
// which is highly undesirable
if (knex._internalListeners) {
knex._internalListeners.forEach(({ eventName, listener }) => {
knex.client.removeListener(eventName, listener); // Remove duplicates for copies
});
}
knex._internalListeners = [];
// Passthrough all "start" and "query" events to the knex object.
_addInternalListener(knex, 'start', (obj) => {
knex.emit('start', obj);
});
_addInternalListener(knex, 'query', (obj) => {
knex.emit('query', obj);
});
_addInternalListener(knex, 'query-error', (err, obj) => {
knex.emit('query-error', err, obj);
});
_addInternalListener(knex, 'query-response', (response, obj, builder) => {
knex.emit('query-response', response, obj, builder);
});
}
function _addInternalListener(knex, eventName, listener) {
knex.client.on(eventName, listener);
knex._internalListeners.push({
eventName,
listener,
});
}
function createQueryBuilder(knexContext, tableName, options) {
const qb = knexContext.queryBuilder();
if (!tableName)
knexContext.client.logger.warn(
'calling knex without a tableName is deprecated. Use knex.queryBuilder() instead.'
);
return tableName ? qb.table(tableName, options) : qb;
}
function shallowCloneFunction(originalFunction) {
const fnContext = Object.create(
Object.getPrototypeOf(originalFunction),
Object.getOwnPropertyDescriptors(originalFunction)
);
const knexContext = {};
const knexFnWrapper = (tableName, options) => {
return createQueryBuilder(knexContext, tableName, options);
};
const clonedFunction = knexFnWrapper.bind(fnContext);
Object.assign(clonedFunction, originalFunction);
clonedFunction.context = knexContext;
return clonedFunction;
}
export default makeKnex; | the_stack |
import { Map, LeafletMouseEvent, geoJSON } from "leaflet";
import {
Feature,
FeatureCollection,
LineString,
MultiLineString,
Position,
} from "geojson";
import {
BaseGlLayer,
ColorCallback,
IBaseGlLayerSettings,
} from "./base-gl-layer";
import { ICanvasOverlayDrawEvent } from "./canvas-overlay";
import * as color from "./color";
import { LineFeatureVertices } from "./line-feature-vertices";
import { latLngDistance, inBounds } from "./utils";
export type WeightCallback = (i: number, feature: any) => number;
export interface ILinesSettings extends IBaseGlLayerSettings {
data: FeatureCollection<LineString | MultiLineString>;
weight: WeightCallback | number;
sensitivity?: number;
sensitivityHover?: number;
eachVertex?: (vertices: LineFeatureVertices) => void;
}
const defaults: Partial<ILinesSettings> = {
data: {
type: "FeatureCollection",
features: [],
},
color: color.random,
className: "",
opacity: 0.5,
weight: 2,
sensitivity: 0.1,
sensitivityHover: 0.03,
shaderVariables: {
vertex: {
type: "FLOAT",
start: 0,
size: 2,
},
color: {
type: "FLOAT",
start: 2,
size: 4,
},
},
};
export class Lines extends BaseGlLayer<ILinesSettings> {
static defaults = defaults;
scale = Infinity;
bytes = 6;
allVertices: number[] = [];
allVerticesTyped: Float32Array = new Float32Array(0);
vertices: LineFeatureVertices[] = [];
aPointSize = -1;
settings: Partial<ILinesSettings>;
get weight(): WeightCallback | number {
if (!this.settings.weight) {
throw new Error("settings.weight not correctly defined");
}
return this.settings.weight;
}
constructor(settings: Partial<ILinesSettings>) {
super(settings);
this.settings = { ...Lines.defaults, ...settings };
if (!settings.data) {
throw new Error('"data" is missing');
}
this.active = true;
this.setup().render();
}
render(): this {
this.resetVertices();
const { canvas, gl, layer, mapMatrix } = this;
const vertexBuffer = this.getBuffer("vertex");
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
const size = this.allVerticesTyped.BYTES_PER_ELEMENT;
gl.bufferData(gl.ARRAY_BUFFER, this.allVerticesTyped, gl.STATIC_DRAW);
const vertexLocation = this.getAttributeLocation("vertex");
gl.vertexAttribPointer(
vertexLocation,
2,
gl.FLOAT,
false,
size * this.bytes,
0
);
gl.enableVertexAttribArray(vertexLocation);
// gl.disable(gl.DEPTH_TEST);
// ----------------------------
// look up the locations for the inputs to our shaders.
this.matrix = this.getUniformLocation("matrix");
this.aPointSize = this.getAttributeLocation("pointSize");
// Set the matrix to some that makes 1 unit 1 pixel.
mapMatrix.setSize(canvas.width, canvas.height);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.uniformMatrix4fv(this.matrix, false, mapMatrix.array);
this.attachShaderVariables(size);
layer.redraw();
return this;
}
resetVertices(): this {
const {
map,
opacity,
color,
weight,
latitudeKey,
longitudeKey,
data,
bytes,
settings,
} = this;
const { eachVertex } = settings;
const { features } = data;
const featureMax = features.length;
let feature: Feature<LineString | MultiLineString>;
let colorFn: ColorCallback | null = null;
let weightFn: WeightCallback | null = null;
let chosenColor: color.IColor;
let featureIndex = 0;
if (typeof color === "function") {
colorFn = color;
}
if (typeof weight === "function") {
weightFn = weight;
}
const project = map.project.bind(map);
// -- data
const vertices: LineFeatureVertices[] = [];
for (; featureIndex < featureMax; featureIndex++) {
feature = features[featureIndex];
// use colorFn function here if it exists
if (colorFn) {
chosenColor = colorFn(featureIndex, feature);
} else {
chosenColor = color as color.IColor;
}
const chosenWeight: number = weightFn
? weightFn(featureIndex, feature)
: (weight as number);
const featureVertices = new LineFeatureVertices({
project,
latitudeKey,
longitudeKey,
color: chosenColor,
weight: chosenWeight,
opacity,
});
featureVertices.fillFromCoordinates(feature.geometry.coordinates);
vertices.push(featureVertices);
if (eachVertex) {
eachVertex(featureVertices);
}
}
/*
Transforming lines according to the rule:
1. Take one line (single feature)
[[0,0],[1,1],[2,2]]
2. Split the line in segments, duplicating all coordinates except first and last one
[[0,0],[1,1],[2,2]] => [[0,0],[1,1],[1,1],[2,2]]
3. Do this for all lines and put all coordinates in array
*/
const size = vertices.length;
const allVertices = [];
for (let i = 0; i < size; i++) {
const vertexArray = vertices[i].array;
const length = vertexArray.length / bytes;
for (let j = 0; j < length; j++) {
const vertexIndex = j * bytes;
if (j !== 0 && j !== length - 1) {
allVertices.push(
vertexArray[vertexIndex],
vertexArray[vertexIndex + 1],
vertexArray[vertexIndex + 2],
vertexArray[vertexIndex + 3],
vertexArray[vertexIndex + 4],
vertexArray[vertexIndex + 5]
);
}
allVertices.push(
vertexArray[vertexIndex],
vertexArray[vertexIndex + 1],
vertexArray[vertexIndex + 2],
vertexArray[vertexIndex + 3],
vertexArray[vertexIndex + 4],
vertexArray[vertexIndex + 5]
);
}
}
this.vertices = vertices;
this.allVertices = allVertices;
this.allVerticesTyped = new Float32Array(allVertices);
return this;
}
drawOnCanvas(e: ICanvasOverlayDrawEvent): this {
if (!this.gl) return this;
const {
gl,
data,
canvas,
mapMatrix,
matrix,
allVertices,
vertices,
weight,
aPointSize,
bytes,
} = this;
const { scale, offset, zoom } = e;
this.scale = scale;
const pointSize = Math.max(zoom - 4.0, 4.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.viewport(0, 0, canvas.width, canvas.height);
gl.vertexAttrib1f(aPointSize, pointSize);
mapMatrix.setSize(canvas.width, canvas.height).scaleTo(scale);
if (zoom > 18) {
mapMatrix.translateTo(-offset.x, -offset.y);
// -- attach matrix value to 'mapMatrix' uniform in shader
gl.uniformMatrix4fv(matrix, false, mapMatrix.array);
gl.drawArrays(gl.LINES, 0, allVertices.length / bytes);
} else if (typeof weight === "number") {
// Now draw the lines several times, but like a brush, taking advantage of the half pixel line generally used by cards
for (let yOffset = -weight; yOffset <= weight; yOffset += 0.5) {
for (let xOffset = -weight; xOffset <= weight; xOffset += 0.5) {
// -- set base matrix to translate canvas pixel coordinates -> webgl coordinates
mapMatrix.translateTo(
-offset.x + xOffset / scale,
-offset.y + yOffset / scale
);
// -- attach matrix value to 'mapMatrix' uniform in shader
gl.uniformMatrix4fv(matrix, false, mapMatrix.array);
gl.drawArrays(gl.LINES, 0, allVertices.length / bytes);
}
}
} else if (typeof weight === "function") {
let allVertexCount = 0;
const { features } = data;
for (let i = 0; i < vertices.length; i++) {
const featureVertices = vertices[i];
const { vertexCount } = featureVertices;
const weightValue = weight(i, features[i]);
// Now draw the lines several times, but like a brush, taking advantage of the half pixel line generally used by cards
for (
let yOffset = -weightValue;
yOffset <= weightValue;
yOffset += 0.5
) {
for (
let xOffset = -weightValue;
xOffset <= weightValue;
xOffset += 0.5
) {
// -- set base matrix to translate canvas pixel coordinates -> webgl coordinates
mapMatrix.translateTo(
-offset.x + xOffset / scale,
-offset.y + yOffset / scale
);
// -- attach matrix value to 'mapMatrix' uniform in shader
gl.uniformMatrix4fv(this.matrix, false, mapMatrix.array);
gl.drawArrays(gl.LINES, allVertexCount, vertexCount);
}
}
allVertexCount += vertexCount;
}
}
return this;
}
// attempts to click the top-most Lines instance
static tryClick(
e: LeafletMouseEvent,
map: Map,
instances: Lines[]
): boolean | undefined {
let foundFeature: Feature<LineString | MultiLineString> | null = null;
let foundLines: Lines | null = null;
instances.forEach((instance: Lines): void => {
const {
latitudeKey,
longitudeKey,
sensitivity,
weight,
scale,
active,
} = instance;
if (!active) return;
if (instance.map !== map) return;
function checkClick(
coordinate: Position,
prevCoordinate: Position,
feature: Feature<LineString | MultiLineString>,
chosenWeight: number
): void {
const distance = latLngDistance(
e.latlng.lng,
e.latlng.lat,
prevCoordinate[longitudeKey],
prevCoordinate[latitudeKey],
coordinate[longitudeKey],
coordinate[latitudeKey]
);
if (distance <= sensitivity + chosenWeight / scale) {
foundFeature = feature;
foundLines = instance;
}
}
instance.data.features.forEach(
(feature: Feature<LineString | MultiLineString>, i: number): void => {
const chosenWeight =
typeof weight === "function" ? weight(i, feature) : weight;
const { coordinates, type } = feature.geometry;
if (type === "LineString") {
for (let i = 1; i < coordinates.length; i++) {
checkClick(
coordinates[i] as Position,
coordinates[i - 1] as Position,
feature,
chosenWeight
);
}
} else if (type === "MultiLineString") {
// TODO: Unit test
for (let i = 0; i < coordinates.length; i++) {
const coordinate = coordinates[i];
for (let j = 0; j < coordinate.length; j++) {
if (j === 0 && i > 0) {
const prevCoordinates = coordinates[i - 1];
const lastPositions =
prevCoordinates[prevCoordinates.length - 1];
checkClick(
lastPositions as Position,
coordinates[i][j] as Position,
feature,
chosenWeight
);
} else if (j > 0) {
checkClick(
coordinates[i][j] as Position,
coordinates[i][j - 1] as Position,
feature,
chosenWeight
);
}
}
}
}
}
);
});
if (foundLines && foundFeature) {
const result = (foundLines as Lines).click(e, foundFeature);
return result !== undefined ? result : undefined;
}
}
hoveringFeatures: Array<Feature<LineString | MultiLineString>> = [];
// hovers all touching Lines instances
static tryHover(
e: LeafletMouseEvent,
map: Map,
instances: Lines[]
): Array<boolean | undefined> {
const results: Array<boolean | undefined> = [];
instances.forEach((instance: Lines): void => {
const {
sensitivityHover,
latitudeKey,
longitudeKey,
data,
hoveringFeatures,
weight,
scale,
} = instance;
function checkHover(
coordinate: Position,
prevCoordinate: Position,
feature: Feature<LineString | MultiLineString>,
chosenWeight: number
): boolean {
const distance = latLngDistance(
e.latlng.lng,
e.latlng.lat,
prevCoordinate[longitudeKey],
prevCoordinate[latitudeKey],
coordinate[longitudeKey],
coordinate[latitudeKey]
);
if (distance <= sensitivityHover + chosenWeight / scale) {
if (!newHoveredFeatures.includes(feature)) {
newHoveredFeatures.push(feature);
}
if (!oldHoveredFeatures.includes(feature)) {
return true;
}
}
return false;
}
if (!instance.active) return;
if (map !== instance.map) return;
const oldHoveredFeatures = hoveringFeatures;
const newHoveredFeatures: Array<
Feature<LineString | MultiLineString>
> = [];
instance.hoveringFeatures = newHoveredFeatures;
// Check if e.latlng is inside the bbox of the features
const bounds = geoJSON(data.features).getBounds();
if (inBounds(e.latlng, bounds)) {
data.features.forEach(
(feature: Feature<LineString | MultiLineString>, i: number): void => {
const chosenWeight =
typeof weight === "function" ? weight(i, feature) : weight;
const { coordinates, type } = feature.geometry;
let isHovering = false;
if (type === "LineString") {
for (let i = 1; i < coordinates.length; i++) {
isHovering = checkHover(
coordinates[i] as Position,
coordinates[i - 1] as Position,
feature,
chosenWeight
);
if (isHovering) break;
}
} else if (type === "MultiLineString") {
// TODO: Unit test
for (let i = 0; i < coordinates.length; i++) {
const coordinate = coordinates[i];
for (let j = 0; j < coordinate.length; j++) {
if (j === 0 && i > 0) {
const prevCoordinates = coordinates[i - 1];
const lastPositions =
prevCoordinates[prevCoordinates.length - 1];
isHovering = checkHover(
lastPositions as Position,
coordinates[i][j] as Position,
feature,
chosenWeight
);
if (isHovering) break;
} else if (j > 0) {
isHovering = checkHover(
coordinates[i][j] as Position,
coordinates[i][j - 1] as Position,
feature,
chosenWeight
);
if (isHovering) break;
}
}
}
}
if (isHovering) {
const result = instance.hover(e, feature);
if (result !== undefined) {
results.push(result);
}
}
}
);
}
for (let i = 0; i < oldHoveredFeatures.length; i++) {
const feature = oldHoveredFeatures[i];
if (!newHoveredFeatures.includes(feature)) {
instance.hoverOff(e, feature);
}
}
});
return results;
}
} | the_stack |
'use strict';
import errHandler = require('./util/error-handler');
import path = require('path');
import fs = require('fs');
import Promise = require('bluebird');
import VError = require('verror');
import miniwrite = require('miniwrite');
import ministyle = require('ministyle');
import fileIO = require('../xm/fileIO');
import assertVar = require('../xm/assertVar');
import dateUtils = require('../xm/dateUtils');
import stringUtils = require('../xm/stringUtils');
import PackageJSON = require('../xm/lib/PackageJSON');
import StyledOut = require('../xm/lib/StyledOut');
import ActionMap = require('../xm/lib/ActionMap');
import GithubRateInfo = require('../git/model/GithubRateInfo');
import API = require('./API');
import Options = require('./Options');
import Context = require('./context/Context');
import Const = require('./context/Const');
import Paths = require('./context/Paths');
import DefVersion = require('./data/DefVersion');
import defUtil = require('./util/defUtil');
import Query = require('./select/Query');
import Selection = require('./select/Selection');
import VersionMatcher = require('./select/VersionMatcher');
import CommitMatcher = require('./select/CommitMatcher');
import DateMatcher = require('./select/DateMatcher');
import InstallResult = require('./logic/InstallResult');
import PackageDefinition = require('./support/PackageDefinition');
import BundleChange = require('./support/BundleChange');
import Expose = require('../expose/Expose');
import ExposeGroup = require('../expose/Group');
import ExposeOption = require('../expose/Option');
import ExposeResult = require('../expose/Result');
import ExposeCommand = require('../expose/Command');
import ExposeContext = require('../expose/Context');
import sorter = require('../expose/sorter');
import CliConst = require('./cli/const');
import Opt = CliConst.Opt;
import Group = CliConst.Group;
import Action = CliConst.Action;
import Printer = require('./cli/CLIPrinter');
import TablePrinter = require('./cli/TablePrinter');
import StyleMap = require('./cli/StyleMap');
import Tracker = require('./cli/tracker');
import addCommon = require('./cli/addCommon');
import update = require('./cli/update');
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// bundle some data
export class Job {
ctx: ExposeContext;
api: API;
context: Context;
query: Query;
options: Options;
}
// hah!
export interface JobSelectionAction {
(ctx: ExposeContext, job: Job, selection: Selection):Promise<any>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// the fun starts here
export function getExpose(): Expose {
var output = new StyledOut();
if (!process.stdout['isTTY']) {
output.useStyle(ministyle.plain());
}
var print = new Printer(output);
var table = new TablePrinter(output);
var styles = new StyleMap(output);
var tracker = new Tracker();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// very basic (async) init stuff
function init(ctx: ExposeContext): Promise<void> {
return Promise.resolve();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function showHeader(): Promise<void> {
var pkg = PackageJSON.getLocal();
output.ln().report(true).tweakPunc(pkg.getNameVersion()).ln(); // .space().muted('(').accent('beta').muted(')').ln();
// .clear().span(pkg.getHomepage(true)).ln()
// .ruler().ln();
return Promise.resolve();
}
function runUpdateNotifier(ctx: ExposeContext, context: Context): Promise<any> {
if (ctx.getOpt(Opt.services)) {
return update.runNotifier(context, false);
}
return Promise.resolve();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// TODO get rid of syncronous io
function getContext(ctx: ExposeContext): Promise<Context> {
assertVar(ctx, ExposeContext, 'ctx');
var context = new Context(ctx.getOpt(Opt.config), ctx.getOpt(Opt.verbose));
tracker.init(context, (ctx.getOpt(Opt.services) && context.config.stats), ctx.getOpt(Opt.verbose));
if (ctx.getOpt(Opt.dev)) {
// TODO why not local?
context.paths.cacheDir = path.resolve(path.dirname(PackageJSON.find()), Const.cacheDir);
}
else if (ctx.hasOpt(Opt.cacheDir)) {
context.paths.cacheDir = path.resolve(ctx.getOpt(Opt.cacheDir));
}
else if (!context.paths.cacheDir) {
context.paths.cacheDir = Paths.getUserCacheDir();
}
return Promise.resolve(context);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var defaultJobOptions = [Opt.config];
function jobOptions(merge: string[] = []): string[] {
return defaultJobOptions.concat(merge);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// get a API with a Context and parse basic arguments
function getAPIJob(ctx: ExposeContext): Promise<Job> {
return init(ctx).then(() => {
return getContext(ctx).then((context: Context) => {
var job = new Job();
job.context = context;
job.ctx = ctx;
job.api = new API(job.context);
job.options = new Options();
job.options.limitApi = ctx.getOpt(Opt.limit);
job.options.minMatches = ctx.getOpt(Opt.min);
job.options.maxMatches = ctx.getOpt(Opt.max);
job.options.saveToConfig = ctx.getOpt(Opt.save);
job.options.saveBundle = ctx.getOpt(Opt.save);
job.options.overwriteFiles = ctx.getOpt(Opt.overwrite);
job.options.resolveDependencies = ctx.getOpt(Opt.resolve);
job.options.addToBundles = ctx.getOpt(Opt.bundle);
job.options.reinstallClean = ctx.getOpt(Opt.reinstallClean);
if (ctx.hasOpt(Opt.cacheMode)) {
job.api.core.useCacheMode(ctx.getOpt(Opt.cacheMode));
}
return job.api.readConfig(true).then(() => {
tracker.enabled = (tracker.enabled && job.context.config.stats);
return runUpdateNotifier(ctx, job.context);
}).return(job);
});
});
}
// get a API and parse selector options
function getSelectorJob(ctx: ExposeContext): Promise<Job> {
// callback for easy error reporting
return getAPIJob(ctx).then((job: Job) => {
if (ctx.numArgs < 1) {
throw new VError('pass at least one query pattern');
}
job.query = new Query();
for (var i = 0, ii = ctx.numArgs; i < ii; i++) {
job.query.addNamePattern(ctx.getArgAt(i));
}
job.query.versionMatcher = new VersionMatcher(ctx.getOpt(Opt.semver));
if (ctx.hasOpt(Opt.commit)) {
job.query.commitMatcher = new CommitMatcher(ctx.getOpt(Opt.commit));
}
if (ctx.hasOpt(Opt.date)) {
job.query.dateMatcher = new DateMatcher(ctx.getOpt(Opt.date));
}
job.query.parseInfo = ctx.getOpt(Opt.info);
job.query.loadHistory = ctx.getOpt(Opt.history);
if (ctx.getOptAs(Opt.verbose, 'boolean')) {
output.span('CLI job.query').info().inspect(job.query, 3);
}
return job;
});
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
var expose = new Expose(output);
function reportError(err: any, head: boolean = true): void {
tracker.error(err);
errHandler.handler(err);
};
function link(job: Job): Promise<PackageDefinition[]> {
return job.api.link(job.api.context.paths.startCwd).then((packages: PackageDefinition[]) => {
if (packages.length > 0) {
packages.forEach((linked) => {
tracker.link(linked.name + ' (' + linked.manager + ')');
output.indent(1).report(true).line(linked.name + ' (' + linked.manager + ')');
});
}
return packages;
});
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
expose.before = (ctx: ExposeContext) => {
return null; // showHeader();
};
expose.end = (ctx: ExposeResult) => {
if (!ctx.error) {
return update.showNotifier(output);
}
return null;
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
expose.defineGroup((group: ExposeGroup) => {
group.name = Group.query;
group.label = 'main';
group.options = [Opt.config, Opt.cacheDir, Opt.min, Opt.max, Opt.limit];
group.sorter = (one: ExposeCommand, two: ExposeCommand): number => {
var sort: number;
// TODO sane-ify sorting groups
sort = sorter.sortHasElem(one.groups, two.groups, Group.query);
if (sort !== 0) {
return sort;
}
return sorter.sortCommandIndex(one, two);
};
});
expose.defineGroup((group: ExposeGroup) => {
group.name = Group.manage;
group.label = 'manage';
group.options = [];
group.sorter = (one: ExposeCommand, two: ExposeCommand): number => {
var sort: number;
// TODO sane-ify sorting groups
sort = sorter.sortHasElem(one.groups, two.groups, Group.manage);
if (sort !== 0) {
return sort;
}
return sorter.sortCommandIndex(one, two);
};
});
expose.defineGroup((group: ExposeGroup) => {
group.name = Group.support;
group.label = 'support';
group.options = [];
group.sorter = (one: ExposeCommand, two: ExposeCommand): number => {
var sort: number;
// TODO sane-ify sorting groups
sort = sorter.sortHasElem(one.groups, two.groups, Group.support);
if (sort !== 0) {
return sort;
}
return sorter.sortCommandIndex(one, two);
};
});
expose.defineGroup((group: ExposeGroup) => {
group.name = Group.help;
group.label = 'help';
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// bulk add boring commands and options
addCommon(expose, print, styles);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function executeReinstall(ctx: ExposeContext, cmd: ExposeCommand) {
return getAPIJob(ctx).then((job: Job) => {
output.line();
output.info(true).span('running').space().accent(cmd.name).ln();
return job.api.reinstall(job.options).then((result: InstallResult) => {
print.installResult(result);
tracker.install('reinstall', result);
});
}).catch(reportError);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'help';
cmd.label = 'display usage help';
cmd.groups = [Group.support];
cmd.execute = (ctx: ExposeContext) => {
return showHeader().then(() => {
return getContext(ctx);
}).then((context: Context) => {
ctx.out.ln();
ctx.expose.reporter.printCommands();
return runUpdateNotifier(ctx, context);
}).catch(reportError);
};
});
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'version';
cmd.label = 'display tsd version info';
cmd.groups = [Group.support];
cmd.execute = (ctx: ExposeContext) => {
return showHeader().then(() => {
return getContext(ctx);
}).then((context: Context) => {
return runUpdateNotifier(ctx, context);
}).catch(reportError);
};
});
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'init';
cmd.label = 'create empty config file';
cmd.options = [Opt.config, Opt.overwrite];
cmd.groups = [Group.support];
cmd.execute = (ctx: ExposeContext) => {
return getAPIJob(ctx).then((job: Job) => {
return job.api.initConfig(ctx.getOpt(Opt.overwrite)).then((targets: string[]) => {
output.ln();
targets.forEach((dest) => {
output.info().accent('written').sp().span(dest).ln();
});
});
}).catch(reportError);
};
});
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'settings';
cmd.label = 'display config settings';
cmd.options = [Opt.config, Opt.cacheDir];
cmd.groups = [Group.support];
cmd.execute = (ctx: ExposeContext) => {
return getAPIJob(ctx).then((job: Job) => {
output.ln().plain(JSON.stringify(job.api.context.getInfo(true), null, 3));
}).catch(reportError);
};
});
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'purge';
cmd.label = 'clear local caches';
cmd.options = [Opt.cacheDir];
cmd.groups = [Group.support];
cmd.execute = (ctx: ExposeContext) => {
return getAPIJob(ctx).then((job: Job) => {
// TODO expose raw/api/all option
return job.api.purge(true, true).then(() => {
output.ln().info().success('purged cache').ln();
});
}).catch(reportError);
};
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// TODO abstractify ActionMap / JobSelectionAction into Expose
var queryActions = new ActionMap<JobSelectionAction>();
queryActions.set(Action.install, function (ctx: ExposeContext, job: Job, selection: Selection) {
return job.api.install(selection, job.options).then((result: InstallResult) => {
print.installResult(result);
tracker.install('install', result);
});
});
queryActions.set(Action.browse, function (ctx: ExposeContext, job: Job, selection: Selection) {
return job.api.browse(selection.selection).then((opened: string[]) => {
if (opened.length > 0) {
print.output.ln();
opened.forEach((url: string) => {
print.output.note(true).line(url);
tracker.browser(url);
});
}
});
});
queryActions.set(Action.visit, function (ctx: ExposeContext, job: Job, selection: Selection) {
return job.api.visit(selection.selection).then((opened: string[]) => {
if (opened.length > 0) {
print.output.ln();
opened.forEach((url: string) => {
print.output.note(true).line(url);
tracker.visit(url);
});
}
});
});
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'install';
cmd.label = 'install definitions using one or more globbing patterns.';
cmd.examples = [
['tsd install mocha', 'install mocha'],
['tsd install angularjs/', 'install full angularjs bundle'],
['tsd install', 'perform reinstall command']
];
cmd.variadic = ['...pattern'];
cmd.groups = [Group.query];
cmd.options = [
Opt.semver, Opt.date, Opt.commit,
Opt.overwrite, Opt.save, Opt.bundle
];
cmd.execute = (ctx: ExposeContext) => {
// Verify if install command has any arguments, if not,
// the command will be performed as a reinstall command
// ref: https://github.com/DefinitelyTyped/tsd/issues/122
// https://github.com/DefinitelyTyped/tsd/issues/116
if (ctx.numArgs === 0) {
return executeReinstall(ctx, cmd);
}
// install command will have --resolve flag by default
ctx.argv[Opt.resolve] = true;
return getSelectorJob(ctx).then((job: Job) => {
tracker.query(job.query);
if (job.options.saveToConfig) {
job.options.overwriteFiles = true;
}
return job.api.select(job.query, job.options).then((selection: Selection) => {
if (selection.selection.length === 0) {
output.ln().report().signal('zero results').ln();
return;
}
output.line();
table.fileTable(selection.selection);
output.ln().report(true).span('running').space().accent('install').span('..').ln();
return job.api.install(selection, job.options).then((result: InstallResult) => {
print.installResult(result);
tracker.install('install', result);
}).catch((err) => {
output.report().span('install').space().error('error!').ln();
reportError(err, false);
});
});
}).catch(reportError);
};
});
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'query';
cmd.label = 'search definitions using one or more globbing patterns';
cmd.examples = [
['tsd query d3 --info --history', 'view d3 info & history'],
['tsd query mocha --action install', 'install mocha'],
['tsd query jquery.*/*', 'search jquery plugins'],
['tsd query angularjs/ --resolve', 'list full angularjs bundle']
];
cmd.variadic = ['...pattern'];
cmd.groups = [Group.query];
cmd.options = [
Opt.info, Opt.history,
Opt.semver, Opt.date, Opt.commit,
Opt.action,
Opt.resolve, Opt.overwrite, Opt.save, Opt.bundle
];
cmd.execute = (ctx: ExposeContext) => {
return getSelectorJob(ctx).then((job: Job) => {
tracker.query(job.query);
if (job.options.saveToConfig) {
job.options.overwriteFiles = true;
}
return job.api.select(job.query, job.options).then((selection: Selection) => {
if (selection.selection.length === 0) {
output.ln().report().signal('zero results').ln();
return;
}
output.line();
table.fileTable(selection.selection);
// run actions
return Promise.attempt(() => {
// get as arg
var action = ctx.getOpt(Opt.action);
if (!action) {
// output.ln().report().warning('no action').ln();
return;
}
if (!queryActions.has(action)) {
output.ln().report().signal('unknown action:').space().span(action).ln();
return;
}
output.ln().report(true).span('running').space().accent(action).span('..').ln();
return queryActions.run(action, (run: JobSelectionAction) => {
return run(ctx, job, selection);
}, true).catch((err) => {
output.report().span(action).space().error('error!').ln();
reportError(err, false);
});
});
});
}).catch(reportError);
};
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'reinstall';
cmd.label = 're-install definitions from config';
cmd.options = [Opt.overwrite, Opt.save, Opt.reinstallClean];
cmd.groups = [Group.manage];
cmd.execute = (ctx: ExposeContext) => {
return executeReinstall(ctx, cmd);
};
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'update';
cmd.label = 'update definitions from config';
cmd.options = [Opt.overwrite, Opt.save];
cmd.groups = [Group.manage];
cmd.execute = (ctx: ExposeContext) => {
return getAPIJob(ctx).then((job: Job) => {
output.line();
output.info(true).span('running').space().accent(cmd.name).ln();
return job.api.update(job.options).then((result: InstallResult) => {
print.installResult(result);
tracker.install('update', result);
});
}).catch(reportError);
};
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'rebundle';
cmd.label = 'update & clean reference bundle';
cmd.groups = [Group.manage];
cmd.execute = (ctx: ExposeContext) => {
return getAPIJob(ctx).then((job: Job) => {
return Promise.attempt(() => {
if (!job.api.context.config.bundle) {
output.line();
output.report(true).line('no bundle configured').ln();
return null;
}
output.line();
// output.info(true).span('running').space().accent(cmd.name).ln();
return job.api.updateBundle(job.api.context.config.bundle, true).then((changes) => {
if (changes.someRemoved()) {
output.report(true).line('removed:');
changes.getRemoved(true, true).sort().forEach((file) => {
output.indent(1).bullet(true).tweakPath(file).ln();
});
}
if (changes.someAdded()) {
output.report(true).line('added:');
changes.getAdded(true, true).sort().forEach((file) => {
output.indent(1).bullet(true).tweakPath(file).ln();
});
}
if (!changes.someAdded() && !changes.someRemoved()) {
output.report(true).span('nothing rebundled').ln();
}
});
});
}).catch(reportError);
};
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'link';
cmd.label = 'link definitions from package managers';
cmd.groups = [Group.manage];
cmd.execute = (ctx: ExposeContext) => {
return getAPIJob(ctx).then((job: Job) => {
output.line();
// output.info(true).span('running').space().accent(cmd.name).ln().ln();
return link(job).then((packages) => {
if (packages.length === 0) {
output.report(true).line('no (new) packages to link');
}
});
}).catch(reportError);
};
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
expose.defineCommand((cmd: ExposeCommand) => {
cmd.name = 'rate';
cmd.label = 'check github rate-limit';
cmd.groups = [Group.support];
cmd.execute = (ctx: ExposeContext) => {
return getAPIJob(ctx).then((job: Job) => {
return job.api.getRateInfo().then((info: GithubRateInfo) => {
print.rateInfo(info, false, true);
});
}).catch(reportError);
};
});
return expose;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// trying to remove tsd-debug.log if exists
try {
if (fs.existsSync(path.resolve(process.cwd(), 'tsd-debug.log'))) {
fs.unlinkSync(path.resolve(process.cwd(), 'tsd-debug.log'));
}
} catch (e) { /*...*/ }
/*
runARGV: run raw cli arguments, like process.argv
*/
export function runARGV(argvRaw: any) {
getExpose().executeArgv(argvRaw, 'help');
} | the_stack |
import type * as CSS from 'csstype';
import type * as postcss from 'postcss';
type KeyValuePair<TKey extends keyof never = string, TValue = string> = Record<TKey, TValue>;
type CSSProperties = CSS.Properties & Record<`--${string}`, string>;
type CSSBlock = Record<string, CSSProperties | Record<string, CSSProperties>>;
type ConfigUtils = {
negative: <TInput, TOutput>(input: TInput) => TOutput;
breakpoints: <TInput, TOutput>(input: TInput) => TOutput;
};
type ConfigDotNotationPath = string;
type ResolvableTo<TResult> =
| TResult
| ((theme: (path: ConfigDotNotationPath) => TResult, utils: ConfigUtils) => TResult);
type BaseConfig = {
important: boolean | string;
target: 'ie11' | 'relaxed';
prefix: string | ((className: string) => string);
separator: string;
};
type PurgeConfig =
| Array<string>
| false
| { enabled: boolean; mode: 'all' | 'conservative'; content: Array<string> }
| { enabled: boolean; options: { content: Array<string>; whitelist: Array<string> } };
type ContentConfig =
| Array<string>
| {
files: Array<string>;
safelist?: Array<string | { pattern: RegExp; variants?: Array<string> }>;
transform?: Record<string, (content: string) => string>;
extract?: Record<string, (content: string) => Array<string>>;
};
type FutureConfig = Record<never, never> | 'all' | [];
type ExperimentalConfig = Record<never, never> | 'all' | [];
type DarkModeConfig = 'class' | 'media' | false;
type ThemeConfig = Partial<
Record<string, unknown> & {
extend: Partial<Omit<ThemeConfig, 'extend'>>;
/** Responsiveness */
screens: ResolvableTo<KeyValuePair>;
/** Reusable base configs */
colors: ResolvableTo<KeyValuePair | Record<string, Record<number | string, string>>>;
spacing: ResolvableTo<KeyValuePair>;
/** Background */
backgroundColor: ThemeConfig['colors'];
backgroundImage: ResolvableTo<KeyValuePair>;
gradientColorStops: ThemeConfig['colors'];
backgroundOpacity: ThemeConfig['opacity'];
backgroundPosition: ResolvableTo<KeyValuePair>;
backgroundSize: ResolvableTo<KeyValuePair>;
backgroundOrigin: ResolvableTo<KeyValuePair>;
/** Border */
borderColor: ThemeConfig['colors'];
borderOpacity: ThemeConfig['opacity'];
borderRadius: ResolvableTo<KeyValuePair>;
borderWidth: ResolvableTo<KeyValuePair>;
/** Shadow */
boxShadow: ResolvableTo<KeyValuePair>;
/** Outline */
outline: ResolvableTo<KeyValuePair>;
/** Cursor */
cursor: ResolvableTo<KeyValuePair>;
/** Content */
content: ResolvableTo<KeyValuePair>;
/** Divider */
divideColor: ThemeConfig['borderColor'];
divideOpacity: ThemeConfig['borderOpacity'];
devideWidth: ThemeConfig['borderWidth'];
/** SVG */
fill: ResolvableTo<KeyValuePair>;
stroke: ResolvableTo<KeyValuePair>;
strokeWidth: ResolvableTo<KeyValuePair>;
/** Flexbox */
flex: ResolvableTo<KeyValuePair>;
flexGrow: ResolvableTo<KeyValuePair>;
flexShrink: ResolvableTo<KeyValuePair>;
/** Fonts */
fontFamily: ResolvableTo<Record<string, Array<string>>>;
fontSize: ResolvableTo<KeyValuePair>;
fontWeight: ResolvableTo<KeyValuePair>;
/** Sizes */
height: ThemeConfig['spacing'];
minHeight: ResolvableTo<KeyValuePair>;
maxHeight: ResolvableTo<KeyValuePair>;
width: ThemeConfig['spacing'];
minWidth: ResolvableTo<KeyValuePair>;
maxWidth: ResolvableTo<KeyValuePair>;
aspectRatio: ResolvableTo<KeyValuePair>;
/** Positioning */
inset: ResolvableTo<KeyValuePair>;
zIndex: ResolvableTo<KeyValuePair>;
/** Text */
letterSpacing: ResolvableTo<KeyValuePair>;
lineHeight: ResolvableTo<KeyValuePair>;
textColor: ThemeConfig['colors'];
textOpacity: ThemeConfig['opacity'];
textIndent: ThemeConfig['spacing'];
/** Input */
placeholderColor: ThemeConfig['colors'];
placeholderOpacity: ThemeConfig['opacity'];
caretColor: ThemeConfig['colors'];
/** Lists */
listStyleType: ResolvableTo<KeyValuePair>;
/** Layout */
margin: ThemeConfig['spacing'];
padding: ThemeConfig['spacing'];
space: ThemeConfig['spacing'];
opacity: ResolvableTo<KeyValuePair>;
order: ResolvableTo<KeyValuePair>;
columns: ResolvableTo<KeyValuePair>;
/** Images */
objectPosition: ResolvableTo<KeyValuePair>;
/** Grid */
gap: ThemeConfig['spacing'];
gridTemplateColumns: ResolvableTo<KeyValuePair>;
gridColumn: ResolvableTo<KeyValuePair>;
gridColumnStart: ResolvableTo<KeyValuePair>;
gridColumnEnd: ResolvableTo<KeyValuePair>;
gridTemplateRows: ResolvableTo<KeyValuePair>;
gridRow: ResolvableTo<KeyValuePair>;
gridRowStart: ResolvableTo<KeyValuePair>;
gridRowEnd: ResolvableTo<KeyValuePair>;
/** Transformations */
transformOrigin: ResolvableTo<KeyValuePair>;
scale: ResolvableTo<KeyValuePair>;
rotate: ResolvableTo<KeyValuePair>;
translate: ThemeConfig['spacing'];
skew: ResolvableTo<KeyValuePair>;
/** Transitions */
transitionProperty: ResolvableTo<KeyValuePair>;
transitionTimingFunction: ResolvableTo<KeyValuePair>;
transitionDuration: ResolvableTo<KeyValuePair>;
transitionDelay: ResolvableTo<KeyValuePair>;
willChange: ResolvableTo<KeyValuePair>;
/** Animations */
animation: ResolvableTo<KeyValuePair>;
keyframes: ResolvableTo<Record<string, Record<string, KeyValuePair | string>>>;
/** Filters */
blur: ResolvableTo<Record<string, Array<string> | string>>;
brightness: ResolvableTo<Record<string, Array<string> | string>>;
contrast: ResolvableTo<Record<string, Array<string> | string>>;
dropShadow: ResolvableTo<Record<string, Array<string> | string>>;
grayscale: ResolvableTo<Record<string, Array<string> | string>>;
hueRotate: ResolvableTo<Record<string, Array<string> | string>>;
invert: ResolvableTo<Record<string, Array<string> | string>>;
saturate: ResolvableTo<Record<string, Array<string> | string>>;
sepia: ResolvableTo<Record<string, Array<string> | string>>;
backdropFilter: ResolvableTo<Record<string, Array<string> | string>>;
backdropBlur: ResolvableTo<Record<string, Array<string> | string>>;
backdropBrightness: ResolvableTo<Record<string, Array<string> | string>>;
backdropContrast: ResolvableTo<Record<string, Array<string> | string>>;
backdropGrayscale: ResolvableTo<Record<string, Array<string> | string>>;
backdropHueRotate: ResolvableTo<Record<string, Array<string> | string>>;
backdropInvert: ResolvableTo<Record<string, Array<string> | string>>;
backdropOpacity: ResolvableTo<Record<string, Array<string> | string>>;
backdropSaturate: ResolvableTo<Record<string, Array<string> | string>>;
backdropSepia: ResolvableTo<Record<string, Array<string> | string>>;
/** Components */
container: Partial<{
screens:
| Array<string>
| Record<string, { min: string; max: string }>
| Record<string, string>;
center: boolean;
padding: KeyValuePair | string;
}>;
}
>;
type VariantsAPI = {
variants: (path: string) => Array<string>;
before: (
toInsert: Array<string>,
variant?: string,
existingPluginVariants?: Array<string>,
) => Array<string>;
after: (
toInsert: Array<string>,
variant?: string,
existingPluginVariants?: Array<string>,
) => Array<string>;
without: (toRemove: Array<string>, existingPluginVariants?: Array<string>) => Array<string>;
};
type VariantsConfig =
| Array<string>
| Record<string, Array<string> | ((api: VariantsAPI) => Array<string>)>
| { extend: Record<string, Array<string>> };
type CorePluginsConfig = Array<string> | Record<string, boolean>;
type VariantConfig =
| Array<string>
| Partial<{ variants: Array<string>; respectPrefix: false; respectImportant: false }>;
type ValueType =
| 'absolute-size'
| 'any'
| 'color'
| 'family-name'
| 'generic-name'
| 'image'
| 'length'
| 'line-width'
| 'lookup'
| 'number'
| 'percentage'
| 'position'
| 'relative-size'
| 'url';
type PluginAPI = {
/** Get access to the whole config */
config: <TDefaultValue = TailwindConfig>(
path?: ConfigDotNotationPath,
defaultValue?: TDefaultValue,
) => TDefaultValue;
/** Escape classNames */
e: (className: string) => string;
/** Shortcut for the theme section of the config */
theme: <TDefaultValue>(
path: ConfigDotNotationPath,
defaultValue?: TDefaultValue,
) => TDefaultValue;
variants: <TDefaultValue>(
path: ConfigDotNotationPath,
defaultValue: TDefaultValue,
) => TDefaultValue;
target: (path: ConfigDotNotationPath) => string;
prefix: (selector: string) => string;
/** Ability to add utilities. E.g.: .p-4 */
addUtilities: (utilities: CSSBlock, variantConfig?: VariantConfig) => void;
/** Ability to add components. E.g.: .btn */
addComponents: (components: CSSBlock, variantConfig?: VariantConfig) => void;
addBase: (base: CSSBlock) => void;
addVariant: (
name: string,
generator: (api: {
container: postcss.Container;
separator: string;
modifySelectors: (
modifierFunction: (api: { className: string; selector: string }) => void,
) => void;
}) => void,
) => void;
matchUtilities: <T>(
utilities: Record<string, (value: T) => CSSBlock[string]>,
options?: Partial<{
values: Record<string, T>;
type: Array<ValueType> | ValueType;
respectPrefix: boolean;
respectImportant: boolean;
respectVariants: boolean;
}>,
) => void;
corePlugins: (path: string) => boolean;
postcss: typeof postcss;
};
type PluginCreator = (api: PluginAPI) => void;
type PluginsConfig = Array<PluginCreator | { handler: PluginCreator; config?: TailwindConfig }>;
/** The holy grail Tailwind config definition */
type TailwindConfig = Partial<
BaseConfig &
Record<string, unknown> & {
presets: Array<TailwindConfig>;
future: FutureConfig;
experimental: ExperimentalConfig;
purge: PurgeConfig;
content: ContentConfig;
darkMode: DarkModeConfig;
theme: ThemeConfig;
variants: VariantsConfig;
corePlugins: CorePluginsConfig;
plugins: PluginsConfig;
mode: 'aot' | 'jit';
}
>;
type EntryPoint = (config: TailwindConfig) => TailwindConfig; | the_stack |
import React, { Component } from "react";
import { Table } from "reactstrap";
import { fetchEvents } from "../utils/fetch";
import Error from "./Error";
import { FaCaretDown, FaCaretRight } from "react-icons/fa";
import { parseDate } from "../utils/date";
import { SessionBar } from "./SessionBar";
import { niceTime, TaskStatusBadge } from "./utils";
const bgColors = ["white", "#EEE", "#D2D2D2"];
interface Node {
name: string;
type: string;
open?: boolean;
// Groups
tasksCount?: number;
tasksFinished?: number;
childs?: Node[];
durationSum?: number;
durationStdDev?: number;
// Task
spec?: any;
info?: any;
status?: string;
startTime?: number;
}
interface State {
name: string;
error: string;
root: Node;
tasks: Map<number, Node>;
}
interface Props {
id: string;
}
interface ListItem {
level: number;
node: Node;
}
function getColor(value: number) {
const hue = ((1 - value) * 120).toString(10);
return ["hsl(", hue, ",100%,75%)"].join("");
}
const GroupRow = (props: {
level: number;
node: Node;
rootDurationSum: number;
toggleOpen: (node: Node) => void;
}) => {
const node = props.node;
const durationRatio = node.durationSum / props.rootDurationSum;
const toggle = () => props.toggleOpen(props.node);
return (
<tr style={{ backgroundColor: bgColors[props.level % 3] }}>
<td>
<span
onClick={toggle}
style={{ paddingLeft: props.level * 2 + "em", cursor: "pointer" }}
>
{node.open ? <FaCaretDown /> : <FaCaretRight />}
{node.name || <i>Unnamed</i>} {node.spec && node.spec.id[1]}{" "}
</span>
</td>
<td>
{node.tasksFinished}/{node.tasksCount}
</td>
<td>
{node.tasksFinished > 0 &&
niceTime(node.durationSum / node.tasksFinished) +
" ±" +
niceTime(node.durationStdDev)}
</td>
<td
style={{
paddingLeft: props.level + 0.5 + "em",
backgroundColor: getColor(durationRatio)
}}
>
{niceTime(node.durationSum)} ({(durationRatio * 100).toFixed(0)}
%)
</td>
</tr>
);
};
const TaskRow = (props: {
level: number;
node: Node;
rootDurationSum: number;
toggleOpen: (node: Node) => void;
}) => {
const node = props.node;
let durationRatio = 0;
let duration;
if (node.info && node.info.duration) {
duration = node.info.duration;
durationRatio = duration / props.rootDurationSum;
} else {
duration = null;
}
const toggle = () => props.toggleOpen(props.node);
const main = (
<tr style={{ backgroundColor: "#eef" }}>
<td>
<span
style={{ paddingLeft: props.level * 2 + "em", cursor: "pointer" }}
onClick={toggle}
>
{node.open ? <FaCaretDown /> : <FaCaretRight />}
Task {node.spec && node.spec.id[1]} {node.name}
</span>
</td>
<td>
<TaskStatusBadge status={node.status} />
</td>
<td>{duration && niceTime(duration)}</td>
{duration ? (
<td
style={{
paddingLeft: props.level + "em",
backgroundColor: getColor(durationRatio)
}}
>
{niceTime(duration)} ({(durationRatio * 100).toFixed(0)}
%)
</td>
) : (
<td />
)}
</tr>
);
if (!node.open) {
return main;
} else {
return (
<>
{main}
<tr>
<td colSpan={5} style={{ paddingLeft: (props.level + 1) * 2 + "em" }}>
<TaskDetails node={props.node} />
</td>
</tr>
</>
);
}
};
const TaskDetails = (props: { node: Node }) => {
const spec = props.node.spec;
const inputs = spec.inputs || [];
const outputs = spec.outputs || [];
const info = props.node.info;
return (
<div>
<Table>
<thead>
<tr>
<th style={{ width: "10em" }}>Spec name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Id</td>
<td>{spec.id[1]}</td>
</tr>
<tr>
<td>Name</td>
<td>{spec.name}</td>
</tr>
<tr>
<td>Resources</td>
<td>
<pre>{JSON.stringify(spec.resources, null, 2)}</pre>
</td>
</tr>
<tr>
<td>Task type</td>
<td>{spec.task_type}</td>
</tr>
<tr>
<td>Task config</td>
<td>
<pre>{JSON.stringify(spec.config, null, 2)}</pre>
</td>
</tr>
<tr>
<td>Inputs</td>
<td>{inputs.length}</td>
</tr>
<tr>
<td>Outputs</td>
<td>{outputs.length}</td>
</tr>
<tr>
<td>User</td>
<td>
<pre>{JSON.stringify(spec.user, null, 2)}</pre>
</td>
</tr>
</tbody>
</Table>
{info && (
<Table>
<thead>
<tr>
<th style={{ width: "10em" }}>Info name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Start time</td>
<td>{info.start_time}</td>
</tr>
<tr>
<td>Duration</td>
<td>{info.duration && niceTime(info.duration)}</td>
</tr>
<tr>
<td>Governor</td>
<td>{info.governor}</td>
</tr>
<tr>
<td>Error</td>
<td>
<pre>{info.error}</pre>
</td>
</tr>
<tr>
<td>Debug</td>
<td>
<pre>{info.debug}</pre>
</td>
</tr>
<tr>
<td>User</td>
<td>
<pre>{JSON.stringify(spec.user, null, 2)}</pre>
</td>
</tr>
</tbody>
</Table>
)}
</div>
);
};
class TaskList extends Component<Props, State> {
readonly state: State = {
name: null,
error: null,
root: this.newGroup("All tasks"),
tasks: new Map()
};
private readonly unsubscribe: () => void;
constructor(props: Props) {
super(props);
this.unsubscribe = fetchEvents(
{ session: { value: +props.id, mode: "=" } },
events => {
const state = { ...this.state };
for (const event of events) {
const evt = event.event;
const type = event.event.type;
if (type === "TaskFinished") {
const node = state.tasks.get(evt.task[1]);
node.status = evt.info.error ? "error" : "finished";
node.info = evt.info;
} else if (type === "TaskStarted") {
const node = state.tasks.get(evt.task[1]);
node.status = "running";
node.startTime = parseDate(event.time).getTime();
node.info = evt.info;
} else if (type === "ClientSubmit") {
this.processSubmit(event.event.tasks);
} else if (type === "SessionNew") {
state.name = evt.spec.name;
} else if (type === "SessionClosed") {
this.unsubscribe();
}
}
this.updateCounts(this.state.root);
this.setState(state);
},
error => {
this.setState(() => ({ error }));
}
);
}
newGroup(name: string): Node {
return {
name,
type: "g",
childs: [],
open: false,
tasksCount: 0,
tasksFinished: 0
};
}
ensureGroup(node: Node, parent: Node): Node {
if (node.type === "g") {
return node;
}
const name = node.name;
const index = parent.childs.indexOf(node);
node.name = null;
const newChild = this.newGroup(name);
newChild.childs.push(node);
parent.childs[index] = newChild;
return newChild;
}
/*
findNode(name: string): Node[] {
let node = this.state.root;
const tokens = name.split("/");
const path = [];
path.push(node);
for (const token in tokens) {
node = node.childs.find(n => token === n.name);
path.push(node);
}
return path;
}
findTask(name: string, taskId: number): Node[] {
let path = this.findNode(name);
let node = path[path.length - 1];
if (node.type === "t") {
return path;
} else {
const t = node.childs.find(n => n.spec && n.spec.id[1] == taskId);
path.push(t);
return path;
}
}*/
findOrCreateGroup(node: Node, names: string, index: number): Node {
const name = names[index];
index += 1;
let child = node.childs.find(c => c.name === name);
if (!child) {
child = this.newGroup(name);
node.childs.push(child);
} else if (child.type === "t") {
child = this.ensureGroup(child, node);
}
if (index === names.length) {
return child;
} else {
return this.findOrCreateGroup(child, names, index);
}
}
updateCounts(root: Node) {
let tasksCount = 0;
let tasksFinished = 0;
let durationSum = 0;
for (const node of root.childs) {
if (node.type === "g") {
this.updateCounts(node);
tasksCount += node.tasksCount;
tasksFinished += node.tasksFinished;
durationSum += node.durationSum;
} else {
tasksCount += 1;
if (node.status === "finished" || node.status === "error") {
tasksFinished += 1;
durationSum += node.info.duration;
}
}
}
const avg = durationSum / tasksFinished;
let devSum = 0;
for (const node of root.childs) {
if (node.type === "g" && node.durationStdDev) {
const diff = node.durationSum / node.tasksFinished - avg;
devSum +=
node.tasksFinished *
(node.durationStdDev * node.durationStdDev + diff * diff);
} else if (node.status === "finished" || node.status === "error") {
const diff = node.info.duration - avg;
devSum += diff * diff;
}
}
root.tasksCount = tasksCount;
root.tasksFinished = tasksFinished;
root.durationSum = durationSum;
root.durationStdDev = Math.sqrt(devSum / tasksFinished);
}
processSubmit(tasks: any[]) {
const root = this.state.root;
for (const task of tasks) {
const tokens = (task.name || "").split("/");
if (tokens.length > 1 && tokens[0] === "") {
tokens.shift();
}
let lastName = tokens.pop();
let group;
if (tokens.length === 0) {
group = root;
} else {
group = this.findOrCreateGroup(root, tokens, 0);
}
const child = group.childs.find(n => n.name === lastName);
if (child) {
group = this.ensureGroup(child, group);
lastName = null;
}
const taskNode: Node = {
name: lastName,
type: "t",
spec: task,
status: null
};
group.childs.push(taskNode);
this.state.tasks.set(task.id[1], taskNode);
}
}
componentWillUnmount() {
this.unsubscribe();
}
linearize() {
const output: ListItem[] = [];
this.linearizeHelper(this.state.root, 0, output);
return output;
}
linearizeHelper(node: Node, level: number, output: ListItem[]) {
output.push({ level, node });
if (node.childs && node.open) {
for (const child of node.childs) {
this.linearizeHelper(child, level + 1, output);
}
}
}
toggleOpen = (node: Node) => {
node.open = !node.open;
this.setState(this.state);
};
render() {
const state = this.state;
return (
<div>
<Error error={this.state.error} />
{state.name && (
<div>
<h1>
Session '{state.name}' ({this.props.id})
</h1>
</div>
)}
<SessionBar id={this.props.id} />
<Table className="text-left" bordered size="sm">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Task Duration</th>
<th>Duration sum</th>
</tr>
</thead>
<tbody>
{this.linearize().map(c => {
if (c.node.type === "g") {
return (
<GroupRow
key={c.node.name}
node={c.node}
toggleOpen={this.toggleOpen}
level={c.level}
rootDurationSum={this.state.root.durationSum}
/>
);
} else {
return (
<TaskRow
key={c.node.spec.id[1]}
node={c.node}
level={c.level}
rootDurationSum={this.state.root.durationSum}
toggleOpen={this.toggleOpen}
/>
);
}
})}
</tbody>
</Table>
</div>
);
}
}
export default TaskList; | the_stack |
import * as pgsqlAST from 'pgsql-ast-parser'
import * as lodash from 'lodash'
import {pascalCase, tryOrDefault} from '../util'
import {match} from 'io-ts-extra'
import * as assert from 'assert'
import * as pluralize from 'pluralize'
// function return types:
// $ echo 'select pg_get_function_result(2880)' | docker-compose exec -T postgres psql -h localhost -U postgres postgres -f -
// $ echo 'select oid, proname from pg_proc where proname like '"'"'%advisory%'"'"' limit 1' | docker-compose exec -T postgres psql -h localhost -U postgres postgres -f -
/**
* parser needs valid-ish sql, so can't use $1, $2 placeholders. Use `null` as a placeholder instead.
* Will probably still fail when placeholder is used for a table identifier, but we can't get any types
* at all for those kinds of queries anyway.
*/
export const templateToValidSql = (template: string[]) => template.join('null')
/**
* _Tries_ to return `true` when a query is definitely not going to work with \gdesc. Will miss some cases, and those cases will cause an error to be logged to the console.
* It will catch:
* - multi statements (that pgsql-ast-parser is able to process) e.g. `insert into foo(id) values (1); insert into foo(id) values (2);`
* - statements that use identifiers (as opposed to param values) e.g. `select * from ${sql.identifier([tableFromVariableName])}`
*/
export const isUntypeable = (template: string[]) => {
let untypeable = false
try {
const delimiter = `t${Math.random()}`.replace('0.', '')
pgsqlAST
.astVisitor(map => ({
tableRef: t => {
if (t.name === delimiter) {
untypeable = true // can only get type when delimiter is used as a parameter, not an identifier
}
map.super().tableRef(t)
},
}))
.statement(getHopefullyViewableAST(template.join(delimiter)))
} catch {}
// too many statements
try {
untypeable ||= pgsqlAST.parse(templateToValidSql(template)).length !== 1
} catch {
untypeable ||= templateToValidSql(template).trim().replace(/\n/g, ' ').replace(/;$/, '').includes(';')
}
return untypeable
}
// todo: return null if statement is not a select
// and have test cases for when a view can't be created
// export const getHopefullyViewableAST = (sql: string): pgsqlAST.Statement => {
// const statements = parseWithWorkarounds(sql)
// assert.ok(statements.length === 1, `Can't parse query ${sql}; it has ${statements.length} statements.`)
// return astToSelect({modifications: [], ast: statements[0]}).ast
// }
const getModifiedAST = (sql: string): ModifiedAST => {
const statements = parseWithWorkarounds(sql)
assert.ok(statements.length === 1, `Can't parse query ${sql}; it has ${statements.length} statements.`)
return astToSelect({modifications: [], ast: statements[0]})
}
export const parseWithWorkarounds = (sql: string, attemptsLeft = 2): pgsqlAST.Statement[] => {
try {
return pgsqlAST.parse(sql)
} catch (e) {
/* istanbul ignore if */
if (attemptsLeft <= 1) {
throw e
}
if (sql.trim().startsWith('with ')) {
// handle (some) CTEs. Can fail if comments trip up the parsing. You'll end up with queries called `Anonymous` if that happens
const state = {
parenLevel: 0,
cteStart: -1,
}
const replacements: Array<{start: number; end: number; text: string}> = []
for (let i = 0; i < sql.length; i++) {
const prev = sql.slice(0, i).replace(/\s+/, ' ').trim()
if (sql[i] === '(') {
state.parenLevel++
if (prev.endsWith(' as')) {
if (state.parenLevel === 1) {
state.cteStart = i
}
}
}
if (sql[i] === ')') {
state.parenLevel--
if (state.parenLevel === 0 && state.cteStart > -1) {
replacements.push({start: state.cteStart + 1, end: i, text: 'select 1'})
state.cteStart = -1
}
}
}
const newSql = replacements.reduceRight(
(acc, rep) => acc.slice(0, rep.start) + rep.text + acc.slice(rep.end),
sql,
)
return parseWithWorkarounds(newSql, attemptsLeft - 1)
}
throw e
}
}
interface ModifiedAST {
modifications: ('cte' | 'returning')[]
ast: pgsqlAST.Statement
}
const astToSelect = ({modifications, ast}: ModifiedAST): ModifiedAST => {
if ((ast.type === 'update' || ast.type === 'insert' || ast.type === 'delete') && ast.returning) {
return {
modifications: [...modifications, 'returning'],
ast: {
type: 'select',
from: [
{
type: 'table',
name: {
name: ast.type === 'update' ? ast.table.name : ast.type === 'insert' ? ast.into.name : ast.from.name,
},
},
],
columns: ast.returning,
},
}
}
if (ast.type === 'with') {
return astToSelect({
modifications: [...modifications, 'cte'],
ast: ast.in,
})
}
return {modifications, ast}
}
/**
* Get tables and columns used in a sql query. Not complete; optimistic. Useful for getting a (non-unique)
* name that can be used to refer to queries.
*/
export const sqlTablesAndColumns = (sql: string): {tables?: string[]; columns?: string[]} => {
const ast = getHopefullyViewableAST(sql)
if (ast.type === 'select') {
return {
tables: ast.from
?.map(f =>
match(f)
.case({alias: {name: String}}, f => f.alias.name)
.case({type: 'table'} as const, t => t.name.name)
.default(() => '') // filtered out below
.get(),
)
.filter(Boolean),
columns: lodash
.chain(ast.columns)
.map(c => c.alias?.name || expressionName(c.expr))
.compact()
.value(),
}
}
return {}
}
const expressionName = (ex: pgsqlAST.Expr): string | undefined => {
return match(ex)
.case({type: 'ref' as const}, e => e.name)
.case({type: 'call', function: {name: String}} as const, e => e.function.name)
.case({type: 'cast'} as const, e => expressionName(e.operand))
.default(() => undefined)
.get()
}
/**
* This analyses an AST statement, and tries to find the table name and column name the query column could possibly correspond to.
* It doesn't try to understand every possible kind of postgres statement, so for very complicated queries it will return a long
* list of `tablesColumnCouldBeFrom`. For simple queries like `select id from messages` it'll get sensible results, though, and those
* results can be used to look for non-nullability of columns.
*/
export const aliasMappings = (
statement: pgsqlAST.Statement,
): Array<{queryColumn: string; aliasFor: string; tablesColumnCouldBeFrom: string[]; hasNullableJoin: boolean}> => {
assert.strictEqual(statement.type, 'select' as const)
assert.ok(statement.columns, `Can't get alias mappings from query with no columns`)
interface QueryTableReference {
table: string
referredToAs: string
}
const allTableReferences: QueryTableReference[] = []
const nullableJoins: string[] = []
pgsqlAST
.astVisitor(map => ({
tableRef: t =>
allTableReferences.push({
table: t.name,
referredToAs: t.alias || t.name,
}),
join: t => {
const markNullable = (ref: pgsqlAST.Expr) =>
ref.type === 'ref' && ref.table?.name && nullableJoins.push(ref.table.name)
if (t.type === 'LEFT JOIN' && t.on && t.on.type === 'binary') {
markNullable(t.on.right)
}
if (t.type === 'FULL JOIN' && t.on?.type === 'binary') {
markNullable(t.on.left)
markNullable(t.on.right)
}
return map.super().join(t)
},
}))
.statement(statement)
const availableTables = lodash.uniqBy(allTableReferences, JSON.stringify)
const aliasGroups = lodash.groupBy(availableTables, t => t.referredToAs)
assert.ok(
!lodash.some(aliasGroups, group => group.length > 1),
`Some aliases are duplicated, this is too confusing. ${JSON.stringify({aliasGroups})}`,
)
const mappings = statement.columns
.map(c => {
const tableReferences = availableTables.filter(t =>
c.expr.type === 'ref' && c.expr.table ? c.expr.table.name === t.referredToAs : true,
)
return {
queryColumn: c.alias?.name,
aliasFor: c.expr.type === 'ref' ? c.expr.name : '',
tablesColumnCouldBeFrom: tableReferences.map(t => t.table),
hasNullableJoin: c.expr.type === 'ref' && !!c.expr.table?.name && nullableJoins.includes(c.expr.table.name),
}
})
.map(c => ({...c, queryColumn: c.queryColumn || c.aliasFor}))
.filter(c => c.queryColumn && c.aliasFor)
return mappings
}
export const suggestedTags = ({tables, columns}: ReturnType<typeof sqlTablesAndColumns>): string[] => {
if (!columns) {
return ['_void']
}
const tablesInvolved = (tables || []).map(pascalCase).map(pluralize.singular).join('_')
return lodash
.uniq([
tablesInvolved, // e.g. User_Role
[tablesInvolved, ...columns.map(lodash.camelCase)].filter(Boolean).join('_'), // e.g. User_Role_id_name_roleId
])
.map(lodash.upperFirst)
.filter(Boolean)
}
export const getHopefullyViewableAST = lodash.flow(getModifiedAST, m => m.ast)
export const isCTE = lodash.flow(templateToValidSql, getModifiedAST, m => m.modifications.includes('cte'))
export const getSuggestedTags = lodash.flow(templateToValidSql, sqlTablesAndColumns, suggestedTags)
export const getViewFriendlySql = lodash.flow(templateToValidSql, getHopefullyViewableAST, pgsqlAST.toSql.statement)
export const getAliasMappings = lodash.flow(getHopefullyViewableAST, aliasMappings)
export const removeSimpleComments = (sql: string) =>
sql
.split('\n')
.map(line => (line.trim().startsWith('--') ? '' : line))
.join('\n')
export const simplifySql = lodash.flow(pgsqlAST.parseFirst, pgsqlAST.toSql.statement)
/* istanbul ignore if */
if (require.main === module) {
console.log = (...x: any[]) => console.dir(x.length === 1 ? x[0] : x, {depth: null})
console.log(getHopefullyViewableAST('select other.content as id from messages join other on shit = id where id = 1'))
// console.log(isUntypable([`select * from `, ` where b = hi`]))
// console.log(isUntypable([`select * from a where b = `, ``]))
// console.log(
// isUntypeable([
// '\n' + ' insert into test_table(id, n) values (1, 2);\n' + ' insert into test_table(id, n) values (3, 4);\n',
// ]),
// )
const exprName = (e: pgsqlAST.Expr) => {
if ('name' in e && typeof e.name === 'string') {
return e.name
}
return null
}
const opNames: Record<pgsqlAST.BinaryOperator, string | null> = {
'!=': 'ne',
'#-': null,
'%': 'modulo',
'&&': null,
'*': 'times',
'+': 'plus',
'-': 'minus',
'/': 'divided_by',
'<': 'less_than',
'<=': 'lte',
'<@': null,
'=': 'equals',
'>': 'greater_than',
'>=': 'gte',
'?': null,
'?&': null,
'?|': null,
'@>': null,
'NOT ILIKE': 'not_ilike',
'NOT IN': 'not_in',
'NOT LIKE': 'not_like',
'^': 'to_the_power_of',
'||': 'concat',
AND: 'and',
ILIKE: 'ilike',
IN: 'in',
LIKE: 'like',
OR: 'or',
'#>>': 'json_obj_from_path_text',
'&': 'binary_and',
'|': 'binary_or',
'~': 'binary_ones_complement',
'<<': 'binary_left_shift',
'>>': 'binary_right_shift',
'#': 'bitwise_xor',
}
// console.log(`
// select *
// from a
// join top_x(1, 2) as p on b = c
// `)
// throw 'end'
console.log(
lodash.flow(
//
getSuggestedTags,
)([require('./testquery.ignoreme').default]),
)
throw 'end'
pgsqlAST
.astVisitor(map => ({
expr: e => {
const grandChildren =
// Object.values(e) ||
Object.values(e).flatMap(child =>
// [child] || //
child && typeof child === 'object' ? Object.values(child) : [],
)
console.log({e, grandChildren})
if (grandChildren.some(e => JSON.stringify(e).startsWith('{"type":"parameter'))) {
}
console.log(pgsqlAST.toSql.statement(getHopefullyViewableAST('select id from messages where id <= $1')), 444555)
// console.log({e})
// if (Object.values(e).some(v => JSON.stringify(v).startsWith(`{"type":"parameter"`))) {
// console.log(112)
// if (e.type === 'binary') {
// const params = [e.left, e.right].filter(
// (side): side is pgsqlAST.ExprParameter => side.type === 'parameter',
// )
// params.forEach(p => {
// const names = [e.left, e.right].map(exprName)
// console.log(112, {names})
// if (names.every(Boolean) && opNames[e.op]) {
// console.log({
// param: p.name,
// readable: names.join(`_${opNames[e.op]}_`),
// orig: pgsqlAST.toSql.expr(e),
// })
// }
// })
// }
// }
return map.super().expr(e)
},
// parameter: e => ({type: 'ref', name: 'SPLITTABLE'}),
}))
.statement(getHopefullyViewableAST('select id from messages where id <= $1'))!
console.log(getHopefullyViewableAST(`select * from test_table where id = 'placeholder_parameter_$1' or id = 'other'`))
pgsqlAST
.astVisitor(map => ({
constant: t => {
console.log({t}, map.super())
return map.super().constant(t)
},
}))
.statement(
getHopefullyViewableAST(`select * from test_table where id = 'placeholder_parameter_$1' or id = 'other'`),
)
console.log(
getHopefullyViewableAST(
'SELECT "t1"."id" FROM "test_table" AS "t1" INNER JOIN "test_table" AS "t2" ON ("t1"."id" = "t2"."n")',
),
)
console.log(getHopefullyViewableAST('select t1.id from test_table t1 join test_table t2 on t1.id = t2.n'))
console.log(aliasMappings(getHopefullyViewableAST(`select a.a, b.b from atable a join btable b on a.i = b.j`)))
console.log(getHopefullyViewableAST(`select * from (select id from test) d`))
console.log(getHopefullyViewableAST(`select * from (values (1, 'one'), (2, 'two')) as vals (num, letter)`))
console.log(
pgsqlAST
.astVisitor(map => ({
tableRef: t => console.log({table: t.name, referredToAs: t.alias || t.name}),
join: t => map.super().join(t),
}))
.statement(getHopefullyViewableAST('select 1 from (select * from t)')),
)
console.log(
getHopefullyViewableAST(
`select * from (values (1, 'one'), (2, 'two')) as vals (num, letter)` ||
`drop table test` ||
`
BEGIN
SELECT * INTO STRICT myrec FROM emp WHERE empname = myname;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE EXCEPTION 'employee % not found', myname;
WHEN TOO_MANY_ROWS THEN
RAISE EXCEPTION 'employee % not unique', myname;
END
`,
),
)
console.log(lodash.flow(getHopefullyViewableAST, aliasMappings)('select * from messages where id = 1'))
// console.dir(suggestedTags(parse('insert into foo(id) values (1) returning id, date')), {depth: null})
// console.dir(suggestedTags(parse('insert into foo(id) values (1) returning id, date')), {depth: null})
console.log(
sqlTablesAndColumns('select pt.typname, foo.bar::regtype from pg_type as pt join foo on pg_type.id = foo.oid'),
)
// console.dir(suggestedTags(parse('select foo::regtype from foo')), {depth: null})
// console.dir(suggestedTags(parse('select i, j from a join b on 1=1')), {depth: null})
console.dir(suggestedTags(sqlTablesAndColumns(`select count(*), * from foo where y = null`)), {depth: null})
console.dir(suggestedTags(sqlTablesAndColumns(`select pg_advisory_lock(123), x, y from foo`)), {depth: null})
console.dir(suggestedTags(sqlTablesAndColumns(`insert into foo(id) values (1) returning *`)), {depth: null})
console.dir(suggestedTags(sqlTablesAndColumns(`insert into foo(id) values (1)`)), {depth: null})
console.dir(suggestedTags(sqlTablesAndColumns(`update foo set bar = 'baz' returning *`)), {depth: null})
console.dir(suggestedTags(sqlTablesAndColumns(`select foo.x from foo where y = null`)), {depth: null})
} | the_stack |
import util from 'util';
import {CreateChannelParams, Participant} from '@statechannels/client-api-schema';
import {hexZeroPad} from 'ethers/lib/utils';
import yargs from 'yargs';
import {hideBin} from 'yargs/helpers';
import * as jsonfile from 'jsonfile';
import chalk from 'chalk';
import {generateSlug} from 'random-word-slugs';
import _ from 'lodash';
import {BigNumber, ethers} from 'ethers';
import ms from 'ms';
import {zeroAddress} from '@statechannels/wallet-core/src/config';
import {COUNTING_APP_DEFINITION} from '../../src/models/__test__/fixtures/app-bytecode';
import {FundingInfo, RoleConfig, Step} from '../types';
import {setupUnhandledErrorListeners} from '../utils';
// We want to create all the ledger channels in the first 5 seconds.
const MAX_CREATE_LEDGER_TIME = ms('5 seconds');
setupUnhandledErrorListeners();
createLoad();
async function createLoad() {
const {
createRate,
prettyOutput,
roleFile,
outputFile,
closeRate,
duration,
closeDelay,
fundingStrategy,
ledgerDelay,
amountOfLedgerChannels,
} = await yargs(hideBin(process.argv))
.option('prettyOutput', {
default: true,
type: 'boolean',
describe: 'Whether the output is formatted nicely with spaces.',
})
.option('outputFile', {
alias: 'o',
description: 'The file to write the generated load to.',
default: 'temp/test_load.json',
})
.option('roleFile', {
alias: 'rf',
describe: 'The path to a file containing the role information.',
default: './e2e-testing/test-data/roles.json',
})
.option('fundingStrategy', {
alias: 'f',
describe: 'Whether application channels are funded directly or by ledger channels.',
choices: ['Ledger', 'Direct'],
demandOption: true,
})
.option('duration', {
alias: 'd',
min: 10,
default: 60,
describe: `The amount of time (in seconds) that the load should run for. Steps will be generated with a timestamp such that step.timestamp <= duration.`,
})
.option('createRate', {
alias: 'cr',
min: 1,
default: 1,
describe: 'The number of channels that should be created per a second.',
})
.option('amountOfLedgerChannels', {
alias: 'l',
default: 1,
describe: `The number of ledger channels that will be created and used for funding.`,
})
.option('ledgerDelay', {
default: 20,
min: 0,
describe: `The minumum amount of time (in seconds) to wait before attempting to use a ledger channel. This is used to prevent using a ledger channel that has not finished being funded.`,
})
.option('closeDelay', {
default: 5,
min: 0,
describe: `The minumum amount of time (in seconds) to wait before closing a channel. This is used to prevent closing a channel that has not finished being funded.`,
})
.option('closeRate', {
default: 0,
min: 0,
describe:
'The amount of channels to be closed per a second. If this is larger than the createRate then all channels will eventually get closed. Otherwise, some channels will remain open.',
}).argv;
const roles = (await jsonfile.readFile(roleFile)) as Record<string, RoleConfig>;
console.log(chalk.whiteBright(`Generating a test load file to ${outputFile}`));
console.log(
chalk.whiteBright(
`Using the following options ${util.inspect({
outputFile,
roleFile,
duration,
createRate,
closeRate,
closeDelay,
fundingStrategy,
})}`
)
);
if (fundingStrategy === 'Ledger') {
console.log(
chalk.whiteBright(
`Ledger options ${util.inspect({
ledgerDelay,
amountOfLedgerChannels,
})}`
)
);
}
console.log(chalk.whiteBright(`${createRate * duration} channels will be created.`));
console.log(
chalk.whiteBright(
`${
closeRate * duration > 0 ? closeRate * duration : 'None'
} of those channels will be closed.`
)
);
if (closeRate >= createRate) {
console.log(
chalk.yellow(
'The close rate is equal to or larger than the create rate! All channels will end up closed!'
)
);
}
let steps: Step[] = [];
if (fundingStrategy === 'Ledger') {
steps = generateCreateLedgerSteps(amountOfLedgerChannels, duration, roles);
}
steps = generateCreateSteps(
createRate,
duration,
roles,
fundingStrategy === 'Ledger' ? {type: 'Ledger', ledgerDelay} : {type: 'Direct'},
steps
);
steps = generateCloseSteps(closeRate, duration, closeDelay, steps);
await jsonfile.writeFile(outputFile, steps, {spaces: prettyOutput ? 1 : 0});
console.log(chalk.greenBright(`Complete!`));
}
function generateCreateLedgerSteps(
amountOfLedgerChannels: number,
duration: number,
roles: Record<string, RoleConfig>
): Step[] {
const steps: Step[] = [];
_.times(amountOfLedgerChannels, () => {
const timestamp = generateRandomInteger(0, MAX_CREATE_LEDGER_TIME);
const startIndex = generateRandomInteger(0, Object.keys(roles).length - 1);
const participants = generateParticipants(roles, startIndex);
// Generate a jobId that is 4 random words
const jobId = generateSlug(4);
steps.push({
type: 'CreateLedgerChannel',
jobId,
serverId: participants[0].participantId,
timestamp,
// We want well funded ledger channels
ledgerChannelParams: generateChannelParams(participants, 100_000),
});
});
return steps;
}
function generateCloseSteps(
closeRate: number,
duration: number,
closeDelay: number,
previousSteps: Readonly<Step[]>
): Step[] {
// TODO: We cast this so we can mutate the cloned array
const steps = _.clone(previousSteps) as Step[];
if (closeRate > 0) {
_.times(closeRate * duration, () => {
const createStep = getRandomJobToClose(steps);
if (createStep) {
// We want a close timestamp that occurs at least closeDelay time after the create time
const timestamp = Math.max(
generateRandomInteger(createStep.timestamp, toMilliseconds(duration)),
createStep.timestamp + toMilliseconds(closeDelay)
);
steps.push({
type: 'CloseChannel',
jobId: createStep.jobId,
serverId: createStep.serverId,
timestamp,
});
}
});
}
return steps;
}
function generateCreateSteps(
createRate: number,
duration: number,
roles: Record<string, RoleConfig>,
funding: {type: 'Ledger'; ledgerDelay: number} | {type: 'Direct'},
previousSteps: readonly Step[]
): Step[] {
const steps = _.clone(previousSteps) as Step[];
const ledgerSteps = steps.filter(s => s.type === 'CreateLedgerChannel');
_.times(createRate * duration, () => {
const startIndex = generateRandomInteger(0, Object.keys(roles).length - 1);
// Due to https://github.com/statechannels/statechannels/issues/3652 we'll run into duplicate channelIds if we use the same constants.
// For now we re-order the participants based on who is creating the channel.
const participants = generateParticipants(roles, startIndex);
// Generate a jobId that is 4 random words
const jobId = generateSlug(4);
let timestamp;
let fundingInfo: FundingInfo;
if (funding.type === 'Ledger') {
const ledgerToUse = getRandomElement(ledgerSteps);
// We want to wait ledgerDelay before attempting to use the ledger channel
timestamp = generateRandomInteger(
ledgerToUse.timestamp + funding.ledgerDelay,
toMilliseconds(duration)
);
fundingInfo = {type: 'Ledger', fundingLedgerJob: ledgerToUse.jobId};
} else {
timestamp = generateRandomInteger(0, toMilliseconds(duration));
fundingInfo = {type: 'Direct'};
}
steps.push({
type: 'CreateChannel',
jobId,
serverId: participants[0].participantId,
timestamp,
// We want a well funded ledger channel
channelParams: generateChannelParams(participants),
fundingInfo,
});
});
return steps;
}
/**
* Generates a random integer from [min,max]
* @param min The minimum possible value that can be generated
* @param max The maximum possible value that can be generated
* @returns The generated number
*/
function generateRandomInteger(min: number, max: number): number {
return Math.floor(Math.random() * (max - min + 1) + min);
}
/**
* Generates participants based on roles. Uses the startIndex to determine the order of the participants.
* This may no longer be needed after https://github.com/statechannels/statechannels/issues/3652
* @param roles The record containing role configs
* @param startIndex The index of the role we should start at
* @returns A collection of participants
*/
function generateParticipants(roles: Record<string, RoleConfig>, startIndex: number) {
// Flatten out the Record into a simple array
const roleArray = Object.keys(roles).map(rId => ({roleId: rId, ...roles[rId]}));
const participants: Participant[] = [];
// We iterate through the role array starting at start index and add the role to the participants
for (let i = 0; i < roleArray.length; i++) {
const role = roleArray[(i + startIndex) % roleArray.length];
const {address: signingAddress} = new ethers.Wallet(role.privateKey);
const destination = hexZeroPad(role.destination, 32);
participants.push({signingAddress, participantId: role.roleId, destination});
}
return participants;
}
/**
* Creates channel parameters based on the provided participants.
* @param participants The participants for the channel.
* @param fundingAmountPerParticipant The amount of funding each participant has. Defaults to 5.
* @returns A CreateChannelParams object (omitting the fundingStrategy)
*/
function generateChannelParams(
participants: Participant[],
fundingAmountPerParticipant = 5
): Omit<CreateChannelParams, 'fundingStrategy'> {
// Eventually these should vary
const allocationItems = participants.map(p => ({
destination: p.destination,
amount: BigNumber.from(fundingAmountPerParticipant).toHexString(),
}));
return {
participants,
allocations: [
{
allocationItems,
asset: zeroAddress,
},
],
appDefinition: COUNTING_APP_DEFINITION,
appData: '0x',
challengeDuration: ms('1d') / 1000, // This is 1 day in seconds,
};
}
/**
* Converts seconds to milliseconds
*/
function toMilliseconds(seconds: number): number {
return seconds * 1000;
}
function getRandomElement<T>(array: Array<T>): T {
const index = generateRandomInteger(0, array.length - 1);
return array[index];
}
/**
* Gets a random job that doesn't already have a close step scheduled
*/
function getRandomJobToClose(
steps: readonly Step[]
): Pick<Step, 'jobId' | 'timestamp' | 'serverId'> | undefined {
const jobsAlreadyWithClose = steps.filter(s => s.type === 'CloseChannel').map(s => s.jobId);
// We only want jobs that don't have a close channel step yet
const filtered = steps.filter(
s => s.type === 'CreateChannel' && !jobsAlreadyWithClose.includes(s.jobId)
);
const index = generateRandomInteger(0, filtered.length - 1);
return filtered[index];
} | the_stack |
describe('panel: <uif-panel />', () => {
beforeEach(() => {
angular.mock.module('officeuifabric.core');
angular.mock.module('officeuifabric.components.panel');
});
describe('Basic Tests', () => {
let panel: JQuery;
let $scope: any;
afterEach(() => {
this.$timeoutservice.verifyNoPendingTasks();
});
beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function, $timeout: angular.ITimeoutService) => {
$scope = $rootScope;
this.$timeoutservice = $timeout;
$scope.isOpen = true;
panel = $compile(`<uif-panel uif-type="small" uif-is-open="isOpen" uif-show-overlay="true" uif-show-close="true">
<uif-panel-header>Header</uif-panel-header>
<uif-content>
<span class="ms-font-m">Place your content in here!</span>
</uif-content>
</uif-panel>
`)($scope);
$scope.$digest();
$('body').append(panel);
panel = jQuery(panel[0]);
}));
it('should render correct html', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
expect(panel).toHaveClass('ms-Panel');
expect(panel.find('div.ms-Overlay').length).toBe(1);
expect(panel.find('div.ms-Panel-main').length).toBe(1);
expect(panel.find('div.ms-Panel-commands').length).toBe(1);
this.$timeoutservice.flush();
}));
it('should test for incorrect open value', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
$scope.isOpen = 'stringvalue';
$rootScope.$digest();
this.$timeoutservice.flush();
// test to ensure code coverage
expect(panel).toHaveClass('ms-Panel');
}));
it('should allow the panel to be opened', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
$scope.isOpen = true;
$rootScope.$digest();
this.$timeoutservice.flush();
expect(panel).toHaveClass('is-open');
}));
it('should allow the panel to be closed', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
$scope.isOpen = true;
$rootScope.$digest();
this.$timeoutservice.flush();
expect(panel).toHaveClass('is-open');
$scope.isOpen = false;
$rootScope.$digest();
this.$timeoutservice.flush();
expect(panel).not.toHaveClass('is-open');
}));
it('close button should close the panel', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
$scope.isOpen = true;
$rootScope.$digest();
expect(panel).toHaveClass('is-open');
// close the panel by pressing the button
panel.find('.ms-Panel-closeButton').trigger('click');
$rootScope.$digest();
this.$timeoutservice.flush();
expect($scope.isOpen).toEqual(false);
}));
it('close button should not trigger submit', () => {
let closeButton: JQuery = panel.find('.ms-Panel-closeButton');
this.$timeoutservice.flush();
expect(closeButton).toHaveAttr('type', 'button');
});
it(
'clicking on the Overlay should not close the panel when no value is supplied to uif-is-light-dismiss',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
$scope.isOpen = true;
$rootScope.$digest();
expect(panel).toHaveClass('is-open');
// attempt to close the panel by clicking on the background overlay
panel.find('.ms-Overlay.ms-Overlay--dark').trigger('click');
$rootScope.$digest();
this.$timeoutservice.flush();
expect($scope.isOpen).toEqual(true);
}));
});
describe('Tests for uif-is-light-dismiss attribute boolean value', () => {
let panel: JQuery;
let $scope: any;
afterEach(() => {
this.$timeoutservice.verifyNoPendingTasks();
});
beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function, $timeout: angular.ITimeoutService) => {
$scope = $rootScope;
this.$timeoutservice = $timeout;
$scope.isOpen = true;
$scope.isLightDismiss = false;
panel = $compile(`<uif-panel uif-type="small" uif-is-open="isOpen" uif-show-overlay="true" uif-show-close="true"
uif-is-light-dismiss="isLightDismiss">
<uif-panel-header>Header</uif-panel-header>
<uif-content>
<span class="ms-font-m">Place your content in here!</span>
</uif-content>
</uif-panel>
`)($scope);
$scope.$digest();
$('body').append(panel);
panel = jQuery(panel[0]);
}));
it(
'clicking on the Overlay should not close the panel when uif-is-light-dismiss is false',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
$scope.isOpen = true;
$rootScope.$digest();
expect(panel).toHaveClass('is-open');
// attempt to close the panel by clicking on the background overlay
panel.find('.ms-Overlay.ms-Overlay--dark').trigger('click');
$rootScope.$digest();
this.$timeoutservice.flush();
expect($scope.isOpen).toEqual(true);
}));
it(
'clicking on the Overlay should close the panel when uif-is-light-dismiss is true',
inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
$scope.isOpen = true;
$scope.isLightDismiss = true;
$rootScope.$digest();
expect(panel).toHaveClass('is-open');
// attempt to close the panel by clicking on the background overlay
panel.find('.ms-Overlay.ms-Overlay--dark').trigger('click');
$rootScope.$digest();
this.$timeoutservice.flush();
expect($scope.isOpen).toEqual(false);
}));
});
describe('Command bar is placed correctly', () => {
let panel: JQuery;
let $scope: any;
beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => {
$scope = $rootScope;
panel = $compile(`
<uif-panel uif-is-open="isOpen" uif-show-overlay="true" uif-show-close="true">
<uif-command-bar uif-search-term="searchValue" placeholder="Search here...">
<uif-command-bar-main uif-show-overflow='true'>
<uif-command-bar-item>
<uif-icon uif-type="save"></uif-icon>
<span class='ms-font-s'>Save</span>
</uif-command-bar-item>
<uif-command-bar-item>
<uif-icon uif-type="x"></uif-icon>
<span class='ms-font-s'>Cancel</span>
</uif-command-bar-item>
</uif-command-bar-main>
</uif-command-bar>
<uif-panel-header>Header</uif-panel-header>
<uif-content>
<span class="ms-font-m">Place your content in here!</span>
</uif-content>
</uif-panel>
`)($scope);
$scope.$digest();
$('body').append(panel);
panel = jQuery(panel[0]);
}));
it('should render correct html', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
expect(panel.find('div.ms-CommandBar').length).toBe(1);
}));
it('should allow the panel to be opened & show the commandbar', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
$scope.isOpen = true;
$rootScope.$digest();
expect(panel).toHaveClass('is-open');
expect(panel.find('div.ms-CommandBarItem')[0]).not.toHaveClass('is-hidden');
}));
});
describe('Ensure default is applied when no uif-type is supplied', () => {
let panel: JQuery;
let $scope: any;
beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => {
$scope = $rootScope;
panel = $compile(`
<uif-panel uif-is-open="vm.isOpen1" uif-show-overlay="true" uif-show-close="true">
<uif-panel-header>Header</uif-panel-header>
<uif-content>
<span class="ms-font-m">Place your content in here!</span>
</uif-content>
</uif-panel>
`)($scope);
$scope.$digest();
$('body').append(panel);
panel = jQuery(panel[0]);
}));
it('should render correct html', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
expect(panel).toHaveClass('ms-Panel');
expect(panel).toHaveClass('ms-Panel--md');
}));
});
describe('Left panel renders', () => {
let panel: JQuery;
let $scope: any;
beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => {
$scope = $rootScope;
panel = $compile(`
<uif-panel uif-type="left" uif-is-open="vm.isOpen1" uif-show-overlay="true" uif-show-close="true">
<uif-panel-header>Header</uif-panel-header>
<uif-content>
<span class="ms-font-m">Place your content in here!</span>
</uif-content>
</uif-panel>
`)($scope);
$scope.$digest();
$('body').append(panel);
panel = jQuery(panel[0]);
}));
it('should render correct html', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
expect(panel).toHaveClass('ms-Panel');
expect(panel).toHaveClass('ms-Panel--left');
}));
});
describe('Handles incorrect panel types', () => {
let panel: JQuery;
let $scope: any;
beforeEach(inject(($rootScope: angular.IRootScopeService, $compile: Function) => {
$scope = $rootScope;
panel = $compile(`
<uif-panel uif-type="invalid" uif-is-open="vm.isOpen1" uif-show-overlay="true" uif-show-close="true">
<uif-panel-header>Header</uif-panel-header>
<uif-content>
<span class="ms-font-m">Place your content in here!</span>
</uif-content>
</uif-panel>
`)($scope);
$scope.$digest();
$('body').append(panel);
panel = jQuery(panel[0]);
}));
it('should render correct html', inject(($compile: Function, $rootScope: angular.IRootScopeService) => {
expect(panel).toHaveClass('ms-Panel');
// default to medium
expect(panel).toHaveClass('ms-Panel--md');
}));
});
}); | the_stack |
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/
class MersenneTwister {
private N: number;
private M: number;
private MATRIX_A: number;
private UPPER_MASK: number;
private LOWER_MASK: number;
private mt: number[];
private mti: number;
constructor(seed: number) {
if (seed === undefined) {
// kept random number same size as time used previously to ensure no unexpected results downstream
seed = Math.floor(Math.random() * Math.pow(10, 13));
}
/* Period parameters */
this.N = 624;
this.M = 397;
this.MATRIX_A = 0x9908b0df; /* constant vector a */
this.UPPER_MASK = 0x80000000; /* most significant w-r bits */
this.LOWER_MASK = 0x7fffffff; /* least significant r bits */
this.mt = new Array(this.N); /* the array for the state vector */
this.mti = this.N + 1; /* mti==N + 1 means mt[N] is not initialized */
this.init_genrand(seed);
}
/* initializes mt[N] with a seed */
private init_genrand(s: number) {
this.mt[0] = s >>> 0;
for (this.mti = 1; this.mti < this.N; this.mti++) {
s = this.mt[this.mti - 1] ^ (this.mt[this.mti - 1] >>> 30);
this.mt[this.mti] =
((((s & 0xffff0000) >>> 16) * 1812433253) << 16) + (s & 0x0000ffff) * 1812433253 + this.mti;
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
/* In the previous versions, MSBs of the seed affect */
/* only MSBs of the array mt[]. */
/* 2002/01/09 modified by Makoto Matsumoto */
this.mt[this.mti] >>>= 0;
/* for >32 bit machines */
}
}
/* generates a random number on [0,0xffffffff]-interval */
private genrand_int32() {
let y;
let mag01 = new Array(0x0, this.MATRIX_A);
/* mag01[x] = x * MATRIX_A for x=0,1 */
if (this.mti >= this.N) {
/* generate N words at one time */
let kk;
if (this.mti === this.N + 1) {
/* if init_genrand() has not been called, */
this.init_genrand(5489); /* a default initial seed is used */
}
for (kk = 0; kk < this.N - this.M; kk++) {
y = (this.mt[kk] & this.UPPER_MASK) | (this.mt[kk + 1] & this.LOWER_MASK);
this.mt[kk] = this.mt[kk + this.M] ^ (y >>> 1) ^ mag01[y & 0x1];
}
for (; kk < this.N - 1; kk++) {
y = (this.mt[kk] & this.UPPER_MASK) | (this.mt[kk + 1] & this.LOWER_MASK);
this.mt[kk] = this.mt[kk + (this.M - this.N)] ^ (y >>> 1) ^ mag01[y & 0x1];
}
y = (this.mt[this.N - 1] & this.UPPER_MASK) | (this.mt[0] & this.LOWER_MASK);
this.mt[this.N - 1] = this.mt[this.M - 1] ^ (y >>> 1) ^ mag01[y & 0x1];
this.mti = 0;
}
y = this.mt[this.mti++];
/* Tempering */
y ^= y >>> 11;
y ^= (y << 7) & 0x9d2c5680;
y ^= (y << 15) & 0xefc60000;
y ^= y >>> 18;
return y >>> 0;
}
/* generates a random number on [0,1)-real-interval */
random() {
return this.genrand_int32() * (1.0 / 4294967296.0);
/* divided by 2^32 */
}
}
// https://github.com/chancejs/chancejs
export class Chance {
private mt: MersenneTwister;
constructor(readonly seed: number) {
// If no generator function was provided, use our MT
this.mt = new MersenneTwister(this.seed);
}
random(): number {
return this.mt.random();
}
/**
* Return a random integer
*
* NOTE the max and min are INCLUDED in the range. So:
* chance.integer({min: 1, max: 3});
* would return either 1, 2, or 3.
*
* @param {Object} [options={}] can specify a min and/or max
* @returns {Number} a single random integer number
* @throws {RangeError} min cannot be greater than max
*/
integer(options: { min: number; max: number }): number {
return Math.floor(this.random() * (options.max - options.min + 1) + options.min);
}
/**
* Return a random natural
*
* NOTE the max and min are INCLUDED in the range. So:
* chance.natural({min: 1, max: 3});
* would return either 1, 2, or 3.
*
* @param {Object} [options={}] can specify a min and/or maxm or a numerals count.
* @returns {Number} a single random integer number
* @throws {RangeError} min cannot be greater than max
*/
natural(options: { max: number }): number {
return this.integer({ min: 0, max: options.max });
}
pick<T>(arr: T[]): T {
if (arr.length === 0) {
throw new RangeError("Chance: Cannot pick() from an empty array");
}
return arr[this.natural({ max: arr.length - 1 })];
}
animal(): string {
// if user does not put in any animal type, will return a random animal regardless
const animalTypeArray = ["desert", "forest", "ocean", "zoo", "farm", "pet", "grassland"];
return this.pick(animals[this.pick(animalTypeArray)]);
}
city(): string {
return this.pick(cities);
}
}
const animals: { [kind: string]: string[] } = {
// list of ocean animals comes from https://owlcation.com/stem/list-of-ocean-animals
ocean: [
"Acantharea",
"Anemone",
"Angelfish King",
"Ahi Tuna",
"Albacore",
"American Oyster",
"Anchovy",
"Armored Snail",
"Arctic Char",
"Atlantic Bluefin Tuna",
"Atlantic Cod",
"Atlantic Goliath Grouper",
"Atlantic Trumpetfish",
"Atlantic Wolffish",
"Baleen Whale",
"Banded Butterflyfish",
"Banded Coral Shrimp",
"Banded Sea Krait",
"Barnacle",
"Barndoor Skate",
"Barracuda",
"Basking Shark",
"Bass",
"Beluga Whale",
"Bluebanded Goby",
"Bluehead Wrasse",
"Bluefish",
"Bluestreak Cleaner-Wrasse",
"Blue Marlin",
"Blue Shark",
"Blue Spiny Lobster",
"Blue Tang",
"Blue Whale",
"Broadclub Cuttlefish",
"Bull Shark",
"Chambered Nautilus",
"Chilean Basket Star",
"Chilean Jack Mackerel",
"Chinook Salmon",
"Christmas Tree Worm",
"Clam",
"Clown Anemonefish",
"Clown Triggerfish",
"Cod",
"Coelacanth",
"Cockscomb Cup Coral",
"Common Fangtooth",
"Conch",
"Cookiecutter Shark",
"Copepod",
"Coral",
"Corydoras",
"Cownose Ray",
"Crab",
"Crown-of-Thorns Starfish",
"Cushion Star",
"Cuttlefish",
"California Sea Otters",
"Dolphin",
"Dolphinfish",
"Dory",
"Devil Fish",
"Dugong",
"Dumbo Octopus",
"Dungeness Crab",
"Eccentric Sand Dollar",
"Edible Sea Cucumber",
"Eel",
"Elephant Seal",
"Elkhorn Coral",
"Emperor Shrimp",
"Estuarine Crocodile",
"Fathead Sculpin",
"Fiddler Crab",
"Fin Whale",
"Flameback",
"Flamingo Tongue Snail",
"Flashlight Fish",
"Flatback Turtle",
"Flatfish",
"Flying Fish",
"Flounder",
"Fluke",
"French Angelfish",
"Frilled Shark",
"Fugu (also called Pufferfish)",
"Gar",
"Geoduck",
"Giant Barrel Sponge",
"Giant Caribbean Sea Anemone",
"Giant Clam",
"Giant Isopod",
"Giant Kingfish",
"Giant Oarfish",
"Giant Pacific Octopus",
"Giant Pyrosome",
"Giant Sea Star",
"Giant Squid",
"Glowing Sucker Octopus",
"Giant Tube Worm",
"Goblin Shark",
"Goosefish",
"Great White Shark",
"Greenland Shark",
"Grey Atlantic Seal",
"Grouper",
"Grunion",
"Guineafowl Puffer",
"Haddock",
"Hake",
"Halibut",
"Hammerhead Shark",
"Hapuka",
"Harbor Porpoise",
"Harbor Seal",
"Hatchetfish",
"Hawaiian Monk Seal",
"Hawksbill Turtle",
"Hector's Dolphin",
"Hermit Crab",
"Herring",
"Hoki",
"Horn Shark",
"Horseshoe Crab",
"Humpback Anglerfish",
"Humpback Whale",
"Icefish",
"Imperator Angelfish",
"Irukandji Jellyfish",
"Isopod",
"Ivory Bush Coral",
"Japanese Spider Crab",
"Jellyfish",
"John Dory",
"Juan Fernandez Fur Seal",
"Killer Whale",
"Kiwa Hirsuta",
"Krill",
"Lagoon Triggerfish",
"Lamprey",
"Leafy Seadragon",
"Leopard Seal",
"Limpet",
"Ling",
"Lionfish",
"Lions Mane Jellyfish",
"Lobe Coral",
"Lobster",
"Loggerhead Turtle",
"Longnose Sawshark",
"Longsnout Seahorse",
"Lophelia Coral",
"Marrus Orthocanna",
"Manatee",
"Manta Ray",
"Marlin",
"Megamouth Shark",
"Mexican Lookdown",
"Mimic Octopus",
"Moon Jelly",
"Mollusk",
"Monkfish",
"Moray Eel",
"Mullet",
"Mussel",
"Megaladon",
"Napoleon Wrasse",
"Nassau Grouper",
"Narwhal",
"Nautilus",
"Needlefish",
"Northern Seahorse",
"North Atlantic Right Whale",
"Northern Red Snapper",
"Norway Lobster",
"Nudibranch",
"Nurse Shark",
"Oarfish",
"Ocean Sunfish",
"Oceanic Whitetip Shark",
"Octopus",
"Olive Sea Snake",
"Orange Roughy",
"Ostracod",
"Otter",
"Oyster",
"Pacific Angelshark",
"Pacific Blackdragon",
"Pacific Halibut",
"Pacific Sardine",
"Pacific Sea Nettle Jellyfish",
"Pacific White Sided Dolphin",
"Pantropical Spotted Dolphin",
"Patagonian Toothfish",
"Peacock Mantis Shrimp",
"Pelagic Thresher Shark",
"Penguin",
"Peruvian Anchoveta",
"Pilchard",
"Pink Salmon",
"Pinniped",
"Plankton",
"Porpoise",
"Polar Bear",
"Portuguese Man o' War",
"Pycnogonid Sea Spider",
"Quahog",
"Queen Angelfish",
"Queen Conch",
"Queen Parrotfish",
"Queensland Grouper",
"Ragfish",
"Ratfish",
"Rattail Fish",
"Ray",
"Red Drum",
"Red King Crab",
"Ringed Seal",
"Risso's Dolphin",
"Ross Seals",
"Sablefish",
"Salmon",
"Sand Dollar",
"Sandbar Shark",
"Sawfish",
"Sarcastic Fringehead",
"Scalloped Hammerhead Shark",
"Seahorse",
"Sea Cucumber",
"Sea Lion",
"Sea Urchin",
"Seal",
"Shark",
"Shortfin Mako Shark",
"Shovelnose Guitarfish",
"Shrimp",
"Silverside Fish",
"Skipjack Tuna",
"Slender Snipe Eel",
"Smalltooth Sawfish",
"Smelts",
"Sockeye Salmon",
"Southern Stingray",
"Sponge",
"Spotted Porcupinefish",
"Spotted Dolphin",
"Spotted Eagle Ray",
"Spotted Moray",
"Squid",
"Squidworm",
"Starfish",
"Stickleback",
"Stonefish",
"Stoplight Loosejaw",
"Sturgeon",
"Swordfish",
"Tan Bristlemouth",
"Tasseled Wobbegong",
"Terrible Claw Lobster",
"Threespot Damselfish",
"Tiger Prawn",
"Tiger Shark",
"Tilefish",
"Toadfish",
"Tropical Two-Wing Flyfish",
"Tuna",
"Umbrella Squid",
"Velvet Crab",
"Venus Flytrap Sea Anemone",
"Vigtorniella Worm",
"Viperfish",
"Vampire Squid",
"Vaquita",
"Wahoo",
"Walrus",
"West Indian Manatee",
"Whale",
"Whale Shark",
"Whiptail Gulper",
"White-Beaked Dolphin",
"White-Ring Garden Eel",
"White Shrimp",
"Wobbegong",
"Wrasse",
"Wreckfish",
"Xiphosura",
"Yellowtail Damselfish",
"Yelloweye Rockfish",
"Yellow Cup Black Coral",
"Yellow Tube Sponge",
"Yellowfin Tuna",
"Zebrashark",
"Zooplankton"
],
// list of desert, grassland, and forest animals comes from http://www.skyenimals.com/
desert: [
"Aardwolf",
"Addax",
"African Wild Ass",
"Ant",
"Antelope",
"Armadillo",
"Baboon",
"Badger",
"Bat",
"Bearded Dragon",
"Beetle",
"Bird",
"Black-footed Cat",
"Boa",
"Brown Bear",
"Bustard",
"Butterfly",
"Camel",
"Caracal",
"Caracara",
"Caterpillar",
"Centipede",
"Cheetah",
"Chipmunk",
"Chuckwalla",
"Climbing Mouse",
"Coati",
"Cobra",
"Cotton Rat",
"Cougar",
"Courser",
"Crane Fly",
"Crow",
"Dassie Rat",
"Dove",
"Dunnart",
"Eagle",
"Echidna",
"Elephant",
"Emu",
"Falcon",
"Fly",
"Fox",
"Frogmouth",
"Gecko",
"Geoffroy's Cat",
"Gerbil",
"Grasshopper",
"Guanaco",
"Gundi",
"Hamster",
"Hawk",
"Hedgehog",
"Hyena",
"Hyrax",
"Jackal",
"Kangaroo",
"Kangaroo Rat",
"Kestrel",
"Kowari",
"Kultarr",
"Leopard",
"Lion",
"Macaw",
"Meerkat",
"Mouse",
"Oryx",
"Ostrich",
"Owl",
"Pronghorn",
"Python",
"Rabbit",
"Raccoon",
"Rattlesnake",
"Rhinoceros",
"Sand Cat",
"Spectacled Bear",
"Spiny Mouse",
"Starling",
"Stick Bug",
"Tarantula",
"Tit",
"Toad",
"Tortoise",
"Tyrant Flycatcher",
"Viper",
"Vulture",
"Waxwing",
"Xerus",
"Zebra"
],
grassland: [
"Aardvark",
"Aardwolf",
"Accentor",
"African Buffalo",
"African Wild Dog",
"Alpaca",
"Anaconda",
"Ant",
"Anteater",
"Antelope",
"Armadillo",
"Baboon",
"Badger",
"Bandicoot",
"Barbet",
"Bat",
"Bee",
"Bee-eater",
"Beetle",
"Bird",
"Bison",
"Black-footed Cat",
"Black-footed Ferret",
"Bluebird",
"Boa",
"Bowerbird",
"Brown Bear",
"Bush Dog",
"Bushshrike",
"Bustard",
"Butterfly",
"Buzzard",
"Caracal",
"Caracara",
"Cardinal",
"Caterpillar",
"Cheetah",
"Chipmunk",
"Civet",
"Climbing Mouse",
"Clouded Leopard",
"Coati",
"Cobra",
"Cockatoo",
"Cockroach",
"Common Genet",
"Cotton Rat",
"Cougar",
"Courser",
"Coyote",
"Crane",
"Crane Fly",
"Cricket",
"Crow",
"Culpeo",
"Death Adder",
"Deer",
"Deer Mouse",
"Dingo",
"Dinosaur",
"Dove",
"Drongo",
"Duck",
"Duiker",
"Dunnart",
"Eagle",
"Echidna",
"Elephant",
"Elk",
"Emu",
"Falcon",
"Finch",
"Flea",
"Fly",
"Flying Frog",
"Fox",
"Frog",
"Frogmouth",
"Garter Snake",
"Gazelle",
"Gecko",
"Geoffroy's Cat",
"Gerbil",
"Giant Tortoise",
"Giraffe",
"Grasshopper",
"Grison",
"Groundhog",
"Grouse",
"Guanaco",
"Guinea Pig",
"Hamster",
"Harrier",
"Hartebeest",
"Hawk",
"Hedgehog",
"Helmetshrike",
"Hippopotamus",
"Hornbill",
"Hyena",
"Hyrax",
"Impala",
"Jackal",
"Jaguar",
"Jaguarundi",
"Kangaroo",
"Kangaroo Rat",
"Kestrel",
"Kultarr",
"Ladybug",
"Leopard",
"Lion",
"Macaw",
"Meerkat",
"Mouse",
"Newt",
"Oryx",
"Ostrich",
"Owl",
"Pangolin",
"Pheasant",
"Prairie Dog",
"Pronghorn",
"Przewalski's Horse",
"Python",
"Quoll",
"Rabbit",
"Raven",
"Rhinoceros",
"Shelduck",
"Sloth Bear",
"Spectacled Bear",
"Squirrel",
"Starling",
"Stick Bug",
"Tamandua",
"Tasmanian Devil",
"Thornbill",
"Thrush",
"Toad",
"Tortoise"
],
forest: [
"Agouti",
"Anaconda",
"Anoa",
"Ant",
"Anteater",
"Antelope",
"Armadillo",
"Asian Black Bear",
"Aye-aye",
"Babirusa",
"Baboon",
"Badger",
"Bandicoot",
"Banteng",
"Barbet",
"Basilisk",
"Bat",
"Bearded Dragon",
"Bee",
"Bee-eater",
"Beetle",
"Bettong",
"Binturong",
"Bird-of-paradise",
"Bongo",
"Bowerbird",
"Bulbul",
"Bush Dog",
"Bushbaby",
"Bushshrike",
"Butterfly",
"Buzzard",
"Caecilian",
"Cardinal",
"Cassowary",
"Caterpillar",
"Centipede",
"Chameleon",
"Chimpanzee",
"Cicada",
"Civet",
"Clouded Leopard",
"Coati",
"Cobra",
"Cockatoo",
"Cockroach",
"Colugo",
"Cotinga",
"Cotton Rat",
"Cougar",
"Crane Fly",
"Cricket",
"Crocodile",
"Crow",
"Cuckoo",
"Cuscus",
"Death Adder",
"Deer",
"Dhole",
"Dingo",
"Dinosaur",
"Drongo",
"Duck",
"Duiker",
"Eagle",
"Echidna",
"Elephant",
"Finch",
"Flat-headed Cat",
"Flea",
"Flowerpecker",
"Fly",
"Flying Frog",
"Fossa",
"Frog",
"Frogmouth",
"Gaur",
"Gecko",
"Gorilla",
"Grison",
"Hawaiian Honeycreeper",
"Hawk",
"Hedgehog",
"Helmetshrike",
"Hornbill",
"Hyrax",
"Iguana",
"Jackal",
"Jaguar",
"Jaguarundi",
"Kestrel",
"Ladybug",
"Lemur",
"Leopard",
"Lion",
"Macaw",
"Mandrill",
"Margay",
"Monkey",
"Mouse",
"Mouse Deer",
"Newt",
"Okapi",
"Old World Flycatcher",
"Orangutan",
"Owl",
"Pangolin",
"Peafowl",
"Pheasant",
"Possum",
"Python",
"Quokka",
"Rabbit",
"Raccoon",
"Red Panda",
"Red River Hog",
"Rhinoceros",
"Sloth Bear",
"Spectacled Bear",
"Squirrel",
"Starling",
"Stick Bug",
"Sun Bear",
"Tamandua",
"Tamarin",
"Tapir",
"Tarantula",
"Thrush",
"Tiger",
"Tit",
"Toad",
"Tortoise",
"Toucan",
"Trogon",
"Trumpeter",
"Turaco",
"Turtle",
"Tyrant Flycatcher",
"Viper",
"Vulture",
"Wallaby",
"Warbler",
"Wasp",
"Waxwing",
"Weaver",
"Weaver-finch",
"Whistler",
"White-eye",
"Whydah",
"Woodswallow",
"Worm",
"Wren",
"Xenops",
"Yellowjacket",
"Accentor",
"African Buffalo",
"American Black Bear",
"Anole",
"Bird",
"Bison",
"Boa",
"Brown Bear",
"Chipmunk",
"Common Genet",
"Copperhead",
"Coyote",
"Deer Mouse",
"Dormouse",
"Elk",
"Emu",
"Fisher",
"Fox",
"Garter Snake",
"Giant Panda",
"Giant Tortoise",
"Groundhog",
"Grouse",
"Guanaco",
"Himalayan Tahr",
"Kangaroo",
"Koala",
"Numbat",
"Quoll",
"Raccoon dog",
"Tasmanian Devil",
"Thornbill",
"Turkey",
"Vole",
"Weasel",
"Wildcat",
"Wolf",
"Wombat",
"Woodchuck",
"Woodpecker"
],
// list of farm animals comes from https://www.buzzle.com/articles/farm-animals-list.html
farm: [
"Alpaca",
"Buffalo",
"Banteng",
"Cow",
"Cat",
"Chicken",
"Carp",
"Camel",
"Donkey",
"Dog",
"Duck",
"Emu",
"Goat",
"Gayal",
"Guinea",
"Goose",
"Horse",
"Honey",
"Llama",
"Pig",
"Pigeon",
"Rhea",
"Rabbit",
"Sheep",
"Silkworm",
"Turkey",
"Yak",
"Zebu"
],
// list of pet animals comes from https://www.dogbreedinfo.com/pets/pet.htm
pet: [
"Bearded Dragon",
"Birds",
"Burro",
"Cats",
"Chameleons",
"Chickens",
"Chinchillas",
"Chinese Water Dragon",
"Cows",
"Dogs",
"Donkey",
"Ducks",
"Ferrets",
"Fish",
"Geckos",
"Geese",
"Gerbils",
"Goats",
"Guinea Fowl",
"Guinea Pigs",
"Hamsters",
"Hedgehogs",
"Horses",
"Iguanas",
"Llamas",
"Lizards",
"Mice",
"Mule",
"Peafowl",
"Pigs and Hogs",
"Pigeons",
"Ponies",
"Pot Bellied Pig",
"Rabbits",
"Rats",
"Sheep",
"Skinks",
"Snakes",
"Stick Insects",
"Sugar Gliders",
"Tarantula",
"Turkeys",
"Turtles"
],
// list of zoo animals comes from https://bronxzoo.com/animals
zoo: [
"Aardvark",
"African Wild Dog",
"Aldabra Tortoise",
"American Alligator",
"American Bison",
"Amur Tiger",
"Anaconda",
"Andean Condor",
"Asian Elephant",
"Baby Doll Sheep",
"Bald Eagle",
"Barred Owl",
"Blue Iguana",
"Boer Goat",
"California Sea Lion",
"Caribbean Flamingo",
"Chinchilla",
"Collared Lemur",
"Coquerel's Sifaka",
"Cuban Amazon Parrot",
"Ebony Langur",
"Fennec Fox",
"Fossa",
"Gelada",
"Giant Anteater",
"Giraffe",
"Gorilla",
"Grizzly Bear",
"Henkel's Leaf-tailed Gecko",
"Indian Gharial",
"Indian Rhinoceros",
"King Cobra",
"King Vulture",
"Komodo Dragon",
"Linne's Two-toed Sloth",
"Lion",
"Little Penguin",
"Madagascar Tree Boa",
"Magellanic Penguin",
"Malayan Tapir",
"Malayan Tiger",
"Matschies Tree Kangaroo",
"Mini Donkey",
"Monarch Butterfly",
"Nile crocodile",
"North American Porcupine",
"Nubian Ibex",
"Okapi",
"Poison Dart Frog",
"Polar Bear",
"Pygmy Marmoset",
"Radiated Tortoise",
"Red Panda",
"Red Ruffed Lemur",
"Ring-tailed Lemur",
"Ring-tailed Mongoose",
"Rock Hyrax",
"Small Clawed Asian Otter",
"Snow Leopard",
"Snowy Owl",
"Southern White-faced Owl",
"Southern White Rhinocerous",
"Squirrel Monkey",
"Tufted Puffin",
"White Cheeked Gibbon",
"White-throated Bee Eater",
"Zebra"
]
};
// Source: https://en.wikipedia.org/wiki/List_of_population_centers_by_latitude
const cities: string[] = [
"Alert",
"Nord",
"Eureka",
"Ny-Ålesund",
"Longyearbyen",
"Qaanaaq",
"Grise Fiord",
"Dikson",
"Upernavik",
"Tiksi",
"Belushya Guba",
"Barrow",
"Honningsvåg",
"Hammerfest",
"Deadhorse",
"Nuorgam",
"Vadsø",
"Alta",
"Utsjoki",
"Kirkenes",
"Tromsø",
"Tuktoyaktuk",
"Norilsk",
"Murmansk",
"Harstad",
"Narvik",
"Inuvik",
"Kiruna",
"Verkhoyansk",
"Bodø",
"Gällivare",
"Kemijärvi",
"Rovaniemi",
"Ísafjörður",
"Kuusamo",
"Tornio",
"Boden",
"Haparanda",
"Kemi",
"Akureyri",
"Luleå",
"Pudasjärvi",
"Piteå",
"Oulu",
"Fairbanks",
"Skellefteå",
"Anadyr",
"Arkhangelsk",
"Nome",
"Nuuk (Godthåb)",
"Reykjavík",
"Umeå",
"Iqaluit",
"Stjørdal",
"Trondheim",
"Örnsköldsvik",
"Östersund",
"Vaasa",
"Kuopio",
"Yellowknife",
"Sundsvall",
"Jyväskylä",
"Yakutsk",
"Tórshavn",
"Petrozavodsk",
"Tampere",
"Anchorage",
"Lillehammer",
"Lahti",
"Qaqortoq",
"Whitehorse",
"Turku",
"Bergen",
"Vantaa",
"Lerwick",
"Espoo",
"Helsinki",
"Oslo",
"Saint Petersburg",
"Uppsala",
"Fritz Creek",
"Magadan",
"Tallinn",
"Stockholm",
"Sarpsborg",
"Örebro",
"Vologda",
"Norrköping",
"Linköping",
"Tartu",
"Juneau",
"Arendal",
"Kristiansand",
"Perm",
"Valga",
"Gothenburg",
"Visby",
"Yaroslavl",
"Inverness",
"Aberdeen",
"Sitka",
"Riga",
"Izhevsk",
"Yekaterinburg",
"Fort McMurray",
"Dundee",
"Nizhny Novgorod",
"Stirling",
"Bratsk",
"Aarhus",
"Krasnoyarsk",
"Edinburgh",
"Glasgow",
"Kazan",
"Moscow",
"Copenhagen",
"Malmö",
"Esbjerg",
"Odense",
"Grande Prairie",
"Chelyabinsk",
"Novosibirsk",
"Derry",
"Omsk",
"Newcastle upon Tyne",
"Sunderland",
"Petropavl",
"Flensburg",
"Ufa",
"Kaliningrad",
"Vilnius",
"Belfast",
"Middlesbrough",
"Gdynia",
"Gdańsk",
"Kiel",
"Douglas",
"Rostock",
"Lancaster",
"York",
"Prince George",
"Minsk",
"Bradford",
"Leeds",
"Hamburg",
"Edmonton",
"Tolyatti",
"Manchester",
"Liverpool",
"Sheffield",
"Dublin",
"Groningen",
"Samara",
"Bremen",
"Petropavlovsk-Kamchatsky",
"Nottingham",
"Derby",
"Leicester",
"Norwich",
"Peterborough",
"Berlin",
"Birmingham",
"Gomel",
"Coventry",
"Poznań",
"Haarlem",
"Amsterdam",
"Hannover",
"Irkutsk",
"Warsaw",
"Enschede",
"Cambridge",
"Leiden",
"Saskatoon",
"Utrecht",
"The Hague",
"Münster",
"Rotterdam",
"Cork",
"Adak",
"Gloucester",
"Oxford",
"Voronezh",
"Swansea",
"Saratov",
"Dortmund",
"London",
"Cardiff",
"Greenwich",
"Bristol",
"Bath",
"Leipzig",
"Düsseldorf",
"Antwerp",
"Astana",
"Winchester",
"Calgary",
"Ghent",
"Dresden",
"Erfurt",
"Calais",
"Cologne",
"Southampton",
"Maastricht",
"Brussels",
"Brighton and Hove",
"Portsmouth",
"Exeter",
"Kamloops",
"Lille",
"Regina",
"Kiev",
"Charleroi",
"Plymouth",
"Frankfurt am Main",
"Prague",
"Kraków",
"Kharkiv",
"Winnipeg",
"Kelowna",
"Lviv",
"Luxembourg",
"Le Havre",
"Nuremberg",
"Rouen",
"Vancouver",
"Paris",
"Stuttgart",
"Bellingham",
"Volgograd",
"Strasbourg",
"Dnipro",
"Victoria",
"Saguenay",
"Brest",
"Thunder Bay",
"Linz",
"Vienna",
"Bratislava",
"Munich",
"Donetsk",
"Ulaanbaatar",
"Orléans",
"Salzburg",
"Seattle",
"St. John's",
"Basel",
"Budapest",
"Qiqihar",
"Zürich",
"Innsbruck",
"Rostov-on-Don",
"Nantes",
"Vaduz",
"Atyrau",
"Graz",
"Chişinău",
"Bern",
"Tiraspol",
"Quebec City",
"Bismarck",
"Duluth",
"Saint-Pierre",
"Cluj-Napoca",
"Moscow",
"Helena",
"Sault Ste. Marie",
"Lausanne",
"Sudbury",
"Odessa",
"North Bay",
"Charlottetown",
"Geneva",
"Moncton",
"Ljubljana",
"Fredericton",
"Zagreb",
"Lyon",
"Harbin",
"New Glasgow",
"Portland",
"Montreal",
"Milan",
"Venice",
"Ottawa",
"Wakkanai",
"Saint John",
"Novi Sad",
"Turin",
"Krasnodar",
"Minneapolis",
"Simferopol",
"Halifax",
"Bordeaux",
"Belgrade",
"Šabac",
"Drobeta Turnu Severin",
"Bologna",
"Bucharest",
"Ravenna",
"Genoa",
"Pierre",
"Craiova",
"Augusta",
"Montpelier",
"Bath",
"San Marino",
"Changchun",
"Sarajevo",
"Yarmouth",
"Ürümqi",
"Florence",
"Asahikawa",
"Monaco",
"Nice",
"Toronto",
"Boise",
"Toulouse",
"Sochi",
"Cannes",
"Gijón",
"Sioux Falls",
"Split",
"Oviedo",
"Nemuro",
"San Sebastián",
"Marseille",
"Almaty",
"Bilbao",
"Concord",
"Rochester",
"Vladivostok",
"Sapporo",
"Milwaukee",
"Sukhumi",
"Kushiro",
"London",
"Follonica",
"Obihiro",
"Buffalo",
"Santiago de Compostela",
"Bishkek",
"Vitoria-Gasteiz",
"Sofia",
"Pristina",
"Andorra la Vella",
"Nukus",
"Podgorica",
"Boston",
"Detroit",
"Windsor",
"Vigo",
"Tskhinvali",
"Avezzano",
"Skopje",
"Colchester",
"Rome",
"Vatican City",
"Chicago",
"Providence",
"Shenyang",
"Chongjin",
"Hartford",
"Hakodate",
"Tbilisi",
"Valladolid",
"Zaragoza",
"Des Moines",
"Braga",
"Cleveland",
"Barcelona",
"Tirana",
"Tashkent",
"Porto",
"Cheyenne",
"Bari",
"Fort Wayne",
"Istanbul",
"Trabzon",
"Namangan",
"Naples",
"Aomori",
"Lincoln",
"Eureka",
"Salt Lake City",
"Jersey City",
"New York City",
"Thessaloniki",
"Lleida",
"Pittsburgh",
"Baku",
"Madrid",
"Trenton",
"Bursa",
"Yerevan",
"Boulder",
"Columbus",
"Ankara",
"Philadelphia",
"Beijing",
"Stepanakert",
"Forked River",
"Eskisehir",
"Indianapolis",
"Denver",
"Akita",
"Morioka",
"Palma",
"Reno",
"Flores Island",
"Valencia",
"Baltimore",
"Cagliari",
"Dover",
"Wonsan",
"Tianjin",
"Cincinnati",
"Kansas City",
"Pyongyang",
"Ibiza",
"Dalian",
"Washington",
"Lisbon",
"St. Louis",
"Horta",
"Sacramento",
"Dushanbe",
"Angra do Heroísmo",
"Halkida",
"İzmir",
"Charleston",
"Alicante",
"Sendai",
"Louisville",
"Yamagata",
"Messina",
"Palermo",
"Tabriz",
"Shijiazhuang",
"Trapani",
"Athena",
"Kaesong",
"Ashgabat",
"Niigata",
"Taiyuan",
"Konya",
"Ponta Delgada",
"Oakland",
"San Francisco",
"Fukushima",
"Wichita",
"Seoul",
"San Jose",
"Catania",
"Incheon",
"Sevilla",
"Mugla",
"Springfield",
"Gaziantep",
"Adana",
"Virginia Beach",
"Almería",
"Tunis",
"Mersin",
"Algiers",
"Málaga",
"Toyama",
"Jinan",
"Nagano",
"Xining",
"Handan",
"Kanazawa",
"Utsunomiya",
"Maebashi",
"Mito",
"Mosul",
"Mashhad",
"Arbil",
"Las Vegas",
"Nashville",
"Gibraltar",
"Tulsa",
"Fukui",
"Qingdao",
"Lanzhou",
"Knoxville",
"Valletta",
"Birkirkara",
"Los Alamos",
"Daegu",
"Raleigh",
"Tangier",
"Tehran",
"Tokyo",
"Santa Fe",
"Kōfu",
"Chiba",
"Latakia",
"Kawasaki",
"Tottori",
"Oklahoma City",
"Matsue",
"Kirkuk",
"Yokohama",
"Gifu",
"Tiaret",
"Heraklion",
"Melilla",
"Charlotte",
"Nagoya",
"Busan",
"Nicosia",
"Memphis",
"Albuquerque",
"Ōtsu",
"Kyoto",
"Shizuoka",
"Zhengzhou",
"Little Rock",
"Sfax",
"Tsu",
"Osaka",
"Kōbe",
"Nara",
"Okayama",
"Kabul",
"Santa Barbara",
"Hiroshima",
"Takamatsu",
"Xi'an",
"Wakayama",
"Wilmington",
"Yamaguchi",
"Arak",
"Srinagar",
"Tokushima",
"Los Angeles",
"Rabat",
"Peshawar",
"Columbia",
"Riverside",
"Beirut",
"Matsuyama",
"Atlanta",
"Islamabad",
"Birmingham",
"Rawalpindi",
"Fukuoka",
"Kōchi",
"Casablanca",
"Damascus",
"Phoenix",
"Lubbock",
"Baghdad",
"Saga",
"Ōita",
"Tripoli",
"Charleston",
"Dallas",
"Nagasaki",
"Kumamoto",
"San Diego",
"Mexicali",
"Funchal",
"El Centro",
"Isfahan",
"Karbala",
"Tijuana",
"Shreveport",
"Jackson",
"Hamilton",
"Tucson",
"Benghazi",
"Tel Aviv",
"Nanjing",
"Najaf",
"Amman",
"Miyazaki",
"Ramallah",
"Ensenada",
"El Paso",
"Jerusalem",
"Ciudad Juárez",
"Amritsar",
"Marrakech",
"Kandahar",
"Kagoshima",
"Lahore",
"Gaza",
"Faisalabad",
"Port Said",
"Alexandria",
"Shanghai",
"Shimla",
"Ludhiana",
"Chandigarh",
"Mobile",
"Chengdu",
"Wuhan",
"Basra",
"Agadir",
"Jacksonville",
"Austin",
"Hangzhou",
"Multan",
"Cairo",
"New Orleans",
"Suez",
"Houston",
"Lhasa",
"Chongqing",
"Eilat",
"San Antonio",
"Kuwait City",
"Shigatse",
"Hermosillo",
"Chihuahua",
"New Delhi",
"Santa Cruz de Tenerife",
"Orlando",
"Las Palmas de Gran Canaria",
"Tampa",
"Corpus Christi",
"Maspalomas",
"Kathmandu",
"Dibrugarh",
"Thimphu",
"Gangtok",
"Agra",
"El Aaiún",
"Sabha",
"Jaipur",
"Lucknow",
"Siliguri",
"Tezpur",
"Kanpur",
"Dammam",
"Naha",
"Manama",
"Guwahati",
"Brownsville",
"Miami",
"Luxor",
"Monterrey",
"Patna",
"Shillong",
"Torreón",
"Kulpahar",
"Doha",
"Dubai",
"Hyderabad",
"Nassau",
"Kunming",
"Taipei",
"Karachi",
"Culiacán",
"Riyadh",
"Key West",
"Medina",
"Abu Dhabi",
"Al Ain",
"Taichung",
"Durango",
"Agartala",
"Dhaka",
"Muscat",
"Havana",
"Guangzhou",
"Ahmedabad",
"Dongguan",
"Tainan",
"Cabo San Lucas",
"Nanning",
"Kaohsiung",
"Kolkata (Calcutta)",
"Shenzhen",
"Chittagong",
"Hong Kong",
"Tampico",
"San Luis Potosí",
"Aguascalientes",
"Jeddah",
"Cockburn Town",
"Mecca",
"Honolulu",
"Chhattisgarh",
"Cancún",
"Surat",
"Nagpur",
"León",
"Hanoi",
"Mérida",
"Hai Phong",
"Zapopan",
"Puerto Vallarta",
"Guadalajara",
"Querétaro",
"Haikou",
"Santiago de Cuba",
"Chiang Rai",
"Naypyidaw",
"Hilo",
"George Town",
"Veracruz",
"Puebla",
"Mumbai",
"Chiang Mai",
"Port-au-Prince",
"Pune",
"Santo Domingo",
"San Juan",
"Road Town",
"Charlotte Amalie",
"The Valley",
"Nouakchott",
"Kingston",
"Vientiane",
"Visakhapatnam",
"Belize City",
"Udon Thani",
"Hyderabad",
"Basseterre",
"Belmopan",
"St. John's",
"Salalah",
"Acapulco",
"Yangon",
"Timbuktu",
"Huế",
"Khon Kaen",
"Da Nang",
"Basse-Terre",
"Omdurman",
"Khartoum",
"Sana'a",
"Asmara",
"Roseau",
"Saipan",
"Son My",
"Nakhon Ratchasima",
"Praia",
"Tapachula",
"Quetzaltenango",
"Thiès",
"Dakar",
"Quezon City",
"Guatemala City",
"Fort-de-France",
"Manila",
"Makati",
"Ayutthaya",
"Tegucigalpa",
"Castries",
"Bangkok",
"San Salvador",
"Niamey",
"Dededo",
"Hagåtña",
"Banjul",
"Serekunda",
"Siem Reap",
"Brikama",
"Kingstown",
"Bridgetown",
"Chennai (Madras)",
"Bangalore",
"Pattaya",
"Koulikoro",
"Bamako",
"Chinandega",
"Oranjestad",
"Ouagadougou",
"Managua",
"Willemstad",
"N'Djamena",
"St. George's",
"Kano",
"Bissau",
"Port Blair",
"Djibouti",
"Phnom Penh",
"Bobo-Dioulasso",
"Barranquilla",
"Ho Chi Minh City",
"Iloilo City",
"Port of Spain",
"Maracaibo",
"Liberia",
"Caracas",
"Chaguanas",
"Cartagena",
"San Fernando",
"Cebu City",
"Maracay",
"Valencia",
"Alajuela",
"Limón",
"Jaffna",
"Hargeisa",
"Puntarenas",
"Kochi",
"San José",
"Tagbilaran",
"Conakry",
"Tamale",
"Surat Thani",
"Abuja",
"Addis Ababa",
"Panama City",
"Mérida",
"Moundou",
"Trivandrum",
"Freetown",
"Ciudad Bolívar",
"Cúcuta",
"Phuket",
"San Cristóbal",
"Nzérékoré",
"Batticaloa",
"Melekeok",
"Weno",
"Ibadan",
"Koror",
"Kandy",
"Majuro",
"Davao City",
"Hat Yai",
"Colombo",
"Palikir",
"Sri Jayawardenapura-Kotte",
"Zamboanga City",
"Yamoussoukro",
"Georgetown",
"Kumasi",
"Porto-Novo",
"Lagos",
"Enugu",
"Cotonou",
"Benin City",
"Monrovia",
"Medellín",
"Lomé",
"Kota Bharu",
"Alor Setar",
"Kota Kinabalu",
"Paramaribo",
"Puerto Ayacucho",
"Accra",
"Banda Aceh",
"George Town",
"Abidjan",
"Cayenne",
"Sekondi-Takoradi",
"Bandar Seri Begawan",
"Juba",
"Port Harcourt",
"Ipoh",
"Bogotá",
"Miri",
"Bangui",
"Malé",
"Douala",
"Yaoundé",
"Malabo",
"Medan",
"Santiago de Cali",
"Kuala Lumpur",
"Boa Vista",
"Malacca Town",
"Mogadishu",
"Kuching",
"Johor Bahru",
"South Tarawa",
"Singapore",
"Pekanbaru",
"Libreville",
"São Tomé",
"Kampala",
"Entebbe",
"Mbandaka",
"Macapá",
"Pontianak",
"Quito",
"Kismayo",
"Yaren District",
"Padang",
"Balikpapan",
"Nairobi",
"Belém",
"Kigali",
"Guayaquil",
"Mwanza",
"São Luís",
"Jayapura",
"Palembang",
"Manaus",
"Bujumbura",
"Sobral",
"Ambon",
"Fortaleza",
"Iquitos",
"Fernando de Noronha",
"Mombasa",
"Brazzaville",
"Kinshasa",
"Victoria",
"Teresina",
"Makassar",
"Imperatriz",
"Natal",
"Zanzibar City",
"Dodoma",
"Jakarta",
"Bogor",
"Dar es Salaam",
"Bandung",
"Semarang",
"João Pessoa",
"Juazeiro do Norte",
"Campina Grande",
"Surabaya",
"Yogyakarta",
"Malang",
"Recife",
"Trujillo",
"Caruaru",
"Funafuti",
"Dili",
"Denpasar",
"Porto Velho",
"Luanda",
"Garanhuns",
"Nukulaelae",
"Petrolina",
"Honiara",
"Port Moresby",
"Maceió",
"Rio Branco",
"Aracaju",
"Palmas",
"Lubumbashi",
"Moroni",
"Sinop",
"Lima",
"Darwin",
"Huambo",
"Mamoudzou",
"Ndola",
"Salvador",
"Ayacucho",
"Mata-Utu",
"Cusco",
"Apia",
"Lilongwe",
"Pago Pago",
"Ilhéus",
"Lusaka",
"Cuiabá",
"Blantyre",
"Brasília",
"Jamestown",
"Arequipa",
"Labasa",
"Rabi Island",
"La Paz",
"Goiânia",
"Cairns",
"Papeete",
"Port Vila",
"Santa Cruz de la Sierra",
"Livingstone",
"Harare",
"Suva",
"Arica",
"Governador Valadares",
"Uberlândia",
"Antananarivo",
"Mutare",
"Sucre",
"Alofi",
"Townsville",
"Gweru",
"Belo Horizonte",
"Port Louis",
"Bulawayo",
"Iquique",
"Port Hedland",
"Vitória",
"Campo Grande",
"São José do Rio Preto",
"Saint-Denis",
"Nukuʻalofa",
"Francistown",
"Ribeirão Preto",
"Avarua",
"Juiz de Fora",
"Poços de Caldas",
"Araraquara",
"Nouméa",
"Bauru",
"Calama",
"Windhoek",
"Assis",
"Campinas",
"Rio de Janeiro",
"São José dos Campos",
"Rockhampton",
"São Paulo",
"Antofagasta",
"Polokwane",
"Gaborone",
"Salta",
"Adamstown",
"Asunción",
"Curitiba",
"Nelspruit",
"Ciudad del Este",
"Pretoria",
"Mafikeng",
"Maputo",
"Johannesburg",
"Mbabane",
"Lobamba",
"Manzini",
"San Miguel de Tucumán",
"Hanga Roa",
"Copiapó",
"Brisbane",
"Corrientes",
"Florianópolis",
"Gold Coast",
"Kimberley",
"Kingston",
"Bloemfontein",
"Maseru",
"Pietermaritzburg",
"Durban",
"La Serena",
"Córdoba",
"Santa Fe",
"Pelotas",
"Perth",
"San Juan",
"Mandurah",
"Bhisho",
"Mendoza",
"Newcastle",
"Rosario",
"Viña del Mar",
"Valparaíso",
"Santiago",
"Chuí",
"Sydney",
"Cape Town",
"Port Elizabeth",
"Wollongong",
"Buenos Aires",
"Montevideo",
"Adelaide",
"Canberra",
"Concepción",
"Auckland",
"Edinburgh of the Seven Seas",
"Hamilton",
"Melbourne",
"Mar del Plata",
"Geelong",
"Bahía Blanca",
"Temuco",
"Neuquén",
"Hastings",
"Valdivia",
"San Carlos de Bariloche",
"Nelson",
"Wellington",
"Puerto Montt",
"Launceston, Tasmania",
"Hobart",
"Trelew",
"Christchurch",
"Waitangi",
"Puerto Aisén",
"Coihaique",
"Comodoro Rivadavia",
"Dunedin",
"Invercargill",
"Río Gallegos",
"Stanley",
"Punta Arenas",
"Grytviken",
"Ushuaia",
"Puerto Williams",
"Puerto Toro",
"Villa Las Estrellas",
"Esperanza",
"Rothera",
"Concordia"
]; | the_stack |
import * as Faker from 'faker';
import {DictValue, UnitConfig} from '../models/units';
import {
booleanOrRandomValue,
DICT_UNIT_MUTATION_FNS,
randomBoolean,
randomDictObject,
randomKeys,
randomNumber,
randomValidValue,
randomValue,
randomValuePureFn,
selectRandom,
somewhatValidConfig,
times,
} from './utils';
import {deepCopy, isDict, isObject, IteratorSymbol} from '../utils/funcs';
import {Configuration} from '../lib/configuration';
import {DictUnit} from '../lib/dict-unit';
import {EventDictUnitAssign, EventDictUnitDelete, EventDictUnitSet} from '../models/events';
const configOptions: Array<keyof UnitConfig<any>> = [
// 'id', // tests with id are done separately to keep other tests simple
// 'immutable', // immutability tests are done separately to keep other tests simple
// 'persistent', // persistence tests are done separately to keep other tests simple
'replay',
'initialValue',
'cacheSize',
'distinctDispatchCheck',
'customDispatchCheck',
'dispatchDebounce',
'dispatchDebounceMode',
];
describe(
'DictUnit',
times(30, () => {
beforeAll(() => {
Configuration.reset();
});
describe('basic tests', () => {
let unit: DictUnit<any>;
let unitValue: DictValue<any>;
beforeEach(() => {
unitValue = randomDictObject(1);
unit = new DictUnit<any>({initialValue: unitValue});
});
it('should only allow dictionaries', () => {
const randValue = randomValue(1);
const originalUnitValue = unit.value();
unit.dispatch(randValue);
if (isDict(randValue)) {
expect(unit.value()).toEqual(randValue);
} else {
expect(unit.value()).toBe(originalUnitValue);
}
});
it('should have valid length', () => {
expect(unit.length).toBe(isDict(unitValue) ? Object.keys(unitValue).length : 0);
unitValue = randomDictObject(1);
unit.dispatch(unitValue);
expect(unit.length).toBe(Object.keys(unitValue).length);
});
it('checks objectKeys method', () => {
expect(unit.objectKeys()).toEqual(Object.keys(unitValue));
unitValue = randomDictObject(1);
unit.dispatch(unitValue);
expect(unit.objectKeys()).toEqual(Object.keys(unitValue));
});
it('checks objectEntries method', () => {
expect(unit.objectEntries()).toEqual(Object.entries(unitValue));
unitValue = randomDictObject(1);
unit.dispatch(unitValue);
expect(unit.objectEntries()).toEqual(Object.entries(unitValue));
});
it('checks objectValues method', () => {
expect(unit.objectValues()).toEqual(Object.values(unitValue));
unitValue = randomDictObject(1);
unit.dispatch(unitValue);
expect(unit.objectValues()).toEqual(Object.values(unitValue));
});
it('should be iterable', () => {
expect(typeof unit[IteratorSymbol]).toBe('function');
expect(typeof unit[IteratorSymbol]().next).toBe('function');
expect([...unit]).toEqual(unit.objectEntries());
expect(unitValue).toEqual(unit.value());
});
it('should not mutate when frozen', () => {
const length = unit.length;
const emitCount = unit.emitCount;
unit.freeze();
selectRandom(DICT_UNIT_MUTATION_FNS)(unit);
selectRandom(DICT_UNIT_MUTATION_FNS)(unit);
selectRandom(DICT_UNIT_MUTATION_FNS)(unit);
expect(length).toBe(unit.length);
expect(emitCount).toBe(unit.emitCount);
expect(unitValue).toEqual(unit.value());
});
it('should not emit when muted', () => {
const emitCount = unit.emitCount;
unit.mute();
selectRandom(DICT_UNIT_MUTATION_FNS)(unit);
selectRandom(DICT_UNIT_MUTATION_FNS)(unit);
selectRandom(DICT_UNIT_MUTATION_FNS)(unit);
expect(emitCount).toBe(unit.emitCount);
expect(unit.isMuted).toBe(true);
});
});
describe('read-only methods', () => {
let unit: DictUnit<any>;
let unitValue: DictValue<any>;
let emitCount: number;
let dictLength: number;
beforeEach(() => {
unit = new DictUnit(somewhatValidConfig(configOptions, DictUnit));
if (randomBoolean(0.8)) {
unit.dispatch(randomValidValue(DictUnit, randomNumber(1, 3)));
}
unitValue = unit.value();
emitCount = unit.emitCount;
dictLength = unit.length;
});
it('checks "forEvery" method', () => {
const callbackSpy = jasmine.createSpy();
const objectEntries = unit.objectEntries();
unit.forEvery((val, key, index, entries) => {
callbackSpy();
expect(val).toEqual(unitValue[key as any]);
expect(objectEntries[index]).toEqual(entries[index]);
expect(objectEntries[index]).toEqual([key, val]);
});
expect(callbackSpy).toHaveBeenCalledTimes(dictLength);
});
it('checks "get" method', () => {
const randKey = randomValue(1);
expect(unit.get(randKey)).toEqual(unitValue[randKey]);
expect(unit.rawValue()).toEqual(unitValue);
});
it('checks "has" method', () => {
const randKey = randomValue(1);
expect(unit.has(randKey)).toBe(unitValue.hasOwnProperty(randKey));
expect(unit.rawValue()).toEqual(unitValue);
});
it('checks "findByProp" method', () => {
const strictEquality = booleanOrRandomValue(0.8);
const skipStrictEqualityArg = randomBoolean(-0.5);
const allProps = Object.assign({}, ...Object.values(unitValue));
const allKeys = Object.keys(allProps);
const randMatchKey = allKeys[randomNumber(0, allKeys.length - 1)];
const randMatchValue = allProps[randMatchKey];
const matches = unit.findByProp(
randMatchKey,
randMatchValue,
...(skipStrictEqualityArg ? [] : [strictEquality])
);
const testMatches = Object.entries(unitValue).filter(
([propKey, prop]) =>
isObject(prop) &&
(!skipStrictEqualityArg && strictEquality === false
? // tslint:disable-next-line:triple-equals
prop[randMatchKey] == randMatchValue
: prop[randMatchKey] === randMatchValue)
);
expect(matches).toEqual(testMatches);
expect(unit.rawValue()).toEqual(unitValue);
});
});
describe('mutative methods', () => {
let unit: DictUnit<any>;
let normalDictObj: DictValue<any>;
let emitCount: number;
let isEmpty: boolean;
beforeEach(() => {
unit = new DictUnit(somewhatValidConfig(configOptions, DictUnit));
if (randomBoolean(0.8)) {
unit.dispatch(randomValidValue(DictUnit, 1, 10));
}
normalDictObj = deepCopy(unit.rawValue());
emitCount = unit.emitCount;
isEmpty = unit.isEmpty;
});
it('checks "set" method', () => {
const randKey = randomValue(1) as number;
const randVal = randomValue(1);
let event;
unit.events$.subscribe(e => (event = e));
unit.set(randKey, randVal);
if (typeof randKey === 'string' || typeof randKey === 'number') {
normalDictObj[randKey] = randVal;
expect(normalDictObj[randKey]).toEqual(unit.get(randKey));
expect(event).toBeInstanceOf(EventDictUnitSet);
expect(event).toEqual(new EventDictUnitSet(randKey, randVal));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalDictObj);
});
it('checks "assign" method', () => {
const randSources = Array(randomNumber(0, 5))
.fill(null)
.map(() => randomDictObject());
let event: EventDictUnitAssign<any>;
unit.events$.subscribe(e => (event = e as EventDictUnitAssign<any>));
unit.assign(...randSources);
if (randSources.length) {
expect(unit.value()).toEqual(Object.assign(normalDictObj, ...randSources));
expect(event).toBeInstanceOf(EventDictUnitAssign);
expect(event.sources).toEqual(randSources);
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalDictObj);
});
it('checks "delete" method', () => {
const mixedKeys = [...unit.objectKeys(), ...randomKeys()];
const randKeys = Faker.helpers
.shuffle(mixedKeys)
.slice(randomNumber(0, mixedKeys.length + 1));
let event;
unit.events$.subscribe(e => (event = e));
unit.delete(...randKeys);
const ownProps = randKeys.filter(key => normalDictObj.hasOwnProperty(key));
if (!isEmpty && ownProps.length) {
const removedProps = {};
ownProps.forEach(key => {
removedProps[key] = deepCopy(normalDictObj[key]);
delete normalDictObj[key];
});
expect(event).toBeInstanceOf(EventDictUnitDelete);
expect(event).toEqual(new EventDictUnitDelete(removedProps));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalDictObj);
});
it('checks "deleteIf" method', () => {
const predicate = randomValuePureFn();
let event;
unit.events$.subscribe(e => (event = e));
unit.deleteIf((v, k, i) => predicate(i));
if (!isEmpty && typeof predicate === 'function') {
const removedProps = {};
Object.keys(normalDictObj).forEach((key, i) => {
if (predicate(i)) {
removedProps[key] = normalDictObj[key];
delete normalDictObj[key];
}
});
expect(event).toBeInstanceOf(EventDictUnitDelete);
expect(event).toEqual(new EventDictUnitDelete(removedProps));
expect(unit.emitCount).toBe(emitCount + 1);
} else {
expect(event).toBe(undefined);
expect(unit.emitCount).toBe(emitCount);
}
expect(unit.rawValue()).toEqual(normalDictObj);
});
});
})
); | the_stack |
import path from "path";
import forge from "node-forge";
import debug from "debug";
import { Stream } from "stream";
import { ZipFile } from "yazl";
import type Joi from "joi";
import * as Schemas from "./schemas";
import formatMessage, { ERROR, DEBUG } from "./messages";
import FieldsArray from "./fieldsArray";
import {
generateStringFile,
dateToW3CString,
isValidRGB,
deletePersonalization,
getAllFilesWithName,
} from "./utils";
import * as Signature from "./signature";
const barcodeDebug = debug("passkit:barcode");
const genericDebug = debug("passkit:generic");
const transitType = Symbol("transitType");
const passProps = Symbol("_props");
const propsSchemaMap = new Map<string, Joi.ObjectSchema<any>>([
["barcodes", Schemas.Barcode],
["barcode", Schemas.Barcode],
["beacons", Schemas.Beacon],
["locations", Schemas.Location],
["nfc", Schemas.NFC],
]);
export class Pass {
private bundle: Schemas.BundleUnit;
private l10nBundles: Schemas.PartitionedBundle["l10nBundle"];
private _fields: (keyof Schemas.PassFields)[] = [
"primaryFields",
"secondaryFields",
"auxiliaryFields",
"backFields",
"headerFields",
];
private [passProps]: Schemas.ValidPass = {};
private type: keyof Schemas.ValidPassType;
private fieldsKeys: Set<string> = new Set<string>();
private passCore: Schemas.ValidPass;
public headerFields: FieldsArray;
public primaryFields: FieldsArray;
public secondaryFields: FieldsArray;
public auxiliaryFields: FieldsArray;
public backFields: FieldsArray;
private Certificates: Schemas.CertificatesSchema;
private [transitType]: string = "";
private l10nTranslations: {
[languageCode: string]: { [placeholder: string]: string };
} = {};
constructor(options: Schemas.PassInstance) {
if (!Schemas.isValid(options, Schemas.PassInstance)) {
throw new Error(formatMessage(ERROR.REQUIR_VALID_FAILED));
}
this.Certificates = options.certificates;
this.l10nBundles = options.model.l10nBundle;
this.bundle = { ...options.model.bundle };
try {
this.passCore = JSON.parse(
this.bundle["pass.json"].toString("utf8"),
);
} catch (err) {
throw new Error(formatMessage(ERROR.PASSFILE_VALIDATION_FAILED));
}
// Parsing the options and extracting only the valid ones.
const validOverrides = Schemas.getValidated(
options.overrides || {},
Schemas.OverridesSupportedOptions,
);
if (validOverrides === null) {
throw new Error(formatMessage(ERROR.OVV_KEYS_BADFORMAT));
}
this.type = Object.keys(this.passCore).find((key) =>
/(boardingPass|eventTicket|coupon|generic|storeCard)/.test(key),
) as keyof Schemas.ValidPassType;
if (!this.type) {
throw new Error(formatMessage(ERROR.NO_PASS_TYPE));
}
// Parsing and validating pass.json keys
const passCoreKeys = Object.keys(
this.passCore,
) as (keyof Schemas.ValidPass)[];
const validatedPassKeys = passCoreKeys.reduce<Schemas.ValidPass>(
(acc, current) => {
if (this.type === current) {
// We want to exclude type keys (eventTicket,
// boardingPass, ecc.) and their content
return acc;
}
if (!propsSchemaMap.has(current)) {
// If the property is unknown (we don't care if
// it is valid or not for Wallet), we return
// directly the content
return { ...acc, [current]: this.passCore[current] };
}
const currentSchema = propsSchemaMap.get(current)!;
if (Array.isArray(this.passCore[current])) {
const valid = getValidInArray<Schemas.ArrayPassSchema>(
currentSchema,
this.passCore[current] as Schemas.ArrayPassSchema[],
);
return {
...acc,
[current]: valid,
};
} else {
return {
...acc,
[current]:
(Schemas.isValid(
this.passCore[current],
currentSchema,
) &&
this.passCore[current]) ||
undefined,
};
}
},
{},
);
this[passProps] = {
...(validatedPassKeys || {}),
...(validOverrides || {}),
};
if (
this.type === "boardingPass" &&
this.passCore[this.type]["transitType"]
) {
// We might want to generate a boarding pass without setting manually
// in the code the transit type but right in the model;
this[transitType] = this.passCore[this.type]["transitType"];
}
this._fields.forEach((fieldName) => {
this[fieldName] = new FieldsArray(
this.fieldsKeys,
...(this.passCore[this.type][fieldName] || []).filter((field) =>
Schemas.isValid(field, Schemas.Field),
),
);
});
}
/**
* Generates the pass Stream
*
* @method generate
* @return A Stream of the generated pass.
*/
generate(): Stream {
// Editing Pass.json
this.bundle["pass.json"] = this._patch(this.bundle["pass.json"]);
/**
* Checking Personalization, as this is available only with NFC
* @see https://apple.co/2SHfb22
*/
const currentBundleFiles = Object.keys(this.bundle);
if (
!this[passProps].nfc &&
currentBundleFiles.includes("personalization.json")
) {
genericDebug(formatMessage(DEBUG.PRS_REMOVED));
deletePersonalization(
this.bundle,
getAllFilesWithName(
"personalizationLogo",
currentBundleFiles,
"startsWith",
),
);
}
const finalBundle: Schemas.BundleUnit = { ...this.bundle };
/**
* Iterating through languages and generating pass.string file
*/
const translationsLanguageCodes = Object.keys(this.l10nTranslations);
for (
let langs = translationsLanguageCodes.length, lang: string;
(lang = translationsLanguageCodes[--langs]);
) {
const strings = generateStringFile(this.l10nTranslations[lang]);
const languageBundleDirname = `${lang}.lproj`;
if (strings.length) {
/**
* if there's already a buffer of the same folder and called
* `pass.strings`, we'll merge the two buffers. We'll create
* it otherwise.
*/
const languageBundleUnit = (this.l10nBundles[
languageBundleDirname
] ??= {});
languageBundleUnit["pass.strings"] = Buffer.concat([
languageBundleUnit["pass.strings"] || Buffer.alloc(0),
strings,
]);
}
if (
!this.l10nBundles[languageBundleDirname] ||
!Object.keys(this.l10nBundles[languageBundleDirname]).length
) {
continue;
}
/**
* Assigning all the localization files to the final bundle
* by mapping the buffer to the pass-relative file path;
*
* We are replacing the slashes to avoid Windows slashes
* composition.
*/
const bundleRelativeL10NPaths = Object.entries(
this.l10nBundles[languageBundleDirname],
).reduce((acc, [fileName, fileContent]) => {
const fullPath = path
.join(languageBundleDirname, fileName)
.replace(/\\/, "/");
return {
...acc,
[fullPath]: fileContent,
};
}, {});
Object.assign(finalBundle, bundleRelativeL10NPaths);
}
/*
* Parsing the buffers, pushing them into the archive
* and returning the compiled manifest
*/
const archive = new ZipFile();
const manifest = Object.entries(finalBundle).reduce<Schemas.Manifest>(
(acc, [fileName, buffer]) => {
let hashFlow = forge.md.sha1.create();
hashFlow.update(buffer.toString("binary"));
archive.addBuffer(buffer, fileName);
return {
...acc,
[fileName]: hashFlow.digest().toHex(),
};
},
{},
);
const signatureBuffer = Signature.create(manifest, this.Certificates);
archive.addBuffer(signatureBuffer, "signature");
archive.addBuffer(
Buffer.from(JSON.stringify(manifest)),
"manifest.json",
);
const passStream = new Stream.PassThrough();
archive.outputStream.pipe(passStream);
archive.end();
return passStream;
}
/**
* Adds traslated strings object to the list of translation to be inserted into the pass
*
* @method localize
* @params lang - the ISO 3166 alpha-2 code for the language
* @params translations - key/value pairs where key is the
* placeholder in pass.json localizable strings
* and value the real translated string.
* @returns {this}
*
* @see https://apple.co/2KOv0OW - Passes support localization
*/
localize(
lang: string,
translations?: { [placeholder: string]: string },
): this {
if (
lang &&
typeof lang === "string" &&
(typeof translations === "object" || translations === undefined)
) {
this.l10nTranslations[lang] = translations || {};
}
return this;
}
/**
* Sets expirationDate property to a W3C-formatted date
*
* @method expiration
* @params date
* @returns {this}
*/
expiration(date: Date | null): this {
if (date === null) {
delete this[passProps]["expirationDate"];
return this;
}
const parsedDate = processDate("expirationDate", date);
if (parsedDate) {
this[passProps]["expirationDate"] = parsedDate;
}
return this;
}
/**
* Sets voided property to true
*
* @method void
* @return {this}
*/
void(): this {
this[passProps]["voided"] = true;
return this;
}
/**
* Sets current pass' relevancy through beacons
* @param data varargs with type schema.Beacon, or single arg null
* @returns {Pass}
*/
beacons(resetFlag: null): this;
beacons(...data: Schemas.Beacon[]): this;
beacons(...data: (Schemas.Beacon | null)[]): this {
if (data[0] === null) {
delete this[passProps]["beacons"];
return this;
}
const valid = getValidInArray(Schemas.Beacon, data);
if (valid.length) {
this[passProps]["beacons"] = valid;
}
return this;
}
/**
* Sets current pass' relevancy through locations
* @param data varargs with type schema.Location, or single arg null
* @returns {Pass}
*/
locations(resetFlag: null): this;
locations(...data: Schemas.Location[]): this;
locations(...data: (Schemas.Location | null)[]): this {
if (data[0] === null) {
delete this[passProps]["locations"];
return this;
}
const valid = getValidInArray(Schemas.Location, data);
if (valid.length) {
this[passProps]["locations"] = valid;
}
return this;
}
/**
* Sets current pass' relevancy through a date
* @param data
* @returns {Pass}
*/
relevantDate(date: Date | null): this {
if (date === null) {
delete this[passProps]["relevantDate"];
return this;
}
const parsedDate = processDate("relevantDate", date);
if (parsedDate) {
this[passProps]["relevantDate"] = parsedDate;
}
return this;
}
/**
* Adds barcodes "barcodes" property.
* It allows to pass a string to autogenerate all the structures.
*
* @method barcode
* @params first - a structure or the string (message) that will generate
* all the barcodes
* @params data - other barcodes support
* @return {this} Improved this with length property and other methods
*/
barcodes(resetFlag: null): this;
barcodes(message: string): this;
barcodes(...data: Schemas.Barcode[]): this;
barcodes(...data: (Schemas.Barcode | null | string)[]): this {
if (data[0] === null) {
delete this[passProps]["barcodes"];
return this;
}
if (typeof data[0] === "string") {
const autogen = barcodesFromUncompleteData(data[0]);
if (!autogen.length) {
barcodeDebug(formatMessage(DEBUG.BRC_AUTC_MISSING_DATA));
return this;
}
this[passProps]["barcodes"] = autogen;
return this;
} else {
/**
* Stripping from the array not-object elements
* and the ones that does not pass validation.
* Validation assign default value to missing parameters (if any).
*/
const validBarcodes = data.reduce<Schemas.Barcode[]>(
(acc, current) => {
if (!(current && current instanceof Object)) {
return acc;
}
const validated = Schemas.getValidated(
current,
Schemas.Barcode,
);
if (
!(
validated &&
validated instanceof Object &&
Object.keys(validated).length
)
) {
return acc;
}
return [...acc, validated];
},
[],
);
if (validBarcodes.length) {
this[passProps]["barcodes"] = validBarcodes;
}
return this;
}
}
/**
* Given an index <= the amount of already set "barcodes",
* this let you choose which structure to use for retrocompatibility
* property "barcode".
*
* @method barcode
* @params format - the format to be used
* @return {this}
*/
barcode(chosenFormat: Schemas.BarcodeFormat | null): this {
const { barcodes } = this[passProps];
if (chosenFormat === null) {
delete this[passProps]["barcode"];
return this;
}
if (typeof chosenFormat !== "string") {
barcodeDebug(formatMessage(DEBUG.BRC_FORMATTYPE_UNMATCH));
return this;
}
if (chosenFormat === "PKBarcodeFormatCode128") {
barcodeDebug(formatMessage(DEBUG.BRC_BW_FORMAT_UNSUPPORTED));
return this;
}
if (!(barcodes && barcodes.length)) {
barcodeDebug(formatMessage(DEBUG.BRC_NO_POOL));
return this;
}
// Checking which object among barcodes has the same format of the specified one.
const index = barcodes.findIndex((b) =>
b.format.toLowerCase().includes(chosenFormat.toLowerCase()),
);
if (index === -1) {
barcodeDebug(formatMessage(DEBUG.BRC_NOT_SUPPORTED));
return this;
}
this[passProps]["barcode"] = barcodes[index];
return this;
}
/**
* Sets nfc fields in properties
*
* @method nfc
* @params data - the data to be pushed in the pass
* @returns {this}
* @see https://apple.co/2wTxiaC
*/
nfc(data: Schemas.NFC | null): this {
if (data === null) {
delete this[passProps]["nfc"];
return this;
}
if (
!(
data &&
typeof data === "object" &&
!Array.isArray(data) &&
Schemas.isValid(data, Schemas.NFC)
)
) {
genericDebug(formatMessage(DEBUG.NFC_INVALID));
return this;
}
this[passProps]["nfc"] = data;
return this;
}
/**
* Allows to get the current inserted props;
* will return all props from valid overrides,
* template's pass.json and methods-inserted ones;
*
* @returns The properties will be inserted in the pass.
*/
get props(): Readonly<Schemas.ValidPass> {
return this[passProps];
}
/**
* Edits the buffer of pass.json based on the passed options.
*
* @method _patch
* @params {Buffer} passBuffer - Buffer of the contents of pass.json
* @returns {Promise<Buffer>} Edited pass.json buffer or Object containing error.
*/
private _patch(passCoreBuffer: Buffer): Buffer {
const passFile = JSON.parse(
passCoreBuffer.toString(),
) as Schemas.ValidPass;
if (Object.keys(this[passProps]).length) {
/*
* We filter the existing (in passFile) and non-valid keys from
* the below array keys that accept rgb values
* and then delete it from the passFile.
*/
const passColors = [
"backgroundColor",
"foregroundColor",
"labelColor",
] as Array<keyof Schemas.PassColors>;
passColors
.filter(
(v) =>
this[passProps][v] && !isValidRGB(this[passProps][v]),
)
.forEach((v) => delete this[passProps][v]);
Object.assign(passFile, this[passProps]);
}
this._fields.forEach((field) => {
passFile[this.type][field] = this[field];
});
if (this.type === "boardingPass" && !this[transitType]) {
throw new Error(formatMessage(ERROR.TRSTYPE_REQUIRED));
}
passFile[this.type]["transitType"] = this[transitType];
return Buffer.from(JSON.stringify(passFile));
}
set transitType(value: string) {
if (!Schemas.isValid(value, Schemas.TransitType)) {
genericDebug(formatMessage(DEBUG.TRSTYPE_NOT_VALID, value));
this[transitType] = this[transitType] || "";
return;
}
this[transitType] = value;
}
get transitType(): string {
return this[transitType];
}
}
/**
* Automatically generates barcodes for all the types given common info
*
* @method barcodesFromUncompleteData
* @params message - the content to be placed inside "message" field
* @return Array of barcodeDict compliant
*/
function barcodesFromUncompleteData(message: string): Schemas.Barcode[] {
if (!(message && typeof message === "string")) {
return [];
}
return (
[
"PKBarcodeFormatQR",
"PKBarcodeFormatPDF417",
"PKBarcodeFormatAztec",
"PKBarcodeFormatCode128",
] as Array<Schemas.BarcodeFormat>
).map((format) =>
Schemas.getValidated({ format, message }, Schemas.Barcode),
);
}
function getValidInArray<T>(
schemaName: Joi.ObjectSchema<T>,
contents: T[],
): T[] {
return contents.filter(
(current) =>
Object.keys(current).length && Schemas.isValid(current, schemaName),
);
}
function processDate(key: string, date: Date): string | null {
if (!(date instanceof Date)) {
return null;
}
const dateParse = dateToW3CString(date);
if (!dateParse) {
genericDebug(formatMessage(DEBUG.DATE_FORMAT_UNMATCH, key));
return null;
}
return dateParse;
} | the_stack |
import { expect } from 'chai'
import * as fs from 'fs'
import * as path from 'path'
import { Scheduler } from '../../../src/index'
/**
* v1 Functional Testing Suite
* This suite ensures backwards compatibility with node-sscheduler v1
*/
const scheduler = new Scheduler()
const fileExists = (p: string): boolean => {
try {
return fs.lstatSync(p).isFile()
} catch (err) {
return false
}
}
const getAvailabilitiesAsStrings = (response: any): any => {
const availabilities: any = {}
for (const day of Object.keys(response)) {
const tmp: string[] = response[day]
.filter((el: any) => el.available)
.map((el: any) => el.time)
if (tmp.length) {
availabilities[day] = tmp
}
}
return availabilities
}
const runTest = (inputFilename: string, expectedFilename: string): void => {
const input = JSON.parse(fs.readFileSync(inputFilename).toString())
const expected = JSON.parse(fs.readFileSync(expectedFilename).toString())
const response = scheduler.getAvailability(input)
expect(getAvailabilitiesAsStrings(response)).to.deep.equal(expected)
}
const runTestIntersect = (
inputFilename: string,
expectedFilename: string
): void => {
const input = JSON.parse(fs.readFileSync(inputFilename).toString())
const expected = JSON.parse(fs.readFileSync(expectedFilename).toString())
const response = scheduler.getIntersection(input)
expect(response).to.deep.equal(expected)
}
describe('getAvailability', () => {
describe('validation', () => {
it('from/to validation', () => {
expect(
scheduler.getAvailability.bind(scheduler, {
from: 'test',
to: '2017-01-24',
schedule: {},
interval: 30,
duration: 30
})
).to.throw(Error, '"from" must be a valid ISO 8601 string')
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: 'test',
schedule: {},
interval: 30,
duration: 30
})
).to.throw(Error, '"to" must be a valid ISO 8601 string')
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-23',
schedule: {},
interval: 30,
duration: 30
})
).to.throw(Error, '"to" must be greater than "from"')
})
it('schedule validation', () => {
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: {
from: 'test',
to: '10:00'
}
},
interval: 30,
duration: 30
})
).to.throw(Error, 'monday: "from" must be a time in the format HH:mm')
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: {
from: '09:00',
to: 'test'
}
},
interval: 30,
duration: 30
})
).to.throw(Error, 'monday: "to" must be a time in the format HH:mm')
// this was removed to allow times that wrap around the day
// expect(
// scheduler.getAvailability.bind(scheduler, {
// from: '2017-01-23',
// to: '2017-01-24',
// schedule: {
// monday: {
// from: '09:00',
// to: '09:00'
// }
// },
// interval: 30,
// duration: 30
// })
// ).to.throw(Error, 'monday: "to" must be greater than "from"')
})
it('schedule unavailability validation Interval type', () => {
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: {
from: '09:00',
to: '17:00',
unavailability: [
{
from: 'test',
to: '13:00'
}
]
}
},
interval: 30,
duration: 30
})
).to.throw(
Error,
'monday: unavailability "from" must be a time in the format HH:mm'
)
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: {
from: '09:00',
to: '17:00',
unavailability: [
{
from: '12:00',
to: 'test'
}
]
}
},
interval: 30,
duration: 30
})
).to.throw(
Error,
'monday: unavailability "to" must be a time in the format HH:mm'
)
// this was removed to allow times that wrap around the day
// expect(
// scheduler.getAvailability.bind(scheduler, {
// from: '2017-01-23',
// to: '2017-01-24',
// schedule: {
// monday: {
// from: '09:00',
// to: '17:00',
// unavailability: [
// {
// from: '12:00',
// to: '12:00'
// }
// ]
// }
// },
// interval: 30,
// duration: 30
// })
// ).to.throw(
// Error,
// 'monday: unavailability "to" must be greater than "from"'
// )
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
unavailability: [
{
from: 'test',
to: '2017-01-23 13:00'
}
]
},
interval: 30,
duration: 30
})
).to.throw(Error, 'unavailability "from" must be a valid ISO 8601 string')
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
unavailability: [
{
from: '2017-01-23 10:00',
to: 'test'
}
]
},
interval: 30,
duration: 30
})
).to.throw(Error, 'unavailability "to" must be a valid ISO 8601 string')
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
unavailability: [
{
from: '2017-01-23 10:00',
to: '2017-01-23 09:00'
}
]
},
interval: 30,
duration: 30
})
).to.throw(Error, 'unavailability "to" must be greater than "from"')
})
it('schedule unavailability validation ScheduleSpecificDate type', () => {
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: {
from: '09:00',
to: '17:00',
unavailability: [
{
from: 'test',
to: '13:00'
}
]
}
},
interval: 30,
duration: 30
})
).to.throw(
Error,
'monday: unavailability "from" must be a time in the format HH:mm'
)
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: {
from: '09:00',
to: '17:00',
unavailability: [
{
from: '12:00',
to: 'test'
}
]
}
},
interval: 30,
duration: 30
})
).to.throw(
Error,
'monday: unavailability "to" must be a time in the format HH:mm'
)
// this was removed to allow times that wrap around the day
// expect(
// scheduler.getAvailability.bind(scheduler, {
// from: '2017-01-23',
// to: '2017-01-24',
// schedule: {
// monday: {
// from: '09:00',
// to: '17:00',
// unavailability: [
// {
// from: '12:00',
// to: '12:00'
// }
// ]
// }
// },
// interval: 30,
// duration: 30
// })
// ).to.throw(
// Error,
// 'monday: unavailability "to" must be greater than "from"'
// )
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
unavailability: [
{
date: 'test',
from: '12:00',
to: '13:00'
}
]
},
interval: 30,
duration: 30
})
).to.throw(Error, 'unavailability "date" must be a valid ISO 8601 string')
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
unavailability: [
{
date: '2017-01-23',
from: 'test',
to: '13:00'
}
]
},
interval: 30,
duration: 30
})
).to.throw(
Error,
'unavailability "from" must be a time in the format HH:mm'
)
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
unavailability: [
{
date: '2017-01-23',
from: '10:00',
to: 'test'
}
]
},
interval: 30,
duration: 30
})
).to.throw(
Error,
'unavailability "to" must be a time in the format HH:mm'
)
})
it('schedule allocated validation', () => {
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: { from: '09:00', to: '17:00' },
allocated: [{ from: 'test', duration: 60 }]
},
interval: 30,
duration: 30
})
).to.throw(Error, '"allocated.from" must be a valid ISO 8601 string')
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: { from: '09:00', to: '17:00' },
allocated: [{ from: '2017-01-23 10:00', duration: -1 }]
},
interval: 30,
duration: 30
})
).to.throw(Error, '"allocated.duration" must be a positive integer')
})
it('interval validation', () => {
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: { from: '09:00', to: '17:00' }
},
interval: 'test',
duration: 30
})
).to.throw(Error, '"interval" must be a positive integer')
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: { from: '09:00', to: '17:00' }
},
interval: -5,
duration: 30
})
).to.throw(Error, '"interval" must be a positive integer')
})
it('duration validation', () => {
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: { from: '09:00', to: '17:00' }
},
interval: 30,
duration: 'test'
})
).to.throw(Error, '"duration" must be a positive integer')
expect(
scheduler.getAvailability.bind(scheduler, {
from: '2017-01-23',
to: '2017-01-24',
schedule: {
monday: { from: '09:00', to: '17:00' }
},
interval: 30,
duration: -5
})
).to.throw(Error, '"duration" must be a positive integer')
})
})
})
describe('functionality', () => {
const dataPath = path.resolve(__dirname, 'data')
const folders = fs.readdirSync(dataPath)
for (const folder of folders) {
describe(folder, () => {
const subFolders = fs.readdirSync(path.resolve(dataPath, folder))
for (const subFolder of subFolders) {
for (let i = 1; i < 100; i = i + 1) {
const no = i >= 10 ? `${i}` : `0${i}`
if (
fileExists(
path.resolve(dataPath, folder, subFolder, `input${no}.json`)
)
) {
it(`${subFolder}: test #${no}`, () => {
if (folder === '03-intersect') {
runTestIntersect(
path.resolve(dataPath, folder, subFolder, `input${no}.json`),
path.resolve(
dataPath,
folder,
subFolder,
`expected${no}.json`
)
)
} else {
runTest(
path.resolve(dataPath, folder, subFolder, `input${no}.json`),
path.resolve(
dataPath,
folder,
subFolder,
`expected${no}.json`
)
)
}
})
} else {
break
}
}
}
})
}
}) | the_stack |
import { IDropdownOption, Image, Label, Stack, Text, TextField } from "@fluentui/react";
import { useBoolean } from "@fluentui/react-hooks";
import React, { FunctionComponent, useEffect, useState } from "react";
import * as _ from "underscore";
import AddPropertyIcon from "../../../../images/Add-property.svg";
import RevertBackIcon from "../../../../images/RevertBack.svg";
import { getErrorMessage, handleError } from "../../../Common/ErrorHandlingUtils";
import { TableEntity } from "../../../Common/TableEntity";
import { userContext } from "../../../UserContext";
import * as TableConstants from "../../Tables/Constants";
import * as DataTableUtilities from "../../Tables/DataTable/DataTableUtilities";
import TableEntityListViewModel from "../../Tables/DataTable/TableEntityListViewModel";
import * as Entities from "../../Tables/Entities";
import { CassandraAPIDataClient, TableDataClient } from "../../Tables/TableDataClient";
import * as TableEntityProcessor from "../../Tables/TableEntityProcessor";
import QueryTablesTab from "../../Tabs/QueryTablesTab";
import { RightPaneForm, RightPaneFormProps } from "../RightPaneForm/RightPaneForm";
import {
attributeNameLabel,
attributeValueLabel,
backImageProps,
cassandraOptions,
columnProps,
dataTypeLabel,
defaultStringPlaceHolder,
detailedHelp,
entityFromAttributes,
getAddButtonLabel,
getEntityValuePlaceholder,
getFormattedTime,
imageProps,
options,
} from "./Validators/EntityTableHelper";
interface EditTableEntityPanelProps {
tableDataClient: TableDataClient;
queryTablesTab: QueryTablesTab;
tableEntityListViewModel: TableEntityListViewModel;
cassandraApiClient: CassandraAPIDataClient;
}
interface EntityRowType {
property: string;
type: string;
value: string;
isPropertyTypeDisable: boolean;
isDeleteOptionVisible: boolean;
id: number;
entityValuePlaceholder: string;
isEntityTypeDate: boolean;
entityTimeValue?: string;
isEntityValueDisable?: boolean;
}
export const EditTableEntityPanel: FunctionComponent<EditTableEntityPanelProps> = ({
tableDataClient,
queryTablesTab,
tableEntityListViewModel,
cassandraApiClient,
}: EditTableEntityPanelProps): JSX.Element => {
const [entities, setEntities] = useState<EntityRowType[]>([]);
const [selectedRow, setSelectedRow] = useState<number>(0);
const [entityAttributeValue, setEntityAttributeValue] = useState<string>("");
const [originalDocument, setOriginalDocument] = useState<Entities.ITableEntity>({});
const [entityAttributeProperty, setEntityAttributeProperty] = useState<string>("");
const [formError, setFormError] = useState<string>("");
const [isExecuting, setIsExecuting] = useState<boolean>(false);
const [
isEntityValuePanelOpen,
{ setTrue: setIsEntityValuePanelTrue, setFalse: setIsEntityValuePanelFalse },
] = useBoolean(false);
useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let originalDocument: { [key: string]: any } = {};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const entityAttribute: any = tableEntityListViewModel.selected();
const entityFormattedAttribute = constructDisplayedAttributes(entityAttribute[0]);
setEntities(entityFormattedAttribute);
if (userContext.apiType === "Tables") {
originalDocument = TableEntityProcessor.convertEntitiesToDocuments(entityAttribute, queryTablesTab.collection)[0];
originalDocument.id = (): string => originalDocument.$id;
} else {
originalDocument = entityAttribute;
}
setOriginalDocument(originalDocument);
}, []);
const constructDisplayedAttributes = (entity: Entities.ITableEntity): EntityRowType[] => {
const displayedAttributes: EntityRowType[] = [];
const keys = Object.keys(entity);
keys.length &&
keys.forEach((key: string) => {
if (
key !== TableEntityProcessor.keyProperties.attachments &&
key !== TableEntityProcessor.keyProperties.etag &&
key !== TableEntityProcessor.keyProperties.resourceId &&
key !== TableEntityProcessor.keyProperties.self &&
(userContext.apiType !== "Cassandra" || key !== TableConstants.EntityKeyNames.RowKey)
) {
if (userContext.apiType === "Cassandra") {
const cassandraKeys = queryTablesTab.collection.cassandraKeys.partitionKeys
.concat(queryTablesTab.collection.cassandraKeys.clusteringKeys)
.map((key) => key.property);
const entityAttribute: Entities.ITableEntityAttribute = entity[key];
const entityAttributeType: string = entityAttribute.$;
const displayValue: string = getPropertyDisplayValue(entity, key, entityAttributeType);
const nonEditableType: boolean =
entityAttributeType === TableConstants.CassandraType.Blob ||
entityAttributeType === TableConstants.CassandraType.Inet;
const isDisable = !_.contains<string>(cassandraKeys, key) && !nonEditableType;
const time =
entityAttributeType === TableConstants.TableType.DateTime ? getFormattedTime(displayValue) : "";
displayedAttributes.push({
property: key,
type: entityAttributeType,
value: displayValue,
isPropertyTypeDisable: !nonEditableType,
isDeleteOptionVisible: isDisable,
id: displayedAttributes.length,
entityValuePlaceholder: defaultStringPlaceHolder,
isEntityTypeDate: entityAttributeType === "DateTime",
isEntityValueDisable: !isDisable,
entityTimeValue: time,
});
} else {
const entityAttribute: Entities.ITableEntityAttribute = entity[key];
const entityAttributeType: string = entityAttribute.$;
const displayValue: string = getPropertyDisplayValue(entity, key, entityAttributeType);
const editable: boolean = isAttributeEditable(key, entityAttributeType);
// As per VSO:189935, Binary properties are read-only, we still want to be able to remove them.
const removable: boolean = editable || entityAttributeType === TableConstants.TableType.Binary;
const time =
entityAttributeType === TableConstants.TableType.DateTime ? getFormattedTime(displayValue) : "";
displayedAttributes.push({
property: key,
type: entityAttributeType,
value: displayValue,
isPropertyTypeDisable: !editable,
isDeleteOptionVisible: removable,
id: displayedAttributes.length,
entityValuePlaceholder: defaultStringPlaceHolder,
isEntityTypeDate: entityAttributeType === "DateTime",
isEntityValueDisable: !editable,
entityTimeValue: time,
});
}
}
});
return displayedAttributes;
};
const isAttributeEditable = (attributeName: string, entityAttributeType: string) => {
return !(
attributeName === TableConstants.EntityKeyNames.PartitionKey ||
attributeName === TableConstants.EntityKeyNames.RowKey ||
attributeName === TableConstants.EntityKeyNames.Timestamp ||
// As per VSO:189935, Making Binary properties read-only in Edit Entity dialog until we have a full story for it.
entityAttributeType === TableConstants.TableType.Binary
);
};
const getPropertyDisplayValue = (entity: Entities.ITableEntity, name: string, type: string): string => {
const attribute: Entities.ITableEntityAttribute = entity[name];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let displayValue: any = attribute._;
const isBinary: boolean = type === TableConstants.TableType.Binary;
// Showing the value in base64 for binary properties since that is what the Azure Storage Client Library expects.
// This means that, even if the Azure Storage API returns a byte[] of binary content, it needs that same array
// *base64 - encoded * as the value for the updated property or the whole update operation will fail.
if (isBinary && displayValue && $.isArray(displayValue.data)) {
const bytes: number[] = displayValue.data;
displayValue = getBase64DisplayValue(bytes);
}
return displayValue;
};
const getBase64DisplayValue = (bytes: number[]): string => {
let displayValue = "";
try {
const chars: string[] = bytes.map((byte: number) => String.fromCharCode(byte));
const toEncode: string = chars.join("");
displayValue = window.btoa(toEncode);
} catch (error) {
console.error(error);
}
return displayValue;
};
const onSubmit = async (): Promise<void> => {
for (let i = 0; i < entities.length; i++) {
const { property, type } = entities[i];
if (property === "" || property === undefined) {
setFormError(`Property name cannot be empty. Please enter a property name`);
return;
}
if (!type) {
setFormError(`Property type cannot be empty. Please select a type from the dropdown for property ${property}`);
return;
}
}
setIsExecuting(true);
const entity: Entities.ITableEntity = entityFromAttributes(entities);
const newTableDataClient = userContext.apiType === "Cassandra" ? cassandraApiClient : tableDataClient;
const originalDocumentData = userContext.apiType === "Cassandra" ? originalDocument[0] : originalDocument;
try {
const newEntity: Entities.ITableEntity = await newTableDataClient.updateDocument(
queryTablesTab.collection,
originalDocumentData,
entity
);
await tableEntityListViewModel.updateCachedEntity(newEntity);
if (!tryInsertNewHeaders(tableEntityListViewModel, newEntity)) {
tableEntityListViewModel.redrawTableThrottled();
}
tableEntityListViewModel.selected.removeAll();
tableEntityListViewModel.selected.push(newEntity);
} catch (error) {
const errorMessage = getErrorMessage(error);
handleError(errorMessage, "EditTableRow");
throw error;
} finally {
setIsExecuting(false);
}
};
const tryInsertNewHeaders = (viewModel: TableEntityListViewModel, newEntity: Entities.ITableEntity): boolean => {
let newHeaders: string[] = [];
const keys = Object.keys(newEntity);
keys &&
keys.forEach((key: string) => {
if (
!_.contains(viewModel.headers, key) &&
key !== TableEntityProcessor.keyProperties.attachments &&
key !== TableEntityProcessor.keyProperties.etag &&
key !== TableEntityProcessor.keyProperties.resourceId &&
key !== TableEntityProcessor.keyProperties.self &&
(!(userContext.apiType === "Cassandra") || key !== TableConstants.EntityKeyNames.RowKey)
) {
newHeaders.push(key);
}
});
let newHeadersInserted = false;
if (newHeaders.length) {
if (!DataTableUtilities.checkForDefaultHeader(viewModel.headers)) {
newHeaders = viewModel.headers.concat(newHeaders);
}
viewModel.updateHeaders(newHeaders, /* notifyColumnChanges */ true, /* enablePrompt */ false);
newHeadersInserted = true;
}
return newHeadersInserted;
};
// Add new entity row
const addNewEntity = (): void => {
const cloneEntities = [...entities];
cloneEntities.splice(cloneEntities.length, 0, {
property: "",
type: TableConstants.TableType.String,
value: "",
isPropertyTypeDisable: false,
isDeleteOptionVisible: true,
id: cloneEntities.length + 1,
entityValuePlaceholder: "",
isEntityTypeDate: false,
});
setEntities(cloneEntities);
};
// Delete entity row
const deleteEntityAtIndex = (indexToRemove: number): void => {
const cloneEntities = [...entities];
cloneEntities.splice(indexToRemove, 1);
setEntities(cloneEntities);
};
// handle Entity change
const entityChange = (value: string | Date, indexOfInput: number, key: string): void => {
const cloneEntities = [...entities];
if (key === "property") {
cloneEntities[indexOfInput].property = value.toString();
} else if (key === "time") {
cloneEntities[indexOfInput].entityTimeValue = value.toString();
} else {
cloneEntities[indexOfInput].value = value.toString();
}
setEntities(cloneEntities);
};
// handle Entity type
const entityTypeChange = (
_event: React.FormEvent<HTMLDivElement>,
selectedType: IDropdownOption,
indexOfEntity: number
): void => {
const entityValuePlaceholder = getEntityValuePlaceholder(selectedType.key);
const cloneEntities = [...entities];
cloneEntities[indexOfEntity].type = selectedType.key.toString();
cloneEntities[indexOfEntity].entityValuePlaceholder = entityValuePlaceholder;
cloneEntities[indexOfEntity].isEntityTypeDate = selectedType.key === TableConstants.TableType.DateTime;
setEntities(cloneEntities);
};
// Open edit entity value modal
const editEntity = (rowEndex: number): void => {
const entityAttribute: EntityRowType = entities[rowEndex] && entities[rowEndex];
setEntityAttributeValue(entityAttribute.value);
setEntityAttributeProperty(entityAttribute.property);
setSelectedRow(rowEndex);
setIsEntityValuePanelTrue();
};
if (isEntityValuePanelOpen) {
return (
<Stack style={{ padding: "20px 34px" }}>
<Stack horizontal {...columnProps}>
<Image {...backImageProps} src={RevertBackIcon} alt="back" onClick={() => setIsEntityValuePanelFalse()} />
<Label>{entityAttributeProperty}</Label>
</Stack>
<TextField
multiline
rows={5}
value={entityAttributeValue}
onChange={(event, newInput?: string) => {
setEntityAttributeValue(newInput);
entityChange(newInput, selectedRow, "value");
}}
/>
</Stack>
);
}
const props: RightPaneFormProps = {
formError,
isExecuting,
submitButtonText: "Update",
onSubmit,
};
return (
<RightPaneForm {...props}>
<div className="panelMainContent">
{entities.map((entity, index) => {
return (
<TableEntity
key={"" + entity.id + index}
isDeleteOptionVisible={entity.isDeleteOptionVisible}
entityTypeLabel={index === 0 && dataTypeLabel}
entityPropertyLabel={index === 0 && attributeNameLabel}
entityValueLabel={index === 0 && attributeValueLabel}
options={userContext.apiType === "Cassandra" ? cassandraOptions : options}
isPropertyTypeDisable={entity.isPropertyTypeDisable}
entityProperty={entity.property}
selectedKey={entity.type}
entityPropertyPlaceHolder={detailedHelp}
entityValuePlaceholder={entity.entityValuePlaceholder}
entityValue={entity.value?.toString()}
isEntityTypeDate={entity.isEntityTypeDate}
entityTimeValue={entity.entityTimeValue}
isEntityValueDisable={entity.isEntityValueDisable}
onEditEntity={() => editEntity(index)}
onSelectDate={(date: Date) => {
entityChange(date, index, "value");
}}
onDeleteEntity={() => deleteEntityAtIndex(index)}
onEntityPropertyChange={(event, newInput?: string) => {
entityChange(newInput, index, "property");
}}
onEntityTypeChange={(event: React.FormEvent<HTMLDivElement>, selectedParam: IDropdownOption) => {
entityTypeChange(event, selectedParam, index);
}}
onEntityValueChange={(event, newInput?: string) => {
entityChange(newInput, index, "value");
}}
onEntityTimeValueChange={(event, newInput?: string) => {
entityChange(newInput, index, "time");
}}
/>
);
})}
{userContext.apiType !== "Cassandra" && (
<Stack horizontal onClick={addNewEntity} className="addButtonEntiy">
<Image {...imageProps} src={AddPropertyIcon} alt="Add Entity" />
<Text className="addNewParamStyle">{getAddButtonLabel(userContext.apiType)}</Text>
</Stack>
)}
</div>
</RightPaneForm>
);
}; | the_stack |
import { Erc1155 } from "../core/classes/erc-1155";
import { TokenERC1155 } from "contracts";
import { ContractMetadata } from "../core/classes/contract-metadata";
import { ContractRoles } from "../core/classes/contract-roles";
import { ContractRoyalty } from "../core/classes/contract-royalty";
import { ContractPrimarySale } from "../core/classes/contract-sales";
import { Erc1155Enumerable } from "../core/classes/erc-1155-enumerable";
import { IStorage } from "../core/interfaces/IStorage";
import {
NetworkOrSignerOrProvider,
TransactionResult,
TransactionResultWithId,
} from "../core/types";
import { SDKOptions } from "../schema/sdk-options";
import { ContractWrapper } from "../core/classes/contract-wrapper";
import { TokenErc1155ContractSchema } from "../schema/contracts/token-erc1155";
import {
EditionMetadata,
EditionMetadataOrUri,
EditionMetadataOwner,
} from "../schema/tokens/edition";
import { ContractEncoder } from "../core/classes/contract-encoder";
import { ContractEvents } from "../core/classes/contract-events";
import { ContractInterceptor } from "../core/classes/contract-interceptor";
import { ContractPlatformFee } from "../core/classes/contract-platform-fee";
import { BigNumber, BigNumberish, constants } from "ethers";
import { Erc1155SignatureMinting } from "../core/classes/erc-1155-signature-minting";
import { GasCostEstimator } from "../core/classes/gas-cost-estimator";
import { getRoleHash } from "../common";
import { QueryAllParams } from "../types";
import { Erc1155Mintable } from "../core/classes/erc-1155-mintable";
import { Erc1155BatchMintable } from "../core/classes/erc-1155-batch-mintable";
import { ContractAnalytics } from "../core/classes/contract-analytics";
/**
* Create a collection of NFTs that lets you mint multiple copies of each NFT.
*
* @example
*
* ```javascript
* import { ThirdwebSDK } from "@thirdweb-dev/sdk";
*
* const sdk = new ThirdwebSDK("rinkeby");
* const contract = sdk.getEdition("{{contract_address}}");
* ```
*
* @public
*/
export class Edition extends Erc1155<TokenERC1155> {
static contractType = "edition" as const;
static contractRoles = ["admin", "minter", "transfer"] as const;
static contractAbi = require("../../abis/TokenERC1155.json");
private _query = this.query as Erc1155Enumerable;
private _mint = this.mint as Erc1155Mintable;
private _batchMint = this._mint.batch as Erc1155BatchMintable;
/**
* @internal
*/
static schema = TokenErc1155ContractSchema;
public metadata: ContractMetadata<TokenERC1155, typeof Edition.schema>;
public roles: ContractRoles<
TokenERC1155,
typeof Edition.contractRoles[number]
>;
public sales: ContractPrimarySale<TokenERC1155>;
public platformFees: ContractPlatformFee<TokenERC1155>;
public encoder: ContractEncoder<TokenERC1155>;
public estimator: GasCostEstimator<TokenERC1155>;
public events: ContractEvents<TokenERC1155>;
/**
* @internal
*/
public analytics: ContractAnalytics<TokenERC1155>;
/**
* Configure royalties
* @remarks Set your own royalties for the entire contract or per token
* @example
* ```javascript
* // royalties on the whole contract
* contract.royalties.setDefaultRoyaltyInfo({
* seller_fee_basis_points: 100, // 1%
* fee_recipient: "0x..."
* });
* // override royalty for a particular token
* contract.royalties.setTokenRoyaltyInfo(tokenId, {
* seller_fee_basis_points: 500, // 5%
* fee_recipient: "0x..."
* });
* ```
*/
public royalties: ContractRoyalty<TokenERC1155, typeof Edition.schema>;
/**
* Signature Minting
* @remarks Generate dynamic NFTs with your own signature, and let others mint them using that signature.
* @example
* ```javascript
* // see how to craft a payload to sign in the `contract.signature.generate()` documentation
* const signedPayload = contract.signature.generate(payload);
*
* // now anyone can mint the NFT
* const tx = contract.signature.mint(signedPayload);
* const receipt = tx.receipt; // the mint transaction receipt
* const mintedId = tx.id; // the id of the NFT minted
* ```
*/
public signature: Erc1155SignatureMinting;
/**
* @internal
*/
public interceptor: ContractInterceptor<TokenERC1155>;
constructor(
network: NetworkOrSignerOrProvider,
address: string,
storage: IStorage,
options: SDKOptions = {},
contractWrapper = new ContractWrapper<TokenERC1155>(
network,
address,
Edition.contractAbi,
options,
),
) {
super(contractWrapper, storage, options);
this.metadata = new ContractMetadata(
this.contractWrapper,
Edition.schema,
this.storage,
);
this.roles = new ContractRoles(this.contractWrapper, Edition.contractRoles);
this.royalties = new ContractRoyalty(this.contractWrapper, this.metadata);
this.sales = new ContractPrimarySale(this.contractWrapper);
this.encoder = new ContractEncoder(this.contractWrapper);
this.estimator = new GasCostEstimator(this.contractWrapper);
this.events = new ContractEvents(this.contractWrapper);
this.platformFees = new ContractPlatformFee(this.contractWrapper);
this.interceptor = new ContractInterceptor(this.contractWrapper);
this.analytics = new ContractAnalytics(this.contractWrapper);
this.signature = new Erc1155SignatureMinting(
this.contractWrapper,
this.roles,
this.storage,
);
}
/** ******************************
* READ FUNCTIONS
*******************************/
/**
* Get All Minted NFTs
*
* @remarks Get all the data associated with every NFT in this contract.
*
* By default, returns the first 100 NFTs, use queryParams to fetch more.
*
* @example
* ```javascript
* const nfts = await contract.getAll();
* ```
* @param queryParams - optional filtering to only fetch a subset of results.
* @returns The NFT metadata for all NFTs queried.
*/
public async getAll(
queryParams?: QueryAllParams,
): Promise<EditionMetadata[]> {
return this._query.all(queryParams);
}
/**
* Get Owned NFTs
*
* @remarks Get all the data associated with the NFTs owned by a specific wallet.
*
* @example
* ```javascript
* // Address of the wallet to get the NFTs of
* const address = "{{wallet_address}}";
* const nfts = await contract.getOwned(address);
* ```
*
* @returns The NFT metadata for all NFTs in the contract.
*/
public async getOwned(
walletAddress?: string,
): Promise<EditionMetadataOwner[]> {
return this._query.owned(walletAddress);
}
/**
* Get the number of NFTs minted
* @returns the total number of NFTs minted in this contract
* @public
*/
public async getTotalCount(): Promise<BigNumber> {
return this._query.totalCount();
}
/**
* Get whether users can transfer NFTs from this contract
*/
public async isTransferRestricted(): Promise<boolean> {
const anyoneCanTransfer = await this.contractWrapper.readContract.hasRole(
getRoleHash("transfer"),
constants.AddressZero,
);
return !anyoneCanTransfer;
}
/** ******************************
* WRITE FUNCTIONS
*******************************/
/**
* Mint NFT for the connected wallet
*
* @remarks See {@link Edition.mintTo}
*/
public async mintToSelf(
metadataWithSupply: EditionMetadataOrUri,
): Promise<TransactionResultWithId<EditionMetadata>> {
return this._mint.to(
await this.contractWrapper.getSignerAddress(),
metadataWithSupply,
);
}
/**
* Mint an NFT with a limited supply
*
* @remarks Mint an NFT with a limited supply to a specified wallet.
*
* @example
* ```javascript
* // Address of the wallet you want to mint the NFT to
* const toAddress = "{{wallet_address}}"
*
* // Custom metadata of the NFT, note that you can fully customize this metadata with other properties.
* const metadata = {
* name: "Cool NFT",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/image.png"), // This can be an image url or file
* }
*
* const metadataWithSupply = {
* metadata,
* supply: 1000, // The number of this NFT you want to mint
* }
*
* const tx = await contract.mintTo(toAddress, metadataWithSupply);
* const receipt = tx.receipt; // the transaction receipt
* const tokenId = tx.id; // the id of the NFT minted
* const nft = await tx.data(); // (optional) fetch details of minted NFT
* ```
*/
public async mintTo(
to: string,
metadataWithSupply: EditionMetadataOrUri,
): Promise<TransactionResultWithId<EditionMetadata>> {
return this._mint.to(to, metadataWithSupply);
}
/**
* Increase the supply of an existing NFT and mint it to the connected wallet
*
* @param tokenId - the token id of the NFT to increase supply of
* @param additionalSupply - the additional amount to mint
*/
public async mintAdditionalSupply(
tokenId: BigNumberish,
additionalSupply: BigNumberish,
): Promise<TransactionResultWithId<EditionMetadata>> {
return this._mint.additionalSupplyTo(
await this.contractWrapper.getSignerAddress(),
tokenId,
additionalSupply,
);
}
/**
* Increase the supply of an existing NFT and mint it to a given wallet address
*
* @param to - the address to mint to
* @param tokenId - the token id of the NFT to increase supply of
* @param additionalSupply - the additional amount to mint
*/
public async mintAdditionalSupplyTo(
to: string,
tokenId: BigNumberish,
additionalSupply: BigNumberish,
): Promise<TransactionResultWithId<EditionMetadata>> {
return this._mint.additionalSupplyTo(to, tokenId, additionalSupply);
}
/**
* Mint Many NFTs for the connected wallet
*
* @remarks See {@link Edition.mintBatchTo}
*/
public async mintBatch(
metadatas: EditionMetadataOrUri[],
): Promise<TransactionResultWithId<EditionMetadata>[]> {
return this._batchMint.to(
await this.contractWrapper.getSignerAddress(),
metadatas,
);
}
/**
* Mint Many NFTs with limited supplies
*
* @remarks Mint many different NFTs with limited supplies to a specified wallet.
*
* @example
* ```javascript
* // Address of the wallet you want to mint the NFT to
* const toAddress = "{{wallet_address}}"
*
* // Custom metadata and supplies of your NFTs
* const metadataWithSupply = [{
* supply: 50, // The number of this NFT you want to mint
* metadata: {
* name: "Cool NFT #1",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/image.png"), // This can be an image url or file
* },
* }, {
* supply: 100,
* metadata: {
* name: "Cool NFT #2",
* description: "This is a cool NFT",
* image: fs.readFileSync("path/to/image.png"), // This can be an image url or file
* },
* }];
*
* const tx = await contract.mintBatchTo(toAddress, metadataWithSupply);
* const receipt = tx[0].receipt; // same transaction receipt for all minted NFTs
* const firstTokenId = tx[0].id; // token id of the first minted NFT
* const firstNFT = await tx[0].data(); // (optional) fetch details of the first minted NFT
* ```
*/
public async mintBatchTo(
to: string,
metadataWithSupply: EditionMetadataOrUri[],
): Promise<TransactionResultWithId<EditionMetadata>[]> {
return this._batchMint.to(to, metadataWithSupply);
}
/**
* Burn a specified amount of a NFT
*
* @param tokenId - the token Id to burn
* @param amount - amount to burn
*
* @example
* ```javascript
* const result = await contract.burn(tokenId, amount);
* ```
*/
public async burn(
tokenId: BigNumberish,
amount: BigNumberish,
): Promise<TransactionResult> {
const account = await this.contractWrapper.getSignerAddress();
return {
receipt: await this.contractWrapper.sendTransaction("burn", [
account,
tokenId,
amount,
]),
};
}
} | the_stack |
import { autobind } from 'core-decorators';
import {format, parseISO} from 'date-fns';
import { List } from 'immutable';
import React, {Fragment} from 'react';
import { Link } from 'react-router-dom';
import {
ICommentModel,
ICommentScoreModel,
ICommentSummaryScoreModel,
ITagModel,
IUserModel,
} from '../../../models';
import { DATE_FORMAT_LONG } from '../../config';
import { searchLink } from '../../scenes/routes';
import { editAndRescoreComment } from '../../stores/commentActions';
import {
ARTICLE_CATEGORY_TYPE,
ARTICLE_HEADLINE_TYPE,
BOTTOM_BORDER_TRANSITION,
BOX_DEFAULT_SPACING,
BUTTON_LINK_TYPE,
BUTTON_RESET,
CAPTION_TYPE,
COMMENT_DETAIL_BODY_TEXT_TYPE,
COMMENT_DETAIL_DATE_TYPE,
DARK_PRIMARY_TEXT_COLOR,
DARK_SECONDARY_TEXT_COLOR,
DARK_TERTIARY_TEXT_COLOR,
DIVIDER_COLOR,
GREY_COLOR,
GUTTER_DEFAULT_SPACING,
LIGHT_PRIMARY_TEXT_COLOR,
NICE_MIDDLE_BLUE,
TAG_INCOHERENT_COLOR,
TAG_INFLAMMATORY_COLOR,
TAG_OBSCENE_COLOR,
TAG_OFF_TOPIC_COLOR,
TAG_OTHER_COLOR,
TAG_SPAM_COLOR,
TAG_UNSUBSTANTIAL_COLOR,
WHITE_COLOR,
} from '../../styles';
import { css, stylesheet } from '../../utilx';
import { Avatar } from '../Avatar';
import { Button } from '../Button';
import { FlagsSummary } from '../FlagsSummary';
import {
EditIcon,
} from '../Icons';
import { AnnotatedCommentText } from './components/AnnotatedCommentText';
import { AuthorCounts } from './components/AuthorCounts';
import { CommentTags } from './components/CommentTags';
import {
ApprovalRatingRow,
EmailRow,
ICON_SIZE,
IsSubscriberRow,
SourceIdRow,
} from './components/DetailRow';
import { FlagsList } from './components/FlagsList';
import { SummaryScores } from './components/SummaryScore';
const AVATAR_SIZE = 60;
// const COMMENT_WIDTH = 696;
const REPLY_WIDTH = 642;
// Styling by class and inserting style element rather than inline styles
// in order to style ::selection.
const COMMENT_BODY_STYLES = `
.comment-body a {
text-decoration: underline;
}
.comment-body b {
color: #f00;
}
.comment-body::selection,
.comment-body *::selection {
background: ${NICE_MIDDLE_BLUE};
borderColor: ${LIGHT_PRIMARY_TEXT_COLOR};
color: ${LIGHT_PRIMARY_TEXT_COLOR};
}
.tag {
border-bottom-width: 1px;
border-bottom-style: solid;
}
.tag-obscene {
border-bottom-color: ${TAG_OBSCENE_COLOR};
color: ${TAG_OBSCENE_COLOR};
}
.tag-incoherent {
border-bottom-color: ${TAG_INCOHERENT_COLOR};
color: ${TAG_INCOHERENT_COLOR};
}
.tag-spam {
border-bottom-color: ${TAG_SPAM_COLOR};
color: ${TAG_SPAM_COLOR};
}
.tag-off-topic {
border-bottom-color: ${TAG_OFF_TOPIC_COLOR};
color: ${TAG_OFF_TOPIC_COLOR};
}
.tag-inflammatory {
border-bottom-color: ${TAG_INFLAMMATORY_COLOR};
color: ${TAG_INFLAMMATORY_COLOR};
}
.tag-unsubstantial {
border-bottom-color: ${TAG_UNSUBSTANTIAL_COLOR};
color: ${TAG_UNSUBSTANTIAL_COLOR};
}
.tag-other {
border-bottom-color: ${TAG_OTHER_COLOR};
color: ${TAG_OTHER_COLOR};
}
`;
const STYLES = stylesheet({
threaded: {
flexBasis: '100%',
maxWidth: `${REPLY_WIDTH}px`,
},
editButton: {
...BUTTON_RESET,
...CAPTION_TYPE,
color: DARK_SECONDARY_TEXT_COLOR,
borderRadius: 2,
marginTop: '10px',
height: '36px',
width: '36px',
padding: '6px',
cursor: 'pointer',
marginLeft: '10px',
':hover': {
backgroundColor: NICE_MIDDLE_BLUE,
},
':focus': {
backgroundColor: NICE_MIDDLE_BLUE,
outline: 0,
},
},
contentEditableContainer: {
display: 'inline-block',
outline: `2px solid ${DIVIDER_COLOR}`,
outlineOffset: '2px',
userSelect: 'text',
':focus': {
outline: `2px solid ${GREY_COLOR}`,
},
},
commentTaggingContainer: {
display: 'flex',
justifyContent: 'flex-end',
alignItems: 'center',
},
buttonGroup: {
display: 'flex',
flexDirection: 'row',
backgroundColor: WHITE_COLOR,
justifyContent: 'flex-end',
marginTop: `${GUTTER_DEFAULT_SPACING}px`,
},
cancel: {
backgroundColor: WHITE_COLOR,
color: DARK_PRIMARY_TEXT_COLOR,
border: `1px solid ${DIVIDER_COLOR}`,
marginLeft: `${GUTTER_DEFAULT_SPACING}px`,
padding: '8px 17px 7px 17px',
cursor: 'pointer',
':active': {
backgroundColor: DIVIDER_COLOR,
},
':focus': {
backgroundColor: DIVIDER_COLOR,
},
},
save: {
backgroundColor: NICE_MIDDLE_BLUE,
color: WHITE_COLOR,
padding: '8px 17px 7px 17px',
cursor: 'pointer',
},
});
const PROFILE_STYLES = stylesheet({
base: {
width: '100%',
display: 'flex',
flexWrap: 'no-wrap',
alignItems: 'baseline',
padding: `${GUTTER_DEFAULT_SPACING}px 0`,
borderBottom: '2px solid ' + DIVIDER_COLOR,
},
noBorder: {
borderBottom: 'none',
},
header: {
display: 'flex',
width: '100%',
alignItems: 'center',
},
avatar: {
width: AVATAR_SIZE,
height: AVATAR_SIZE,
overflow: 'hidden',
background: DIVIDER_COLOR,
marginRight: `${GUTTER_DEFAULT_SPACING}px`,
},
nameColumn: {
marginLeft: '35px',
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-end',
flex: 1,
},
name: {
...ARTICLE_HEADLINE_TYPE,
color: DARK_PRIMARY_TEXT_COLOR,
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
},
meta: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-between',
alignItems: 'flex-end',
marginTop: '5px',
},
authorName: {
color: DARK_PRIMARY_TEXT_COLOR,
userSelect: 'text',
':focus': {
outline: 0,
textDecoration: 'underline',
},
},
location: {
...CAPTION_TYPE,
color: DARK_SECONDARY_TEXT_COLOR,
marginRight: `${BOX_DEFAULT_SPACING}px`,
userSelect: 'text',
},
details: {
display: 'flex',
flexWrap: 'no-wrap',
},
});
const COMMENT_STYLES = stylesheet({
base: {
display: 'flex',
flexDirection: 'column',
},
meta: {
display: 'flex',
marginTop: `${GUTTER_DEFAULT_SPACING}px`,
marginBottom: `${GUTTER_DEFAULT_SPACING}px`,
},
bullet: {
...ARTICLE_CATEGORY_TYPE,
color: DARK_TERTIARY_TEXT_COLOR,
margin: '0 5px',
},
link: {
color: NICE_MIDDLE_BLUE,
textDecoration: 'none',
':focus': {
outline: 0,
textDecoration: 'underline',
},
},
flags: {
...ARTICLE_CATEGORY_TYPE,
color: DARK_TERTIARY_TEXT_COLOR,
textTransform: 'uppercase',
},
body: {
...COMMENT_DETAIL_BODY_TEXT_TYPE,
color: DARK_PRIMARY_TEXT_COLOR,
fontSize: '20px',
position: 'relative',
wordWrap: 'break-word',
marginBottom: `${GUTTER_DEFAULT_SPACING * 4}px`,
whiteSpace: 'pre-wrap',
},
scoreDetails: {
...BUTTON_LINK_TYPE, BOTTOM_BORDER_TRANSITION,
color: NICE_MIDDLE_BLUE,
marginTop: `${GUTTER_DEFAULT_SPACING}px`,
display: 'block',
maxWidth: 115,
':hover': {
transition: 'all 0.3 ease',
borderBottomColor: NICE_MIDDLE_BLUE,
},
':focus': {
borderBottomColor: NICE_MIDDLE_BLUE,
},
},
metaType: {
...COMMENT_DETAIL_DATE_TYPE,
color: DARK_SECONDARY_TEXT_COLOR,
},
});
export interface ISingleCommentProps {
comment: ICommentModel;
allScores?: Array<ICommentScoreModel>;
allScoresAboveThreshold?: Array<ICommentScoreModel>;
reducedScoresAboveThreshold?: Array<ICommentScoreModel>;
isThreadedComment?: boolean;
isReply?: boolean;
availableTags?: List<ITagModel>;
onScoreClick?(score: ICommentSummaryScoreModel): void;
onTagButtonClick?(tagId: string): Promise<any>;
onCommentTagClick?(commentScore: ICommentScoreModel): void;
onAnnotateTagButtonClick?(tag: string, start: number, end: number): Promise<any>;
url?: string;
loadScores?(commentId: string): void;
getUserById?(id: string): IUserModel;
currentUser?: IUserModel;
commentEditingEnabled?: boolean;
}
export interface ISingleCommentState {
inEditMode: boolean;
isEditHovered: boolean;
isEditFocused: boolean;
}
export class SingleComment extends React.PureComponent<ISingleCommentProps, ISingleCommentState> {
state = {
inEditMode: false,
isEditHovered: false,
isEditFocused: false,
};
authorLocation: HTMLDivElement = null;
authorName: HTMLSpanElement = null;
commentText: HTMLDivElement = null;
@autobind
handleEditCommentClick() {
this.setState({
inEditMode: !this.state.inEditMode,
});
}
@autobind
saveAuthorLocationRef(elem: HTMLDivElement) {
this.authorLocation = elem;
}
@autobind
saveAuthorNameRef(elem: HTMLSpanElement) {
this.authorName = elem;
}
@autobind
saveCommentTextRef(elem: HTMLDivElement) {
this.commentText = elem;
}
@autobind
saveEditedCommentText(e: React.FormEvent<any>) {
e.preventDefault();
const {
comment,
} = this.props;
// grab new author name and location text
const authorName = this.authorName.innerText;
const authorLoc = this.authorLocation.innerText;
const commentText = this.commentText.innerText;
// reset comment text and author
const author = {...comment.author, name: authorName, location: authorLoc};
// send comment text to be update to publisher
editAndRescoreComment(comment.id, commentText, author);
this.setState({
inEditMode: false,
});
}
@autobind
cancelEditedCommentText(e: React.FormEvent<any>) {
e.preventDefault();
this.setState({
inEditMode: false,
});
}
@autobind
onEditMouseEnter() {
this.setState({ isEditHovered: true });
}
@autobind
onEditMouseLeave() {
this.setState({ isEditHovered: false });
}
@autobind
onEditFocus() {
this.setState({ isEditFocused: true });
}
@autobind
onEditBlur() {
this.setState({ isEditFocused: false });
}
@autobind
focusText() {
this.commentText.focus();
}
@autobind
focusName() {
this.authorName.focus();
}
@autobind
focusLocation() {
this.authorLocation.focus();
}
renderAuthor() {
const {comment} = this.props;
const {inEditMode} = this.state;
const { author } = this.props.comment;
if (!author) {
return null;
}
return (
<Fragment>
{author.avatar && <Avatar key="avatarColumn" target={author} size={60}/>}
<div key="nameColumn" {...css(PROFILE_STYLES.nameColumn)}>
<div {...css(PROFILE_STYLES.name)}>
{!inEditMode ? (
<Link
to={searchLink({searchByAuthor: true, term: author.name})}
key="authorName"
{...css(PROFILE_STYLES.authorName)}
>
{author.name}
</Link>
) : (
<span
key="authorNameEditable"
contentEditable
suppressContentEditableWarning
ref={this.saveAuthorNameRef}
onClick={this.focusName}
{...css(STYLES.contentEditableContainer, {minWidth: '300px'})}
>
{author.name}
</span>
)}
</div>
<div {...css(PROFILE_STYLES.meta)}>
<div>
{author.location && (
<div key="location" {...css(PROFILE_STYLES.location)}>
{!inEditMode ? (
<span key="authorLocation">{author.location}</span>
) : (
<span
key="authorLocationEditable"
contentEditable
suppressContentEditableWarning
ref={this.saveAuthorLocationRef}
onClick={this.focusLocation}
{...css(STYLES.contentEditableContainer)}
>
{author.location}
</span>
)}
</div>
)}
</div>
<div {...css(PROFILE_STYLES.details)}>
<AuthorCounts authorSourceId={comment.authorSourceId}/>
{author.approvalRating && (<ApprovalRatingRow approvalRating={author.approvalRating}/>)}
{author.isSubscriber && (<IsSubscriberRow/>)}
{author.email && (<EmailRow author={author}/>)}
{comment.authorSourceId && (<SourceIdRow authorSourceId={comment.authorSourceId}/>)}
</div>
</div>
</div>
</Fragment>
);
}
render() {
const {
comment,
allScoresAboveThreshold,
reducedScoresAboveThreshold,
availableTags,
onTagButtonClick,
onCommentTagClick,
onAnnotateTagButtonClick,
url,
isReply,
isThreadedComment,
onScoreClick,
loadScores,
getUserById,
currentUser,
commentEditingEnabled,
} = this.props;
const {
inEditMode,
isEditHovered,
isEditFocused,
} = this.state;
const created_at = comment.sourceCreatedAt ? format(parseISO(comment.sourceCreatedAt), DATE_FORMAT_LONG) : '';
const bodyStyling = css(COMMENT_STYLES.body);
const className = bodyStyling.className ? bodyStyling.className + ' comment-body' : 'comment-body';
return (
<div {...css(isThreadedComment && isReply && STYLES.threaded)}>
<div
{...css(
PROFILE_STYLES.base,
isThreadedComment && PROFILE_STYLES.noBorder,
)}
>
<div {...css(PROFILE_STYLES.header)}>
{this.renderAuthor()}
</div>
</div>
<div {...css(COMMENT_STYLES.base)}>
<div {...css(STYLES.commentTaggingContainer)}>
<CommentTags
scores={reducedScoresAboveThreshold}
availableTags={availableTags}
onClick={onTagButtonClick}
onCommentTagClick={onCommentTagClick}
/>
{commentEditingEnabled &&
(
<button
aria-label="Edit Comment Text"
onMouseEnter={this.onEditMouseEnter}
onMouseLeave={this.onEditMouseLeave}
onFocus={this.onEditFocus}
onBlur={this.onEditBlur}
{...css(STYLES.editButton)}
onClick={this.handleEditCommentClick}
>
<EditIcon
{...css({
fill: isEditHovered || isEditFocused
? LIGHT_PRIMARY_TEXT_COLOR
: NICE_MIDDLE_BLUE,
})}
size={ICON_SIZE}
/>
</button>
)
}
</div>
<div
{...css(
COMMENT_STYLES.meta,
/* url && COMMENT_STYLES.metaModerating, */
)}
>
<div {...css(COMMENT_STYLES.metaType)}>
{url ? (
<Link key="submittedAt" to={url} {...css(COMMENT_STYLES.link)}>{created_at} </Link>
) : (
<span key="submittedAt">{created_at} </span>
)}
<FlagsSummary comment={comment} full/>
</div>
</div>
<style>{COMMENT_BODY_STYLES}</style>
<div className={className} style={bodyStyling.style}>
{inEditMode ? (
<div>
<div
key="content"
contentEditable
suppressContentEditableWarning
ref={this.saveCommentTextRef}
onClick={this.focusText}
{...css(STYLES.contentEditableContainer)}
>
{comment.text}
</div>
<div
key="buttons"
{...css(STYLES.buttonGroup)}
>
<Button
key="save"
label="Save"
onClick={this.saveEditedCommentText}
buttonStyles={STYLES.save}
/>
<Button
key="cancel"
label="Cancel"
onClick={this.cancelEditedCommentText}
buttonStyles={STYLES.cancel}
/>
</div>
</div>
) : (
<AnnotatedCommentText
scores={allScoresAboveThreshold}
availableTags={availableTags}
text={comment.text}
loadScores={loadScores}
onClick={onAnnotateTagButtonClick}
getUserById={getUserById}
currentUser={currentUser}
/>
)}
</div>
<SummaryScores comment={comment} onScoreClick={onScoreClick}/>
<FlagsList commentId={comment.id}/>
</div>
</div>
);
}
} | the_stack |
import { Day, DayProperty } from './Day';
import { FrequencyValue, FrequencyValueEvery } from './Frequency';
import { Functions as fn } from './Functions';
import { Locales } from './Locale';
import { Schedule, ScheduleInput } from './Schedule';
import { Weekday } from './Weekday';
/**
* Describes a [[Pattern]] given a [[Day]] to base it on.
*
* @param day The day to base the description on.
* @returns The description of the pattern.
*/
export type DescribePattern = (day: Day) => string;
/**
* A rule helps parse [[ScheduleInput]] and determines whether it matches the
* given pattern.
*
* - When a number is given, the input MUST be an array of the same length and contain any values.
* - When an array of numbers is given, the input MUST be an array containing the same values.
* - When a TRUE is given the input MUST contain that property and can be any value.
* - When a FALSE is given the input MAY contain that property (optional).
* - When a property is NOT specified, the input MUST NOT contain that property.
* - When an object with every is given, the input must match the every and offset values (have the same frequency).
*/
export type PatternRule =
number | // has array with this number of elements
number[] | // is array with same values
boolean | // is true or false
FrequencyValueEvery; // is object with matching every and offset
/**
* The set of rules you can specify for determining if a [[ScheduleInput]]
* matches a pattern.
*/
export interface PatternRules
{
dayOfWeek?: PatternRule;
dayOfMonth?: PatternRule;
lastDayOfMonth?: PatternRule;
dayOfYear?: PatternRule;
month?: PatternRule;
week?: PatternRule;
year?: PatternRule;
weekOfYear?: PatternRule;
weekspanOfYear?: PatternRule;
fullWeekOfYear?: PatternRule;
lastWeekspanOfYear?: PatternRule;
lastFullWeekOfYear?: PatternRule;
weekOfMonth?: PatternRule;
weekspanOfMonth?: PatternRule;
fullWeekOfMonth?: PatternRule;
lastWeekspanOfMonth?: PatternRule;
lastFullWeekOfMonth?: PatternRule;
}
/**
* A class which helps describe [[ScheduleInput]] if it matches a pattern.
*/
export class Pattern
{
/**
* The properties in the [[ScheduleInput]] which are compared against the
* rules of a pattern.
*/
public static PROPS: DayProperty[] =
[
'dayOfWeek', 'dayOfMonth', 'lastDayOfMonth', 'dayOfYear',
'month', 'week', 'year',
'weekOfYear', 'weekspanOfYear', 'fullWeekOfYear', 'lastWeekspanOfYear', 'lastFullWeekOfYear',
'weekOfMonth', 'weekspanOfMonth', 'fullWeekOfMonth', 'lastWeekspanOfMonth', 'lastFullWeekOfMonth'
];
/**
* Whether this pattern should be "listed" or not. Visual schedulers may
* provide a shortcut to describing and changing a [[Schedule]] through
* patterns and any pattern where listed is `true` could be an option in a
* list. The default patterns are all listed.
*/
public listed: boolean;
/**
* The function which describes this pattern given a [[Day]] to base it on.
*/
public describe: DescribePattern;
/**
* The name of this pattern. This is not typically displayed to a user, just
* to uniquely identify a pattern.
*/
public name: string;
/**
* The rules for matching a pattern to a [[Schedule]] or applying a pattern to
* a schedule.
*/
public rules: PatternRules;
/**
* Creates a new pattern.
*
* @param name The unique name of the pattern.
* @param listed If the pattern is "listed" [[Pattern.listed]].
* @param describe A function to describe the pattern given a [[Day]].
* @param rules The rules which describe how to detect and apply the pattern
* to schedule input.
*/
public constructor(name: string, listed: boolean, describe: DescribePattern, rules: PatternRules)
{
this.name = name;
this.listed = listed;
this.describe = describe;
this.rules = rules;
}
/**
* Applies this pattern to a [[Schedule]] or [[ScheduleInput]] removing and
* adding any necessary properties from the input to match this pattern -
* based around the day provided.
*
* @param schedule The schedule to update to match this pattern.
* @param day The day to base the schedule on.
* @returns The reference to the input passed in.
*/
public apply<M, I extends ScheduleInput<M> | Schedule<M>>(schedule: I, day: Day): I
{
if (schedule instanceof Schedule)
{
this.applyGeneric(day,
(prop, frequency) => schedule.setFrequency( prop, frequency ),
(prop) => schedule.setFrequency( prop )
);
schedule.updateChecks();
}
else
{
this.applyGeneric(day,
(prop, frequency) => schedule[ prop ] = frequency,
(prop) => delete schedule[ prop ]
);
}
return schedule;
}
/**
* Applies this pattern to any object provided they implement the
* `setFrequency` and `removeFrequency` functions.
*
* @param day The day to base the schedule on.
* @param setFrequency The function which sets the frequency on the object.
* @param removeFrequency The function to remove a frequency from the object.
*/
public applyGeneric(day: Day,
setFrequency: (property: DayProperty, frequency: any) => any,
removeFrequency: (property: DayProperty) => any): void
{
for (const prop of Pattern.PROPS)
{
const rule = this.rules[ prop ];
// Should have one value
if (rule === 1)
{
setFrequency( prop, [day[ prop ]] );
}
// Can be any of the values in the array
if (fn.isArray(rule))
{
setFrequency( prop, rule );
}
// Must not be present
if (!fn.isDefined(rule))
{
removeFrequency( prop );
}
}
}
/**
* Determines whether the given [[Schedule]] or [[ScheduleInput]] matches this
* pattern. Optionally a day can be provided to make sure the day matches the
* schedule and pattern together.
*
* @param schedule The schedule input to test.
* @param exactlyWith A day to further validate against for matching.
* @returns `true` if the schedule was a match to this pattern with the
* day if one was provided, otherwise `false`.
*/
public isMatch<M, I extends ScheduleInput<M> | Schedule<M>>(schedule: I, exactlyWith?: Day): boolean
{
if (schedule instanceof Schedule)
{
return this.isMatchGeneric((prop) => schedule[ prop ].input, exactlyWith);
}
else
{
return this.isMatchGeneric((prop) => schedule[ prop ], exactlyWith);
}
}
/**
* Determines whether the given input matches this pattern. Optionally a day
* can be provided to make sure the day matches the schedule and pattern
* together.
*
* @param input The schedule input to test.
* @param exactlyWith A day to further validate against for matching.
* @returns `true` if the schedule input was a match to this pattern with the
* day if one was provided, otherwise `false`.
*/
public isMatchGeneric(getFrequency: (property: DayProperty) => FrequencyValue, exactlyWith?: Day): boolean
{
const exactly: boolean = fn.isDefined( exactlyWith );
for (const prop of Pattern.PROPS)
{
const rule = this.rules[ prop ];
const curr = getFrequency( prop );
// Optional, skip it
if (rule === false)
{
continue;
}
// Requires any value
if (rule === true && !curr)
{
return false;
}
// Must not be present
if (!fn.isDefined(rule) && curr)
{
return false;
}
// Must be an array of the same size
if (fn.isNumber(rule))
{
if (fn.isArray(curr) && curr.length === rule)
{
if (exactly && curr.indexOf( exactlyWith[ prop ] ) === -1)
{
return false;
}
}
else
{
return false;
}
}
// Must be an array of the same values
if (fn.isArray(rule))
{
if (!fn.isArray(curr))
{
return false;
}
if (rule.length !== curr.length)
{
return false;
}
for (let i = 0; i < rule.length; i++)
{
if (rule[ i ] !== curr[ i ])
{
return false;
}
}
if (exactly && rule.indexOf( exactlyWith[ prop ] ) === -1)
{
return false;
}
}
// Must be an object with same over & offset.
if (fn.isFrequencyValueEvery(rule))
{
if (!fn.isFrequencyValueEvery(curr))
{
return false;
}
const ruleOffset = rule.offset || 0;
const currOffset = curr.offset || 0;
if (currOffset !== ruleOffset || curr.every !== rule.every)
{
return false;
}
if (exactly && (exactlyWith[ prop ] % rule.every) !== ruleOffset)
{
return false;
}
}
}
return true;
}
/**
* Returns the pattern with the given name if one exists. If you add your own
* patterns make sure to add them to [[PatternMap]].
*
* @param name The name of the pattern to return.
* @return The instance to the pattern with the same name.
*/
public static withName(name: string): Pattern
{
return PatternMap[ name ];
}
/**
* Finds a matching pattern to the given input searching through [[Patterns]]
* for matches. Optionally it will only look at patterns where listed = `true`.
*
* @param input The schedule input to use.
* @param listedOnly When `true` only patterns with [[Pattern.listed]] set to
* `true` will be looked at, otherwise all patterns are looked at.
* @param exactlyWith A day to further validate against for matching.
* @see [[Pattern.isMatch]]
*/
public static findMatch<M, I extends ScheduleInput<M> | Schedule<M>>(input: I, listedOnly: boolean = true, exactlyWith?: Day): Pattern
{
for (const pattern of Patterns)
{
if ((pattern.listed || !listedOnly) && pattern.isMatch<M, I>( input, exactlyWith ))
{
return pattern;
}
}
return null;
}
}
/**
* The list of patterns that can be searched through for matches to schedule
* input.
*
* @see [[Pattern.findMatch]]
*/
export let Patterns: Pattern[] = [
new Pattern(
'none', true,
(day) => Locales.current.patternNone(day),
{
year: 1,
month: 1,
dayOfMonth: 1
}
),
new Pattern(
'daily', true,
(day) => Locales.current.patternDaily(day),
{
}
),
new Pattern(
'weekly', true,
(day) => Locales.current.patternWeekly(day),
{
dayOfWeek: 1
}
),
new Pattern(
'monthlyWeek', true,
(day) => Locales.current.patternMonthlyWeek(day),
{
dayOfWeek: 1,
weekspanOfMonth: 1
}
),
new Pattern(
'annually', true,
(day) => Locales.current.patternAnnually(day),
{
month: 1,
dayOfMonth: 1
}
),
new Pattern(
'annuallyMonthWeek', true,
(day) => Locales.current.patternAnnuallyMonthWeek(day),
{
month: 1,
dayOfWeek: 1,
weekspanOfMonth: 1
}
),
new Pattern(
'weekday', true,
(day) => Locales.current.patternWeekday(day),
{
dayOfWeek: [Weekday.MONDAY, Weekday.TUESDAY, Weekday.WEDNESDAY, Weekday.THURSDAY, Weekday.FRIDAY]
}
),
new Pattern(
'monthly', true,
(day) => Locales.current.patternMonthly(day),
{
dayOfMonth: 1
}
),
new Pattern(
'lastDay', true,
(day) => Locales.current.patternLastDay(day),
{
lastDayOfMonth: [1]
}
),
new Pattern(
'lastDayOfMonth', true,
(day) => Locales.current.patternLastDayOfMonth(day),
{
month: 1,
lastDayOfMonth: [1]
}
),
new Pattern(
'lastWeekday', true,
(day) => Locales.current.patternLastWeekday(day),
{
lastWeekspanOfMonth: [0],
dayOfWeek: 1,
month: 1
}
),
new Pattern(
'custom', true,
(day) => Locales.current.patternCustom(day),
{
dayOfWeek: false,
dayOfMonth: false,
lastDayOfMonth: false,
dayOfYear: false,
year: false,
month: false,
week: false,
weekOfYear: false,
weekspanOfYear: false,
fullWeekOfYear: false,
lastWeekspanOfYear: false,
lastFullWeekOfYear: false,
weekOfMonth: false,
weekspanOfMonth: false,
fullWeekOfMonth: false,
lastWeekspanOfMonth: false,
lastFullWeekOfMonth: false
}
)
];
/**
* The map of patterns keyed by their name.
*
* @see [[Pattern.withName]]
*/
export let PatternMap: { [name: string]: Pattern } = {};
for (const pattern of Patterns)
{
PatternMap[ pattern.name ] = pattern;
} | the_stack |
import * as _ from 'lodash';
import { expect } from 'chai';
import * as bSemver from 'balena-semver';
// HACK: Avoid typescript trying to resolve built es2015 files
const nodeRequire = require;
const { mergePineOptions } = nodeRequire(
'../es2015/util',
) as typeof import('../lib/util');
const { getDeviceOsSemverWithVariant } = nodeRequire(
'../es2015/util/device-os-version',
) as typeof import('../lib/util/device-os-version');
describe('Pine option merging', function () {
it('uses the defaults only, if no extra options are provided', function () {
const defaults = { $filter: { id: 1 } };
const result = mergePineOptions(defaults, undefined);
return expect(result).to.deep.equal(defaults);
});
it("uses extra options directly if they don't conflict with defaults", function () {
const extras = {
$filter: { id: 1 },
$select: ['id'],
$expand: {
device: {
$select: ['id'],
$expand: ['application', 'user'],
},
},
$top: 1,
$skip: 1,
};
// @ts-expect-error
const result = mergePineOptions({}, extras);
return expect(result).to.deep.equal(extras);
});
it('overrides top, skip and orderby options', function () {
const result = mergePineOptions(
{
$top: 1,
$skip: 2,
$orderby: 'app_name asc',
},
{
$top: 3,
$skip: 4,
$orderby: 'id asc',
},
);
return expect(result).to.deep.equal({
$top: 3,
$skip: 4,
$orderby: 'id asc',
});
});
it('combines filter options with $and', function () {
// @ts-expect-error
const result = mergePineOptions(
{ $filter: { id: 1 } },
{ $filter: { name: 'MyApp' } },
);
return expect(result).to.deep.equal({
$filter: {
$and: [{ id: 1 }, { name: 'MyApp' }],
},
});
});
it('combines expand options for separate single relationships', function () {
const result = mergePineOptions(
{ $expand: 'device' },
{ $expand: 'application' },
);
return expect(result).to.deep.equal({
$expand: {
device: {},
application: {},
},
});
});
it('combines expand options for separate arrays of relationships', function () {
const result = mergePineOptions(
{ $expand: ['device', 'application'] },
{ $expand: ['application', 'build'] },
);
return expect(result).to.deep.equal({
$expand: {
device: {},
application: {},
build: {},
},
});
});
it('combines identical expand options to a single expand', function () {
const result = mergePineOptions(
{ $expand: 'device' },
{ $expand: 'device' },
);
return expect(result).to.deep.equal({
$expand: { device: {} },
});
});
it('overrides $select params for expand options for the same relationship, if present', function () {
const result = mergePineOptions(
{ $expand: { device: { $select: ['id'] } } },
{ $expand: { device: { $select: ['name'] } } },
);
return expect(result).to.deep.equal({
$expand: { device: { $select: ['name'] } },
});
});
it('adds $filter params for expand options, if present', function () {
const result = mergePineOptions(
{ $expand: 'device' },
{ $expand: { device: { $filter: { name: 'myname' } } } },
);
return expect(result).to.deep.equal({
$expand: { device: { $filter: { name: 'myname' } } },
});
});
it('combines $filter params for expand options for the same relationship, if present', function () {
const result = mergePineOptions(
{ $expand: { device: { $filter: { id: 1 } } } },
{ $expand: { device: { $filter: { name: 'myname' } } } },
);
return expect(result).to.deep.equal({
$expand: {
device: { $filter: { $and: [{ id: 1 }, { name: 'myname' }] } },
},
});
});
it('combines $expand params for expand options for the same relationship, if present', function () {
const result = mergePineOptions(
{ $expand: { device: { $expand: ['application'] } } },
{ $expand: { device: { $expand: ['build'] } } },
);
return expect(result).to.deep.equal({
$expand: {
device: {
$expand: {
application: {},
build: {},
},
},
},
});
});
it('combines $expand params for expand options that are arrays of objects', function () {
const result = mergePineOptions(
{
$expand: [{ device: { $select: ['id'] } }],
},
{
$expand: [
{ device: { $expand: ['build'] } },
{ application: { $expand: ['release'] } },
],
},
);
return expect(result).to.deep.equal({
$expand: {
application: {
$expand: ['release'],
},
device: {
$select: ['id'],
$expand: ['build'],
},
},
});
});
it('combines $expand params for expand options that are arrays of objects with multiple keys', function () {
const result = mergePineOptions(
{
$expand: [
{
device: { $select: ['id'] },
application: { $expand: ['user'] },
},
],
},
{
$expand: [
{
device: { $expand: ['build'] },
application: { $expand: 'release' },
},
],
},
);
return expect(result).to.deep.equal({
$expand: {
application: {
$expand: {
release: {},
user: {},
},
},
device: {
$select: ['id'],
$expand: ['build'],
},
},
});
});
it('rejects any unknown extra options', () =>
// @ts-expect-error
expect(() => mergePineOptions({}, { unknownKey: 'value' })).to.throw(
'Unknown pine option: unknownKey',
));
it('ignores any unknown default options', () =>
// @ts-expect-error
expect(() => mergePineOptions({ unknownKey: 'value' }, {})).not.to.throw());
});
const itShouldCompareVersionsProperly = function (rcompare) {
it('compares simple semver correctly', function () {
expect(rcompare('1.0.0', '1.1.0')).to.equal(1);
expect(rcompare('2.0.0', '1.0.0')).to.equal(-1);
return expect(rcompare('3.0.0', '3.0.0')).to.equal(0);
});
it('puts prerelease below real releases', function () {
expect(rcompare('2.0.0-rc6+rev2', '2.0.0+rev1')).to.equal(1);
return expect(rcompare('2.0.0-rc6.rev2', '2.0.0+rev1')).to.equal(1);
});
it('sorts by rev if the semver otherwise matches', function () {
expect(rcompare('2.0.6+rev3.prod', '2.0.0+rev1')).to.equal(-1);
expect(rcompare('2.0.6+rev3.prod', '2.0.6+rev3.prod')).to.equal(0);
return expect(rcompare('2.0.0+rev1', '2.0.6+rev3.prod')).to.equal(1);
});
it('sorts any rev above no rev', () =>
expect(rcompare('2.0.0', '2.0.0+rev1')).to.equal(1));
it('sorts by non-rev build metadata for matching revs', function () {
expect(rcompare('2.0.6+rev3.dev', '2.0.0+rev1')).to.equal(-1);
expect(rcompare('2.0.0+dev.rev2', '2.0.6+rev3.prod')).to.equal(1);
return expect(rcompare('2.0.0+rev1', '2.0.6+rev3.dev')).to.equal(1);
});
it('correctly sorts a full list', () =>
expect(
[
'1.0.0',
'2.0.0-rc1+rev5',
'2.0.6+rev3.prod',
'2.0.0+rev1',
'2.0.0',
'1.24.0+rev100',
'2.0.6+rev3.dev',
].sort(rcompare),
).to.deep.equal([
'2.0.6+rev3.prod',
'2.0.6+rev3.dev',
'2.0.0+rev1',
'2.0.0',
'2.0.0-rc1+rev5',
'1.24.0+rev100',
'1.0.0',
]));
};
describe('version comparisons', () =>
describe('bSemver.rcompare', () =>
itShouldCompareVersionsProperly(bSemver.rcompare)));
describe('getDeviceOsSemverWithVariant', function () {
it('should not parse invalid semver versions', () =>
_.forEach(
[
['Resin OS ', 'dev'],
['Resin OS ', 'prod'],
['Resin OS 2.0-beta.8', ''],
],
function ([osVersion, osVariant]) {
return expect(
getDeviceOsSemverWithVariant({
os_version: osVersion,
os_variant: osVariant,
}),
).to.equal(null);
},
));
it('should parse plain os versions w/o variant', () =>
_.forEach(
[
['Resin OS 1.2.1', '', '1.2.1'],
['Resin OS 1.6.0', '', '1.6.0'],
['Resin OS 2.0.0-beta.1', '', '2.0.0-beta.1'],
['Resin OS 2.0.0-beta.3', '', '2.0.0-beta.3'],
['Resin OS 2.0.0-beta11.rev1', '', '2.0.0-beta11.rev1'],
['Resin OS 2.0.0-beta.8', '', '2.0.0-beta.8'],
['Resin OS 2.0.0-rc1.rev1', '', '2.0.0-rc1.rev1'],
['Resin OS 2.0.0-rc1.rev2', '', '2.0.0-rc1.rev2'],
['Resin OS 2.0.1-beta.4', '', '2.0.1-beta.4'],
['Resin OS 2.0.1.rev1', '', '2.0.1+rev1'],
['Resin OS 2.0.2-beta.2', '', '2.0.2-beta.2'],
['Resin OS 2.0.2-beta.7', '', '2.0.2-beta.7'],
['Resin OS 2.0.2+rev2', '', '2.0.2+rev2'],
['Resin OS 2.0.6+rev2', '', '2.0.6+rev2'],
],
function ([osVersion, osVariant, expectation]) {
return expect(
getDeviceOsSemverWithVariant({
os_version: osVersion,
os_variant: osVariant,
}),
).to.equal(expectation);
},
));
it('should properly combine the plain os version & variant', () =>
_.forEach(
[
['Resin OS 2.0.0-beta.8', 'prod', '2.0.0-beta.8+prod'],
['balenaOS 2.0.0-beta12.rev1', 'prod', '2.0.0-beta12.rev1+prod'],
['Resin OS 2.0.0-rc1.rev2', 'prod', '2.0.0-rc1.rev2+prod'],
['Resin OS 2.0.0+rev2', 'prod', '2.0.0+rev2.prod'],
['Resin OS 2.0.0+rev3', 'prod', '2.0.0+rev3.prod'],
['Resin OS 2.0.2+rev2', 'dev', '2.0.2+rev2.dev'],
['Resin OS 2.0.3+rev1', 'dev', '2.0.3+rev1.dev'],
['Resin OS 2.0.3+rev1', 'prod', '2.0.3+rev1.prod'],
['Resin OS 2.0.4+rev1', 'dev', '2.0.4+rev1.dev'],
['Resin OS 2.0.4+rev1', 'prod', '2.0.4+rev1.prod'],
['Resin OS 2.0.4+rev2', 'prod', '2.0.4+rev2.prod'],
['Resin OS 2.0.5', 'dev', '2.0.5+dev'],
['Resin OS 2.0.5+rev1', 'dev', '2.0.5+rev1.dev'],
['Resin OS 2.0.5+rev1', 'prod', '2.0.5+rev1.prod'],
['Resin OS 2.0.6+rev1', 'dev', '2.0.6+rev1.dev'],
['Resin OS 2.0.6+rev1', 'prod', '2.0.6+rev1.prod'],
['Resin OS 2.0.6+rev2', 'dev', '2.0.6+rev2.dev'],
['Resin OS 2.0.6+rev2', 'prod', '2.0.6+rev2.prod'],
['Resin OS 2.1.0+rev1', 'dev', '2.1.0+rev1.dev'],
['Resin OS 2.1.0+rev1', 'prod', '2.1.0+rev1.prod'],
['Resin OS 2.2.0+rev1', 'dev', '2.2.0+rev1.dev'],
['Resin OS 2.2.0+rev1', 'prod', '2.2.0+rev1.prod'],
['Resin OS 2.9.0-multi1+rev1', 'dev', '2.9.0-multi1+rev1.dev'],
['Resin OS 2.9.7+rev1', 'dev', '2.9.7+rev1.dev'],
['Resin OS 2.9.7+rev1', 'prod', '2.9.7+rev1.prod'],
['Resin OS 2.12.0+rev1', 'dev', '2.12.0+rev1.dev'],
['Resin OS 2.12.0+rev1', 'prod', '2.12.0+rev1.prod'],
['Resin OS 2.12.1+rev1', 'dev', '2.12.1+rev1.dev'],
['Resin OS 2.12.1+rev1', 'prod', '2.12.1+rev1.prod'],
['Resin OS 2.12.3', 'dev', '2.12.3+dev'],
['Resin OS 2.12.3+rev1', 'dev', '2.12.3+rev1.dev'],
['balenaOS 2.26.0', 'dev', '2.26.0+dev'],
['balenaOS 2.26.0+rev1', 'dev', '2.26.0+rev1.dev'],
['balenaOS 2.26.0+rev1', 'prod', '2.26.0+rev1.prod'],
['balenaOS 2.28.0-beta1.rev1', 'prod', '2.28.0-beta1.rev1+prod'],
['balenaOS 2.28.0+rev1', 'dev', '2.28.0+rev1.dev'],
],
function ([osVersion, osVariant, expectation]) {
return expect(
getDeviceOsSemverWithVariant({
os_version: osVersion,
os_variant: osVariant,
}),
).to.equal(expectation);
},
));
it('should properly parse the os_version with variant suffix w/o os_variant', () =>
_.forEach(
[
['Resin OS 2.0.0-rc6.rev1 (prod)', '', '2.0.0-rc6.rev1+prod'],
['Resin OS 2.0.0.rev1 (prod)', '', '2.0.0+rev1.prod'],
['Resin OS 2.0.0+rev2 (prod)', '', '2.0.0+rev2.prod'],
['Resin OS 2.0.0+rev3 (dev)', '', '2.0.0+rev3.dev'],
['Resin OS 2.0.0+rev3 (prod)', '', '2.0.0+rev3.prod'],
['Resin OS 2.0.0+rev4 (prod)', '', '2.0.0+rev4.prod'],
['Resin OS 2.0.0+rev5 (dev)', '', '2.0.0+rev5.dev'],
],
function ([osVersion, osVariant, expectation]) {
return expect(
getDeviceOsSemverWithVariant({
os_version: osVersion,
os_variant: osVariant,
}),
).to.equal(expectation);
},
));
it('should properly combine the os_version with variant suffix & os_variant', () =>
_.forEach(
[
['Resin OS 2.0.0.rev1 (prod)', 'prod', '2.0.0+rev1.prod'],
['Resin OS 2.0.0+rev2 (prod)', 'prod', '2.0.0+rev2.prod'],
['Resin OS 2.0.0+rev3 (dev)', 'dev', '2.0.0+rev3.dev'],
['Resin OS 2.0.0+rev3 (prod)', 'prod', '2.0.0+rev3.prod'],
['Resin OS 2.0.0+rev4 (prod)', 'prod', '2.0.0+rev4.prod'],
['Resin OS 2.0.0+rev5 (prod)', 'prod', '2.0.0+rev5.prod'],
],
function ([osVersion, osVariant, expectation]) {
return expect(
getDeviceOsSemverWithVariant({
os_version: osVersion,
os_variant: osVariant,
}),
).to.equal(expectation);
},
));
}); | the_stack |
const writingModesAffectingFlexDirection = new Set([
'tb',
'tb-rl',
'vertical-lr',
'vertical-rl',
]);
// eslint-disable-next-line rulesdir/const_enum
export enum PhysicalDirection {
LEFT_TO_RIGHT = 'left-to-right',
RIGHT_TO_LEFT = 'right-to-left',
BOTTOM_TO_TOP = 'bottom-to-top',
TOP_TO_BOTTOM = 'top-to-bottom',
}
type DirectionsDict = {
[key: string]: PhysicalDirection,
};
export type IconInfo = {
iconName: string,
rotate: number,
scaleX: number,
scaleY: number,
};
type ComputedStyles = Map<string, string>;
export function reverseDirection(direction: PhysicalDirection): PhysicalDirection {
if (direction === PhysicalDirection.LEFT_TO_RIGHT) {
return PhysicalDirection.RIGHT_TO_LEFT;
}
if (direction === PhysicalDirection.RIGHT_TO_LEFT) {
return PhysicalDirection.LEFT_TO_RIGHT;
}
if (direction === PhysicalDirection.TOP_TO_BOTTOM) {
return PhysicalDirection.BOTTOM_TO_TOP;
}
if (direction === PhysicalDirection.BOTTOM_TO_TOP) {
return PhysicalDirection.TOP_TO_BOTTOM;
}
throw new Error('Unknown PhysicalFlexDirection');
}
function extendWithReverseDirections(directions: DirectionsDict): DirectionsDict {
return {
...directions,
'row-reverse': reverseDirection(directions.row),
'column-reverse': reverseDirection(directions.column),
};
}
/**
* Returns absolute directions for rows, columns,
* reverse rows and reverse column taking into account the direction and writing-mode attributes.
*/
export function getPhysicalDirections(computedStyles: ComputedStyles): DirectionsDict {
const isRtl = computedStyles.get('direction') === 'rtl';
const writingMode = computedStyles.get('writing-mode');
const isVertical = writingMode && writingModesAffectingFlexDirection.has(writingMode);
if (isVertical) {
return extendWithReverseDirections({
row: isRtl ? PhysicalDirection.BOTTOM_TO_TOP : PhysicalDirection.TOP_TO_BOTTOM,
column: writingMode === 'vertical-lr' ? PhysicalDirection.LEFT_TO_RIGHT : PhysicalDirection.RIGHT_TO_LEFT,
});
}
return extendWithReverseDirections({
row: isRtl ? PhysicalDirection.RIGHT_TO_LEFT : PhysicalDirection.LEFT_TO_RIGHT,
column: PhysicalDirection.TOP_TO_BOTTOM,
});
}
/**
* Rotates the flex direction icon in such way that it indicates
* the desired `direction` and the arrow in the icon is always at the bottom
* or at the right.
*
* By default, the icon is pointing top-down with the arrow on the right-hand side.
*/
export function rotateFlexDirectionIcon(direction: PhysicalDirection): IconInfo {
// Default to LTR.
let flipX = true;
let flipY = false;
let rotate = -90;
if (direction === PhysicalDirection.RIGHT_TO_LEFT) {
rotate = 90;
flipY = false;
flipX = false;
} else if (direction === PhysicalDirection.TOP_TO_BOTTOM) {
rotate = 0;
flipX = false;
flipY = false;
} else if (direction === PhysicalDirection.BOTTOM_TO_TOP) {
rotate = 0;
flipX = false;
flipY = true;
}
return {
iconName: 'flex-direction-icon',
rotate: rotate,
scaleX: flipX ? -1 : 1,
scaleY: flipY ? -1 : 1,
};
}
export function rotateAlignContentIcon(iconName: string, direction: PhysicalDirection): IconInfo {
return {
iconName,
rotate: direction === PhysicalDirection.RIGHT_TO_LEFT ? 90 :
(direction === PhysicalDirection.LEFT_TO_RIGHT ? -90 : 0),
scaleX: 1,
scaleY: 1,
};
}
export function rotateJustifyContentIcon(iconName: string, direction: PhysicalDirection): IconInfo {
return {
iconName,
rotate: direction === PhysicalDirection.TOP_TO_BOTTOM ? 90 :
(direction === PhysicalDirection.BOTTOM_TO_TOP ? -90 : 0),
scaleX: direction === PhysicalDirection.RIGHT_TO_LEFT ? -1 : 1,
scaleY: 1,
};
}
export function rotateJustifyItemsIcon(iconName: string, direction: PhysicalDirection): IconInfo {
return {
iconName,
rotate: direction === PhysicalDirection.TOP_TO_BOTTOM ? 90 :
(direction === PhysicalDirection.BOTTOM_TO_TOP ? -90 : 0),
scaleX: direction === PhysicalDirection.RIGHT_TO_LEFT ? -1 : 1,
scaleY: 1,
};
}
export function rotateAlignItemsIcon(iconName: string, direction: PhysicalDirection): IconInfo {
return {
iconName,
rotate: direction === PhysicalDirection.RIGHT_TO_LEFT ? 90 :
(direction === PhysicalDirection.LEFT_TO_RIGHT ? -90 : 0),
scaleX: 1,
scaleY: 1,
};
}
function flexDirectionIcon(value: string): (styles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles): IconInfo {
const directions = getPhysicalDirections(computedStyles);
return rotateFlexDirectionIcon(directions[value]);
}
return getIcon;
}
function flexAlignContentIcon(iconName: string): (styles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles): IconInfo {
const directions = getPhysicalDirections(computedStyles);
const flexDirectionToPhysicalDirection = new Map([
['column', directions.row],
['row', directions.column],
['column-reverse', directions.row],
['row-reverse', directions.column],
]);
const computedFlexDirection = computedStyles.get('flex-direction') || 'row';
const iconDirection = flexDirectionToPhysicalDirection.get(computedFlexDirection);
if (!iconDirection) {
throw new Error('Unknown direction for flex-align icon');
}
return rotateAlignContentIcon(iconName, iconDirection);
}
return getIcon;
}
function gridAlignContentIcon(iconName: string): (styles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles): IconInfo {
const directions = getPhysicalDirections(computedStyles);
return rotateAlignContentIcon(iconName, directions.column);
}
return getIcon;
}
function flexJustifyContentIcon(iconName: string): (styles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles): IconInfo {
const directions = getPhysicalDirections(computedStyles);
return rotateJustifyContentIcon(iconName, directions[computedStyles.get('flex-direction') || 'row']);
}
return getIcon;
}
function gridJustifyContentIcon(iconName: string): (styles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles): IconInfo {
const directions = getPhysicalDirections(computedStyles);
return rotateJustifyContentIcon(iconName, directions.row);
}
return getIcon;
}
function gridJustifyItemsIcon(iconName: string): (styles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles): IconInfo {
const directions = getPhysicalDirections(computedStyles);
return rotateJustifyItemsIcon(iconName, directions.row);
}
return getIcon;
}
function flexAlignItemsIcon(iconName: string): (styles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles): IconInfo {
const directions = getPhysicalDirections(computedStyles);
const flexDirectionToPhysicalDirection = new Map([
['column', directions.row],
['row', directions.column],
['column-reverse', directions.row],
['row-reverse', directions.column],
]);
const computedFlexDirection = computedStyles.get('flex-direction') || 'row';
const iconDirection = flexDirectionToPhysicalDirection.get(computedFlexDirection);
if (!iconDirection) {
throw new Error('Unknown direction for flex-align icon');
}
return rotateAlignItemsIcon(iconName, iconDirection);
}
return getIcon;
}
function gridAlignItemsIcon(iconName: string): (styles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles): IconInfo {
const directions = getPhysicalDirections(computedStyles);
return rotateAlignItemsIcon(iconName, directions.column);
}
return getIcon;
}
/**
* The baseline icon contains the letter A to indicate that we're aligning based on where the text baseline is.
* Therefore we're not rotating this icon like the others, as this would become confusing. Plus baseline alignment
* is likely only really useful in horizontal flow cases.
*/
function baselineIcon(): IconInfo {
return {
iconName: 'baseline-icon',
rotate: 0,
scaleX: 1,
scaleY: 1,
};
}
function flexAlignSelfIcon(iconName: string): (styles: ComputedStyles, parentStyles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles, parentComputedStyles: ComputedStyles): IconInfo {
return flexAlignItemsIcon(iconName)(parentComputedStyles);
}
return getIcon;
}
function gridAlignSelfIcon(iconName: string): (styles: ComputedStyles, parentStyles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles, parentComputedStyles: ComputedStyles): IconInfo {
return gridAlignItemsIcon(iconName)(parentComputedStyles);
}
return getIcon;
}
export function roateFlexWrapIcon(iconName: string, direction: PhysicalDirection): IconInfo {
return {
iconName,
rotate: direction === PhysicalDirection.BOTTOM_TO_TOP || direction === PhysicalDirection.TOP_TO_BOTTOM ? 90 : 0,
scaleX: 1,
scaleY: 1,
};
}
function flexWrapIcon(iconName: string): (styles: ComputedStyles) => IconInfo {
function getIcon(computedStyles: ComputedStyles): IconInfo {
const directions = getPhysicalDirections(computedStyles);
const computedFlexDirection = computedStyles.get('flex-direction') || 'row';
return roateFlexWrapIcon(iconName, directions[computedFlexDirection]);
}
return getIcon;
}
const flexContainerIcons = new Map([
['flex-direction: row', flexDirectionIcon('row')],
['flex-direction: column', flexDirectionIcon('column')],
['flex-direction: column-reverse', flexDirectionIcon('column-reverse')],
['flex-direction: row-reverse', flexDirectionIcon('row-reverse')],
['flex-direction: initial', flexDirectionIcon('row')],
['flex-direction: unset', flexDirectionIcon('row')],
['flex-direction: revert', flexDirectionIcon('row')],
['align-content: center', flexAlignContentIcon('align-content-center-icon')],
['align-content: space-around', flexAlignContentIcon('align-content-space-around-icon')],
['align-content: space-between', flexAlignContentIcon('align-content-space-between-icon')],
['align-content: stretch', flexAlignContentIcon('align-content-stretch-icon')],
['align-content: space-evenly', flexAlignContentIcon('align-content-space-evenly-icon')],
['align-content: flex-end', flexAlignContentIcon('align-content-end-icon')],
['align-content: flex-start', flexAlignContentIcon('align-content-start-icon')],
// TODO(crbug.com/1139945): Start & end should be enabled once Chromium supports them for flexbox.
// ['align-content: start', flexAlignContentIcon('align-content-start-icon')],
// ['align-content: end', flexAlignContentIcon('align-content-end-icon')],
['align-content: normal', flexAlignContentIcon('align-content-stretch-icon')],
['align-content: revert', flexAlignContentIcon('align-content-stretch-icon')],
['align-content: unset', flexAlignContentIcon('align-content-stretch-icon')],
['align-content: initial', flexAlignContentIcon('align-content-stretch-icon')],
['justify-content: center', flexJustifyContentIcon('justify-content-center-icon')],
['justify-content: space-around', flexJustifyContentIcon('justify-content-space-around-icon')],
['justify-content: space-between', flexJustifyContentIcon('justify-content-space-between-icon')],
['justify-content: space-evenly', flexJustifyContentIcon('justify-content-space-evenly-icon')],
['justify-content: flex-end', flexJustifyContentIcon('justify-content-flex-end-icon')],
['justify-content: flex-start', flexJustifyContentIcon('justify-content-flex-start-icon')],
['align-items: stretch', flexAlignItemsIcon('align-items-stretch-icon')],
['align-items: flex-end', flexAlignItemsIcon('align-items-flex-end-icon')],
['align-items: flex-start', flexAlignItemsIcon('align-items-flex-start-icon')],
['align-items: center', flexAlignItemsIcon('align-items-center-icon')],
['align-items: baseline', baselineIcon],
['align-content: baseline', baselineIcon],
['flex-wrap: wrap', flexWrapIcon('flex-wrap-icon')],
['flex-wrap: nowrap', flexWrapIcon('flex-nowrap-icon')],
]);
const flexItemIcons = new Map([
['align-self: baseline', baselineIcon],
['align-self: center', flexAlignSelfIcon('align-self-center-icon')],
['align-self: flex-start', flexAlignSelfIcon('align-self-flex-start-icon')],
['align-self: flex-end', flexAlignSelfIcon('align-self-flex-end-icon')],
['align-self: stretch', flexAlignSelfIcon('align-self-stretch-icon')],
]);
const gridContainerIcons = new Map([
['align-content: center', gridAlignContentIcon('align-content-center-icon')],
['align-content: space-around', gridAlignContentIcon('align-content-space-around-icon')],
['align-content: space-between', gridAlignContentIcon('align-content-space-between-icon')],
['align-content: stretch', gridAlignContentIcon('align-content-stretch-icon')],
['align-content: space-evenly', gridAlignContentIcon('align-content-space-evenly-icon')],
['align-content: end', gridAlignContentIcon('align-content-end-icon')],
['align-content: start', gridAlignContentIcon('align-content-start-icon')],
['align-content: baseline', baselineIcon],
['justify-content: center', gridJustifyContentIcon('justify-content-center-icon')],
['justify-content: space-around', gridJustifyContentIcon('justify-content-space-around-icon')],
['justify-content: space-between', gridJustifyContentIcon('justify-content-space-between-icon')],
['justify-content: space-evenly', gridJustifyContentIcon('justify-content-space-evenly-icon')],
['justify-content: end', gridJustifyContentIcon('justify-content-flex-end-icon')],
['justify-content: start', gridJustifyContentIcon('justify-content-flex-start-icon')],
['align-items: stretch', gridAlignItemsIcon('align-items-stretch-icon')],
['align-items: end', gridAlignItemsIcon('align-items-flex-end-icon')],
['align-items: start', gridAlignItemsIcon('align-items-flex-start-icon')],
['align-items: center', gridAlignItemsIcon('align-items-center-icon')],
['align-items: baseline', baselineIcon],
['justify-items: center', gridJustifyItemsIcon('justify-items-center-icon')],
['justify-items: stretch', gridJustifyItemsIcon('justify-items-stretch-icon')],
['justify-items: end', gridJustifyItemsIcon('justify-items-end-icon')],
['justify-items: start', gridJustifyItemsIcon('justify-items-start-icon')],
['justify-items: baseline', baselineIcon],
]);
const gridItemIcons = new Map([
['align-self: baseline', baselineIcon],
['align-self: center', gridAlignSelfIcon('align-self-center-icon')],
['align-self: start', gridAlignSelfIcon('align-self-flex-start-icon')],
['align-self: end', gridAlignSelfIcon('align-self-flex-end-icon')],
['align-self: stretch', gridAlignSelfIcon('align-self-stretch-icon')],
]);
const isFlexContainer = (computedStyles?: ComputedStyles|null): boolean => {
const display = computedStyles?.get('display');
return display === 'flex' || display === 'inline-flex';
};
const isGridContainer = (computedStyles?: ComputedStyles|null): boolean => {
const display = computedStyles?.get('display');
return display === 'grid' || display === 'inline-grid';
};
export function findIcon(
text: string, computedStyles: ComputedStyles|null, parentComputedStyles?: ComputedStyles|null): IconInfo|null {
if (isFlexContainer(computedStyles)) {
const icon = findFlexContainerIcon(text, computedStyles);
if (icon) {
return icon;
}
}
if (isFlexContainer(parentComputedStyles)) {
const icon = findFlexItemIcon(text, computedStyles, parentComputedStyles);
if (icon) {
return icon;
}
}
if (isGridContainer(computedStyles)) {
const icon = findGridContainerIcon(text, computedStyles);
if (icon) {
return icon;
}
}
if (isGridContainer(parentComputedStyles)) {
const icon = findGridItemIcon(text, computedStyles, parentComputedStyles);
if (icon) {
return icon;
}
}
return null;
}
export function findFlexContainerIcon(text: string, computedStyles: ComputedStyles|null): IconInfo|null {
const resolver = flexContainerIcons.get(text);
if (resolver) {
return resolver(computedStyles || new Map());
}
return null;
}
export function findFlexItemIcon(
text: string, computedStyles: ComputedStyles|null, parentComputedStyles?: ComputedStyles|null): IconInfo|null {
const resolver = flexItemIcons.get(text);
if (resolver) {
return resolver(computedStyles || new Map(), parentComputedStyles || new Map());
}
return null;
}
export function findGridContainerIcon(text: string, computedStyles: ComputedStyles|null): IconInfo|null {
const resolver = gridContainerIcons.get(text);
if (resolver) {
return resolver(computedStyles || new Map());
}
return null;
}
export function findGridItemIcon(
text: string, computedStyles: ComputedStyles|null, parentComputedStyles?: ComputedStyles|null): IconInfo|null {
const resolver = gridItemIcons.get(text);
if (resolver) {
return resolver(computedStyles || new Map(), parentComputedStyles || new Map());
}
return null;
} | the_stack |
import get from "lodash/get";
import { createTopic } from "@webiny/pubsub";
import Error from "@webiny/error";
import {
AdvancedPublishingWorkflow,
ApwContentReview,
ApwContentReviewCrud,
ApwContentReviewStatus,
ApwContentReviewStepStatus,
ApwContentTypes,
ApwReviewerCrud,
ApwWorkflowStepTypes,
CreateApwParams,
OnAfterContentReviewCreateTopicParams,
OnAfterContentReviewDeleteTopicParams,
OnAfterContentReviewUpdateTopicParams,
OnBeforeContentReviewCreateTopicParams,
OnBeforeContentReviewDeleteTopicParams,
OnBeforeContentReviewUpdateTopicParams
} from "~/types";
import { getNextStepStatus, hasReviewer } from "~/plugins/utils";
import {
NoSignOffProvidedError,
NotAuthorizedError,
PendingChangeRequestsError,
StepInActiveError,
StepMissingError
} from "~/utils/errors";
import { ApwScheduleActionTypes } from "~/scheduler/types";
import {
checkValidDateTime,
filterContentReviewsByRequiresMyAttention,
getPendingRequiredSteps,
INITIAL_CONTENT_REVIEW_CONTENT_SCHEDULE_META
} from "./utils";
export interface CreateContentReviewMethodsParams extends CreateApwParams {
getReviewer: ApwReviewerCrud["get"];
getContentGetter: AdvancedPublishingWorkflow["getContentGetter"];
getContentPublisher: AdvancedPublishingWorkflow["getContentPublisher"];
getContentUnPublisher: AdvancedPublishingWorkflow["getContentUnPublisher"];
}
export function createContentReviewMethods(
params: CreateContentReviewMethodsParams
): ApwContentReviewCrud {
const {
getIdentity,
storageOperations,
getReviewer,
getContentGetter,
getContentPublisher,
getContentUnPublisher,
scheduler,
handlerClient,
getTenant,
getLocale
} = params;
const onBeforeContentReviewCreate = createTopic<OnBeforeContentReviewCreateTopicParams>();
const onAfterContentReviewCreate = createTopic<OnAfterContentReviewCreateTopicParams>();
const onBeforeContentReviewUpdate = createTopic<OnBeforeContentReviewUpdateTopicParams>();
const onAfterContentReviewUpdate = createTopic<OnAfterContentReviewUpdateTopicParams>();
const onBeforeContentReviewDelete = createTopic<OnBeforeContentReviewDeleteTopicParams>();
const onAfterContentReviewDelete = createTopic<OnAfterContentReviewDeleteTopicParams>();
return {
/**
* Lifecycle events
*/
onBeforeContentReviewCreate,
onAfterContentReviewCreate,
onBeforeContentReviewUpdate,
onAfterContentReviewUpdate,
onBeforeContentReviewDelete,
onAfterContentReviewDelete,
async get(id) {
return storageOperations.getContentReview({ id });
},
async list(params) {
if (params.where && params.where.status === "requiresMyAttention") {
return filterContentReviewsByRequiresMyAttention({
listParams: params,
listContentReviews: storageOperations.listContentReviews,
getReviewer,
getIdentity
});
}
return storageOperations.listContentReviews(params);
},
async create(data) {
const input = {
...data,
status: ApwContentReviewStatus.UNDER_REVIEW
};
await onBeforeContentReviewCreate.publish({ input });
const contentReview = await storageOperations.createContentReview({
data: input
});
await onAfterContentReviewCreate.publish({ contentReview });
return contentReview;
},
async update(id, data) {
const original = await storageOperations.getContentReview({ id });
await onBeforeContentReviewUpdate.publish({ original, input: { id, data } });
const contentReview = await storageOperations.updateContentReview({
id,
data
});
await onAfterContentReviewUpdate.publish({
original,
input: { id, data },
contentReview
});
return contentReview;
},
async delete(id) {
const contentReview = await storageOperations.getContentReview({ id });
await onBeforeContentReviewDelete.publish({ contentReview });
await storageOperations.deleteContentReview({ id });
await onAfterContentReviewDelete.publish({ contentReview });
return true;
},
async provideSignOff(this: ApwContentReviewCrud, id, stepId) {
const entry: ApwContentReview = await this.get(id);
const { steps, status } = entry;
const stepIndex = steps.findIndex(step => step.id === stepId);
const currentStep = steps[stepIndex];
const previousStep = steps[stepIndex - 1];
const identity = getIdentity();
const hasPermission = await hasReviewer({
getReviewer,
identity,
step: currentStep
});
/**
* Check whether the sign-off is requested by a reviewer.
*/
if (!hasPermission) {
throw new NotAuthorizedError({ entry, input: { id, step: stepId } });
}
/**
* Don't allow sign off, if previous step is of "mandatory_blocking" type and undone.
*/
if (
previousStep &&
previousStep.status !== ApwContentReviewStepStatus.DONE &&
previousStep.type === ApwWorkflowStepTypes.MANDATORY_BLOCKING
) {
throw new StepMissingError({ entry, input: { id, step: stepId } });
}
/**
* Don't allow sign off, if there are pending change requests.
*/
if (currentStep.pendingChangeRequests > 0) {
throw new PendingChangeRequestsError({ entry, input: { id, step: stepId } });
}
/**
* Don't allow sign off, if current step is not in "active" state.
*/
if (currentStep.status !== ApwContentReviewStepStatus.ACTIVE) {
throw new StepInActiveError({ entry, input: { id, step: stepId } });
}
let previousStepStatus: ApwContentReviewStepStatus;
/*
* Provide sign-off for give step.
*/
const updatedSteps = steps.map((step, index) => {
if (index === stepIndex) {
previousStepStatus = ApwContentReviewStepStatus.DONE;
return {
...step,
status: ApwContentReviewStepStatus.DONE,
signOffProvidedOn: new Date().toISOString(),
signOffProvidedBy: identity
};
}
/**
* Update next steps status based on type.
*/
if (index > stepIndex) {
const previousStep = steps[index - 1];
previousStepStatus = getNextStepStatus(previousStep.type, previousStepStatus);
return {
...step,
status: previousStepStatus
};
}
return step;
});
/**
* Check for pending steps
*/
let newStatus = status;
const pendingRequiredSteps = getPendingRequiredSteps(
updatedSteps,
step => typeof step.signOffProvidedOn !== "string"
);
/**
* If there are no required steps that are pending, set the status to "READY_TO_BE_PUBLISHED".
*/
if (pendingRequiredSteps.length === 0) {
newStatus = ApwContentReviewStatus.READY_TO_BE_PUBLISHED;
}
/**
* Save updated steps.
*/
await this.update(id, {
steps: updatedSteps,
status: newStatus
});
return true;
},
async retractSignOff(this: ApwContentReviewCrud, id, stepId) {
const entry: ApwContentReview = await this.get(id);
const { steps, status } = entry;
const stepIndex = steps.findIndex(step => step.id === stepId);
const currentStep = steps[stepIndex];
const identity = getIdentity();
const hasPermission = await hasReviewer({
getReviewer,
identity,
step: currentStep
});
/**
* Check whether the retract sign-off is requested by a reviewer.
*/
if (!hasPermission) {
throw new NotAuthorizedError({ entry, input: { id, step: stepId } });
}
/**
* Don't allow, if step in not "done" i.e. no sign-off was provided for it.
*/
if (currentStep.status !== ApwContentReviewStepStatus.DONE) {
throw new NoSignOffProvidedError({ entry, input: { id, step: stepId } });
}
let previousStepStatus: ApwContentReviewStepStatus;
/*
* Retract sign-off for give step.
*/
const updatedSteps = steps.map((step, index) => {
if (index === stepIndex) {
previousStepStatus = ApwContentReviewStepStatus.ACTIVE;
return {
...step,
status: previousStepStatus,
signOffProvidedOn: null,
signOffProvidedBy: null
};
}
/**
* Set next step status as "inactive".
*/
if (index > stepIndex) {
const previousStep = steps[index - 1];
previousStepStatus = getNextStepStatus(previousStep.type, previousStepStatus);
return {
...step,
status: previousStepStatus
};
}
return step;
});
/**
* Check for pending steps
*/
let newStatus = status;
const pendingRequiredSteps = getPendingRequiredSteps(
updatedSteps,
step => step.signOffProvidedOn === null
);
/**
* If there are required steps that are pending, set the status to "UNDER_REVIEW".
*/
if (pendingRequiredSteps.length !== 0) {
newStatus = ApwContentReviewStatus.UNDER_REVIEW;
}
await this.update(id, {
steps: updatedSteps,
status: newStatus
});
return true;
},
async isReviewRequired(data) {
const contentGetter = getContentGetter(data.type);
const content = await contentGetter(data.id, data.settings);
let isReviewRequired = false;
let contentReviewId = null;
if (data.type === ApwContentTypes.PAGE) {
contentReviewId = get(content, "settings.apw.contentReviewId");
const workflowId = get(content, "settings.apw.workflowId");
if (workflowId) {
isReviewRequired = true;
}
}
return {
isReviewRequired,
contentReviewId
};
},
async publishContent(this: ApwContentReviewCrud, id: string, datetime) {
const { content, status } = await this.get(id);
const identity = getIdentity();
if (status !== ApwContentReviewStatus.READY_TO_BE_PUBLISHED) {
throw new Error({
message: `Cannot publish content because it is not yet ready to be published.`,
code: "NOT_READY_TO_BE_PUBLISHED",
data: {
id,
status,
content
}
});
}
checkValidDateTime(datetime);
/**
* If datetime is present it means we're scheduling this action.
*/
if (datetime) {
const scheduledActionId = await this.scheduleAction({
action: ApwScheduleActionTypes.PUBLISH,
type: content.type,
entryId: content.id,
datetime
});
/**
* Update scheduled related meta data.
*/
await this.update(id, {
content: {
...content,
scheduledOn: datetime,
scheduledBy: identity.id,
scheduledActionId
}
});
return true;
}
const contentPublisher = getContentPublisher(content.type);
await contentPublisher(content.id, content.settings);
return true;
},
async unpublishContent(this: ApwContentReviewCrud, id: string, datetime) {
const { content, status } = await this.get(id);
const identity = getIdentity();
if (status !== ApwContentReviewStatus.PUBLISHED) {
throw new Error({
message: `Cannot unpublish content because it is not yet published.`,
code: "NOT_YET_PUBLISHED",
data: {
id,
status,
content
}
});
}
checkValidDateTime(datetime);
/**
* If datetime is present it means we're scheduling this action.
*/
if (datetime) {
const scheduledActionId = await this.scheduleAction({
action: ApwScheduleActionTypes.UNPUBLISH,
type: content.type,
entryId: content.id,
datetime
});
/**
* Update scheduled related meta data.
*/
await this.update(id, {
content: {
...content,
scheduledOn: datetime,
scheduledBy: identity.id,
scheduledActionId
}
});
return true;
}
const contentUnPublisher = getContentUnPublisher(content.type);
await contentUnPublisher(content.id, content.settings);
return true;
},
async scheduleAction(data) {
// Save input in DB
const scheduledAction = await scheduler.create(data);
/**
* This function contains logic of lambda invocation.
* Current we're not mocking it, therefore, we're just returning true.
*/
if (process.env.NODE_ENV === "test") {
return scheduledAction.id;
}
// Invoke handler
await handlerClient.invoke({
name: String(process.env.APW_SCHEDULER_SCHEDULE_ACTION_HANDLER),
payload: { tenant: getTenant().id, locale: getLocale().code },
await: false
});
return scheduledAction.id;
},
async deleteScheduledAction(id) {
const contentReview = await this.get(id);
const scheduledActionId = get(contentReview, "content.scheduledActionId");
/**
* Check if there is any action scheduled for this "content review".
*/
if (!scheduledActionId) {
throw new Error({
message: `There is no action scheduled for content review.`,
code: "NO_ACTION_SCHEDULED",
data: {
id
}
});
}
/**
* Delete scheduled action.
*/
await scheduler.delete(scheduledActionId);
/**
* Reset scheduled related meta data.
*/
await this.update(id, {
content: {
...contentReview.content,
...INITIAL_CONTENT_REVIEW_CONTENT_SCHEDULE_META
}
});
return true;
}
};
} | the_stack |
import { DrawProperties } from '../resources/draw-properties';
import { Frame } from '../resources/frame';
import { Mask } from '../resources/mask';
import { SolidLayer } from '../resources/solid-layer';
import { EventHandler } from '../utilities/event-handler';
import { Position2D } from '../utilities/position2d';
import { Rectangle } from '../utilities/rectangle';
import { Stage } from './stage';
/** handel the display of the game images */
export class DisplayImage {
private imgData?: ImageData;
private groundMask?: SolidLayer;
public getWidth(): number {
if (!this.imgData) {
return 0;
}
return this.imgData.width;
}
public getHeight(): number {
if (!this.imgData) {
return 0;
}
return this.imgData.height;
}
constructor(private stage: Stage) {
this.onMouseDown.on((e) => {
if (!e) {
return;
}
this.setDebugPixel(e.x, e.y);
});
}
public onMouseUp = new EventHandler<Position2D>();
public onMouseDown = new EventHandler<Position2D>();
public onMouseMove = new EventHandler<Position2D>();
public onDoubleClick = new EventHandler<Position2D>();
public initSize(width: number, height: number) {
/// create image data
if ((this.imgData) && (this.imgData.width == width) && (this.imgData.height == height)) {
return;
}
const tmpImg = this.stage.createImage(this, width, height);
if (!tmpImg) {
return;
}
this.imgData = tmpImg;
this.clear();
}
public clear() {
if (!this.imgData) {
return;
}
const img = new Uint32Array(this.imgData.data);
for (let i = 0; i < img.length; i++) {
img[i] = 0xFF00FF00;
}
}
/** render the level-background to an image */
public setBackground(groundImage: Uint8ClampedArray, groundMask?: SolidLayer) {
if (!this.imgData) {
return;
}
/// set pixels
this.imgData.data.set(groundImage);
this.groundMask = groundMask;
}
private uint8ClampedColor(colorValue: number): number {
return colorValue & 0xFF;
}
public drawRectangle(rect: Rectangle, red: number, green: number, blue: number) {
this.drawHorizontalLine(rect.x1, rect.y1, rect.x2, red, green, blue);
this.drawHorizontalLine(rect.x1, rect.y2, rect.x2, red, green, blue);
this.drawVerticalLine(rect.x1, rect.y1, rect.y2, red, green, blue);
this.drawVerticalLine(rect.x2, rect.y1, rect.y2, red, green, blue);
}
/** draw a rect to the display */
public drawRect(x: number, y: number, width: number, height: number, red: number, green: number, blue: number) {
const x2 = x + width;
const y2 = y + height;
this.drawHorizontalLine(x, y, x2, red, green, blue);
this.drawHorizontalLine(x, y2, x2, red, green, blue);
this.drawVerticalLine(x, y, y2, red, green, blue);
this.drawVerticalLine(x2, y, y2, red, green, blue);
}
public drawVerticalLine(x1: number, y1: number, y2: number, red: number, green: number, blue: number) {
if (!this.imgData) {
return;
}
red = this.uint8ClampedColor(red);
green = this.uint8ClampedColor(green);
blue = this.uint8ClampedColor(blue);
const destW = this.imgData.width;
const destH = this.imgData.height;
const destData = this.imgData.data;
x1 = (x1 >= destW) ? (destW - 1) : (x1 < 0) ? 0 : x1;
y1 = (y1 >= destH) ? (destH - 1) : (y1 < 0) ? 0 : y1;
y2 = (y2 >= destH) ? (destH - 1) : (y2 < 0) ? 0 : y2;
for (let y = y1; y <= y2; y += 1) {
const destIndex = ((destW * y) + x1) * 4;
destData[destIndex] = red;
destData[destIndex + 1] = green;
destData[destIndex + 2] = blue;
destData[destIndex + 3] = 255;
}
}
public drawHorizontalLine(x1: number, y1: number, x2: number, red: number, green: number, blue: number) {
if (!this.imgData) {
return;
}
red = this.uint8ClampedColor(red);
green = this.uint8ClampedColor(green);
blue = this.uint8ClampedColor(blue);
const destW = this.imgData.width;
const destH = this.imgData.height;
const destData = this.imgData.data;
x1 = (x1 >= destW) ? (destW - 1) : (x1 < 0) ? 0 : x1;
y1 = (y1 >= destH) ? (destH - 1) : (y1 < 0) ? 0 : y1;
x2 = (x2 >= destW) ? (destW - 1) : (x2 < 0) ? 0 : x2;
for (let x = x1; x <= x2; x += 1) {
const destIndex = ((destW * y1) + x) * 4;
destData[destIndex] = red;
destData[destIndex + 1] = green;
destData[destIndex + 2] = blue;
destData[destIndex + 3] = 255;
}
}
/** copy a mask frame to the display */
public drawMask(mask: Mask, posX: number, posY: number) {
if (!this.imgData) {
return;
}
const srcW = mask.width;
const srcH = mask.height;
const srcMask = mask.getMask();
const destW = this.imgData.width;
const destH = this.imgData.height;
const destData = new Uint32Array(this.imgData.data.buffer);
const destX = posX + mask.offsetX;
const destY = posY + mask.offsetY;
for (let y = 0; y < srcH; y++) {
const outY = y + destY;
if ((outY < 0) || (outY >= destH)) {
continue;
}
for (let x = 0; x < srcW; x++) {
const srcIndex = ((srcW * y) + x);
/// ignore transparent pixels
if (srcMask[srcIndex] == 0) {
continue;
}
const outX = x + destX;
if ((outX < 0) || (outX >= destW)) {
continue;
}
const destIndex = ((destW * outY) + outX);
destData[destIndex] = 0xFFFFFFFF;
}
}
}
/** copy a frame to the display - transparent color is changed to (r,g,b) */
public drawFrameCovered(frame: Frame, posX: number, posY: number, red: number, green: number, blue: number) {
if (!this.imgData) {
return;
}
const srcW = frame.width;
const srcH = frame.height;
const srcBuffer = frame.getBuffer();
const srcMask = frame.getMask();
const nullColor = 0xFF << 24 | blue << 16 | green << 8 | red;
const destW = this.imgData.width;
const destH = this.imgData.height;
const destData = new Uint32Array(this.imgData.data.buffer);
const destX = posX + frame.offsetX;
const destY = posY + frame.offsetY;
red = this.uint8ClampedColor(red);
green = this.uint8ClampedColor(green);
blue = this.uint8ClampedColor(blue);
for (let y = 0; y < srcH; y++) {
const outY = y + destY;
if ((outY < 0) || (outY >= destH)) {
continue;
}
for (let x = 0; x < srcW; x++) {
const srcIndex = ((srcW * y) + x);
const outX = x + destX;
if ((outX < 0) || (outX >= destW)) {
continue;
}
const destIndex = ((destW * outY) + outX);
if (srcMask[srcIndex] == 0) {
/// transparent pixel
destData[destIndex] = nullColor;
}
else {
destData[destIndex] = srcBuffer[srcIndex];
}
}
}
}
/** copy a frame to the display */
public drawFrame(frame: Frame, posX: number, posY: number) {
if (!this.imgData) {
return;
}
const srcW = frame.width;
const srcH = frame.height;
const srcBuffer = frame.getBuffer();
const srcMask = frame.getMask();
const destW = this.imgData.width;
const destH = this.imgData.height;
const destData = new Uint32Array(this.imgData.data.buffer);
const destX = posX + frame.offsetX;
const destY = posY + frame.offsetY;
for (let y = 0; y < srcH; y++) {
const outY = y + destY;
if ((outY < 0) || (outY >= destH)) {
continue;
}
for (let x = 0; x < srcW; x++) {
const srcIndex = ((srcW * y) + x);
/// ignore transparent pixels
if (srcMask[srcIndex] == 0) {
continue;
}
const outX = x + destX;
if ((outX < 0) || (outX >= destW)) {
continue;
}
const destIndex = ((destW * outY) + outX);
destData[destIndex] = srcBuffer[srcIndex];
}
}
}
/** copy a frame to the display */
public drawFrameFlags(frame: Frame, posX: number, posY: number, destConfig: DrawProperties) {
if (!this.imgData) {
return;
}
const srcW = frame.width;
const srcH = frame.height;
const srcBuffer = frame.getBuffer();
const srcMask = frame.getMask();
const destW = this.imgData.width;
const destH = this.imgData.height;
const destData = new Uint32Array(this.imgData.data.buffer);
const destX = posX + frame.offsetX;
const destY = posY + frame.offsetY;
const upsideDown = destConfig.isUpsideDown;
const noOverwrite = destConfig.noOverwrite;
const onlyOverwrite = destConfig.onlyOverwrite;
const mask = this.groundMask;
for (let srcY = 0; srcY < srcH; srcY++) {
const outY = srcY + destY;
if ((outY < 0) || (outY >= destH)) {
continue;
}
for (let srcX = 0; srcX < srcW; srcX++) {
const sourceY = upsideDown ? (srcH - srcY - 1) : srcY;
const srcIndex = ((srcW * sourceY) + srcX);
/// ignore transparent pixels
if (srcMask[srcIndex] == 0) {
continue;
}
const outX = srcX + destX;
if ((outX < 0) || (outX >= destW)) {
continue;
}
/// check flags
if (noOverwrite && mask) {
if (mask.hasGroundAt(outX, outY)) {
continue;
}
}
if (onlyOverwrite && mask) {
if (!mask.hasGroundAt(outX, outY)) {
continue;
}
}
/// draw
const destIndex = ((destW * outY) + outX);
destData[destIndex] = srcBuffer[srcIndex];
}
}
}
public setDebugPixel(x: number, y: number) {
if (!this.imgData) {
return;
}
const pointIndex = (this.imgData.width * (y) + x) * 4;
this.imgData.data[pointIndex] = 255;
this.imgData.data[pointIndex + 1] = 0;
this.imgData.data[pointIndex + 2] = 0;
}
public setPixel(x: number, y: number, r: number, g: number, b: number) {
if (!this.imgData) {
return;
}
const pointIndex = (this.imgData.width * (y) + x) * 4;
this.imgData.data[pointIndex] = r;
this.imgData.data[pointIndex + 1] = g;
this.imgData.data[pointIndex + 2] = b;
}
public setScreenPosition(x: number, y: number) {
this.stage.setGameViewPointPosition(x, y);
}
public getImageData() {
return this.imgData;
}
public redraw() {
this.stage.redraw();
}
} | the_stack |
export default class RmpVast {
/**
* @constructor
* @param {string} id - the id for the player container. Required parameter.
* @typedef {object} VpaidSettings
* @property {number} [width]
* @property {number} [height]
* @property {string} [viewMode]
* @property {number} [desiredBitrate]
* @typedef {object} Labels
* @property {string} [skipMessage]
* @property {string} [closeAd]
* @property {string} [textForClickUIOnMobile]
* @typedef {object} RmpVastParams
* @property {number} [ajaxTimeout] - timeout in ms for an AJAX request to load a VAST tag from the ad server. Default 8000.
* @property {number} [creativeLoadTimeout] - timeout in ms to load linear media creative from the server. Default 10000.
* @property {boolean} [ajaxWithCredentials] - AJAX request to load VAST tag from ad server should or should not be made with credentials. Default: false.
* @property {number} [maxNumRedirects] - the number of VAST wrappers the player should follow before triggering an error. Default: 4. Capped at 30 to avoid infinite wrapper loops.
* @property {boolean} [outstream] - Enables outstream ad mode. Default: false.
* @property {boolean} [showControlsForVastPlayer] - Shows VAST player HTML5 default video controls. Only works when debug setting is true. Default: true.
* @property {boolean} [enableVpaid] - Enables VPAID support or not. Default: true.
* @property {boolean} [omidSupport] - Enables OMID (OM Web SDK) support in rmp-vast. Default: true.
* @property {string[]} [omidAllowedVendors] - List of allowed vendors for ad verification. Vendors not listed will be rejected. Default: [].
* @property {string} [omidPathTo] - Path to OM Web SDK script. Default: '../externals/omweb-v1.js'.
* @property {boolean} [autoplay] - The content player will autoplay or not. The possibility of autoplay is not determined by rmp-vast, this information needs to be passed to rmp-vast (see this script for example). Default: false (means a click to play is required).
* @property {string} [partnerName] - partnerName for OMID. Default: 'Radiantmediaplayer'.
* @property {string} [partnerVersion] - partnerVersion for OMID. Default: '3.2.0'.
* @property {VpaidSettings} [vpaidSettings] - information required to properly display VPAID creatives - note that it is up to the parent application of rmp-vast to provide those informations
* @property {Labels} [labels] - information required to properly display VPAID creatives - note that it is up to the parent application of rmp-vast to provide those informations
* @param {RmpVastParams} [params] - an object representing various parameters that can be passed to a rmp-vast instance and that will affect the player inner-workings. Optional parameter.
* @param {boolean} [debug] - display debug console logs in browser dev tools. Default: false. Optional parameter.
*/
constructor(id: string, params?: {
/**
* - timeout in ms for an AJAX request to load a VAST tag from the ad server. Default 8000.
*/
ajaxTimeout?: number;
/**
* - timeout in ms to load linear media creative from the server. Default 10000.
*/
creativeLoadTimeout?: number;
/**
* - AJAX request to load VAST tag from ad server should or should not be made with credentials. Default: false.
*/
ajaxWithCredentials?: boolean;
/**
* - the number of VAST wrappers the player should follow before triggering an error. Default: 4. Capped at 30 to avoid infinite wrapper loops.
*/
maxNumRedirects?: number;
/**
* - Enables outstream ad mode. Default: false.
*/
outstream?: boolean;
/**
* - Shows VAST player HTML5 default video controls. Only works when debug setting is true. Default: true.
*/
showControlsForVastPlayer?: boolean;
/**
* - Enables VPAID support or not. Default: true.
*/
enableVpaid?: boolean;
/**
* - Enables OMID (OM Web SDK) support in rmp-vast. Default: true.
*/
omidSupport?: boolean;
/**
* - List of allowed vendors for ad verification. Vendors not listed will be rejected. Default: [].
*/
omidAllowedVendors?: string[];
/**
* - Path to OM Web SDK script. Default: '../externals/omweb-v1.js'.
*/
omidPathTo?: string;
/**
* - The content player will autoplay or not. The possibility of autoplay is not determined by rmp-vast, this information needs to be passed to rmp-vast (see this script for example). Default: false (means a click to play is required).
*/
autoplay?: boolean;
/**
* - partnerName for OMID. Default: 'Radiantmediaplayer'.
*/
partnerName?: string;
/**
* - partnerVersion for OMID. Default: '3.2.0'.
*/
partnerVersion?: string;
/**
* - information required to properly display VPAID creatives - note that it is up to the parent application of rmp-vast to provide those informations
*/
vpaidSettings?: {
width?: number;
height?: number;
viewMode?: string;
desiredBitrate?: number;
};
/**
* - information required to properly display VPAID creatives - note that it is up to the parent application of rmp-vast to provide those informations
*/
labels?: {
skipMessage?: string;
closeAd?: string;
textForClickUIOnMobile?: string;
};
}, debug?: boolean);
debug: boolean;
id: string;
container: HTMLElement;
contentWrapper: Element;
contentPlayer: Element;
/**
* @private
*/
private addTrackingEvents_;
/**
* @private
*/
private loopAds_;
adPod: boolean;
adPodLength: number;
adSequence: number;
/**
* @private
*/
private getVastTag_;
adTagUrl: string;
/**
* @param {string} vastUrl - the URI to the VAST resource to be loaded
* @param {object} [regulationsInfo] - data for regulations as
* @param {string} [regulationsInfo.regulations] - coppa|gdpr for REGULATIONS macro
* @param {string} [regulationsInfo.limitAdTracking] - 0|1 for LIMITADTRACKING macro
* @param {string} [regulationsInfo.gdprConsent] - Base64-encoded Cookie Value of IAB GDPR consent info for GDPRCONSENT macro
* @param {boolean} [requireCategory] - for enforcement of VAST 4 Ad Categories
* @return {void}
*/
loadAds(vastUrl: string, regulationsInfo?: {
regulations?: string;
limitAdTracking?: string;
gdprConsent?: string;
}, requireCategory?: boolean): void;
requireCategory: boolean;
currentContentSrc: any;
currentContentCurrentTime: any;
/**
* @type {() => void}
*/
play(): void;
/**
* @type {() => void}
*/
pause(): void;
/**
* @type {() => boolean}
*/
getAdPaused(): boolean;
/**
* @type {(level: number) => void}
*/
setVolume(level: number): void;
/**
* @type {() => number}
*/
getVolume(): number;
/**
* @type {(muted: boolean) => void}
*/
setMute(muted: boolean): void;
/**
* @type {() => boolean}
*/
getMute(): boolean;
/**
* @type {() => boolean}
*/
getFullscreen(): boolean;
/**
* @type {() => void}
*/
stopAds(): void;
/**
* @type {() => void}
*/
skipAd(): void;
/**
* @type {() => string}
*/
getAdTagUrl(): string;
/**
* @type {() => string}
*/
getAdMediaUrl(): string;
/**
* @typedef {object} Environment
* @property {number} devicePixelRatio
* @property {number} maxTouchPoints
* @property {boolean} isIpadOS
* @property {array} isIos
* @property {array} isAndroid
* @property {boolean} isMacOSSafari
* @property {boolean} isFirefox
* @property {boolean} isMobile
* @property {boolean} hasNativeFullscreenSupport
* @return {Environment}
*/
getEnvironment(): {
devicePixelRatio: number;
maxTouchPoints: number;
isIpadOS: boolean;
isIos: any[];
isAndroid: any[];
isMacOSSafari: boolean;
isFirefox: boolean;
isMobile: boolean;
hasNativeFullscreenSupport: boolean;
};
/**
* @type {() => boolean}
*/
getAdLinear(): boolean;
/**
* @typedef {object} AdSystem
* @property {string} value
* @property {string} version
* @return {AdSystem}
*/
getAdSystem(): {
value: string;
version: string;
};
/**
* @typedef {object} UniversalAdId
* @property {string} idRegistry
* @property {string} value
* @return {UniversalAdId}
*/
getAdUniversalAdId(): {
idRegistry: string;
value: string;
};
/**
* @type {() => string}
*/
getAdContentType(): string;
/**
* @type {() => string}
*/
getAdTitle(): string;
/**
* @type {() => string}
*/
getAdDescription(): string;
/**
* @typedef {object} Advertiser
* @property {string} id
* @property {string} value
* @return {Advertiser}
*/
getAdAdvertiser(): {
id: string;
value: string;
};
/**
* @typedef {object} Pricing
* @property {string} value
* @property {string} model
* @property {string} currency
* @return {Pricing}
*/
getAdPricing(): {
value: string;
model: string;
currency: string;
};
/**
* @type {() => string}
*/
getAdSurvey(): string;
/**
* @type {() => string}
*/
getAdAdServingId(): string;
/**
* @typedef {object} Category
* @property {string} authority
* @property {string} value
* @return {Category[]}
*/
getAdCategories(): {
authority: string;
value: string;
}[];
/**
* @typedef {object} BlockedAdCategory
* @property {string} authority
* @property {string} value
* @return {BlockedAdCategory[]}
*/
getAdBlockedAdCategories(): {
authority: string;
value: string;
}[];
/**
* @type {() => number}
*/
getAdDuration(): number;
/**
* @type {() => number}
*/
getAdCurrentTime(): number;
/**
* @type {() => number}
*/
getAdRemainingTime(): number;
/**
* @type {() => boolean}
*/
getAdOnStage(): boolean;
/**
* @type {() => number}
*/
getAdMediaWidth(): number;
/**
* @type {() => number}
*/
getAdMediaHeight(): number;
/**
* @type {() => string}
*/
getClickThroughUrl(): string;
/**
* @type {() => number}
*/
getSkipTimeOffset(): number;
/**
* @type {() => boolean}
*/
getIsSkippableAd(): boolean;
/**
* @type {() => boolean}
*/
getContentPlayerCompleted(): boolean;
/**
* @param {boolean} value
* @return {void}
*/
setContentPlayerCompleted(value: boolean): void;
contentPlayerCompleted: boolean;
/**
* @type {() => string}
*/
getAdErrorMessage(): string;
/**
* @type {() => number}
*/
getAdVastErrorCode(): number;
/**
* @type {() => string}
*/
getAdErrorType(): string;
/**
* @type {() => boolean}
*/
getIsUsingContentPlayerForAds(): boolean;
/**
* @type {() => boolean}
*/
getAdSkippableState(): boolean;
/**
* @return {HTMLMediaElement|null}
*/
getVastPlayer(): HTMLMediaElement | null;
/**
* @return {HTMLMediaElement|null}
*/
getContentPlayer(): HTMLMediaElement | null;
/**
* @param {number} inputWidth
* @param {number} inputHeight
* @typedef {object} Companion
* @property {string} adSlotID
* @property {string} altText
* @property {string} companionClickThroughUrl
* @property {string} companionClickTrackingUrl
* @property {number} height
* @property {number} width
* @property {string} imageUrl
* @property {string[]} trackingEventsUri
* @return {Companion[]}
*/
getCompanionAdsList(inputWidth: number, inputHeight: number): {
adSlotID: string;
altText: string;
companionClickThroughUrl: string;
companionClickTrackingUrl: string;
height: number;
width: number;
imageUrl: string;
trackingEventsUri: string[];
}[];
companionAdsList: any[];
/**
* @param {number} index
* @return {HTMLElement|null}
*/
getCompanionAd(index: number): HTMLElement | null;
/**
* @type {() => string}
*/
getCompanionAdsRequiredAttribute(): string;
/**
* @type {() => void}
*/
initialize(): void;
/**
* @type {() => boolean}
*/
getInitialized(): boolean;
/**
* @type {() => void}
*/
destroy(): void;
/**
* @typedef {object} AdPod
* @property {number} adPodCurrentIndex
* @property {number} adPodLength
* @return {AdPod}
*/
getAdPodInfo(): {
adPodCurrentIndex: number;
adPodLength: number;
};
/**
* @type {(width: number, height: number, viewMode: string) => void}
*/
resizeAd(width: number, height: number, viewMode: string): void;
/**
* @type {() => void}
*/
expandAd(): void;
/**
* @type {() => void}
*/
collapseAd(): void;
/**
* @type {() => boolean}
*/
getAdExpanded(): boolean;
/**
* @type {() => string}
*/
getVPAIDCompanionAds(): string;
} | the_stack |
import {
Dispatch,
SetStateAction,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
} from 'react';
// See https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
const useIsomorphicLayoutEffect =
typeof window !== 'undefined' &&
typeof window.document !== 'undefined' &&
typeof window.document.createElement !== 'undefined'
? useLayoutEffect
: useEffect;
// Assign current value to a ref and returns a stable getter to get the latest value.
// This way we are sure to always get latest value provided to hook and
// avoid weird issues due to closures capturing stale values...
// See https://github.com/facebook/react/issues/16956
// See https://overreacted.io/making-setinterval-declarative-with-react-hooks/
const useGetter = <T>(t: T) => {
const ref = useRef(t);
useIsomorphicLayoutEffect(() => {
ref.current = t;
});
return useCallback(() => ref.current, [ref]);
};
type UnknownResult = unknown;
// Convenient to avoid declaring the type of args, which may help reduce type boilerplate
//type UnknownArgs = unknown[];
// TODO unfortunately it seems required for now if we want default param to work...
// See https://twitter.com/sebastienlorber/status/1170003594894106624
type UnknownArgs = any[];
export type AsyncStateStatus =
| 'not-requested'
| 'loading'
| 'success'
| 'error';
export type AsyncState<R> = {
status: AsyncStateStatus;
loading: boolean;
error: Error | undefined;
result: R | undefined;
};
type SetLoading<R> = (asyncState: AsyncState<R>) => AsyncState<R>;
type SetResult<R> = (result: R, asyncState: AsyncState<R>) => AsyncState<R>;
type SetError<R> = (error: Error, asyncState: AsyncState<R>) => AsyncState<R>;
type MaybePromise<T> = Promise<T> | T;
type PromiseCallbackOptions = {
// Permit to know if the success/error belongs to the last async call
isCurrent: () => boolean;
// TODO this can be convenient but need some refactor
// params: Args;
};
export type UseAsyncOptionsNormalized<R> = {
initialState: (options?: UseAsyncOptionsNormalized<R>) => AsyncState<R>;
executeOnMount: boolean;
executeOnUpdate: boolean;
setLoading: SetLoading<R>;
setResult: SetResult<R>;
setError: SetError<R>;
onSuccess: (r: R, options: PromiseCallbackOptions) => void;
onError: (e: Error, options: PromiseCallbackOptions) => void;
};
export type UseAsyncOptions<R> =
| Partial<UseAsyncOptionsNormalized<R>>
| undefined
| null;
const InitialAsyncState: AsyncState<any> = {
status: 'not-requested',
loading: false,
result: undefined,
error: undefined,
};
const InitialAsyncLoadingState: AsyncState<any> = {
status: 'loading',
loading: true,
result: undefined,
error: undefined,
};
const defaultSetLoading: SetLoading<any> = _asyncState =>
InitialAsyncLoadingState;
const defaultSetResult: SetResult<any> = (result, _asyncState) => ({
status: 'success',
loading: false,
result: result,
error: undefined,
});
const defaultSetError: SetError<any> = (error, _asyncState) => ({
status: 'error',
loading: false,
result: undefined,
error: error,
});
const noop = () => {};
const DefaultOptions: UseAsyncOptionsNormalized<any> = {
initialState: options =>
options && options.executeOnMount
? InitialAsyncLoadingState
: InitialAsyncState,
executeOnMount: true,
executeOnUpdate: true,
setLoading: defaultSetLoading,
setResult: defaultSetResult,
setError: defaultSetError,
onSuccess: noop,
onError: noop,
};
const normalizeOptions = <R>(
options: UseAsyncOptions<R>
): UseAsyncOptionsNormalized<R> => ({
...DefaultOptions,
...options,
});
type UseAsyncStateResult<R> = {
value: AsyncState<R>;
set: Dispatch<SetStateAction<AsyncState<R>>>;
merge: (value: Partial<AsyncState<R>>) => void;
reset: () => void;
setLoading: () => void;
setResult: (r: R) => void;
setError: (e: Error) => void;
};
const useAsyncState = <R extends {}>(
options: UseAsyncOptionsNormalized<R>
): UseAsyncStateResult<R> => {
const [value, setValue] = useState<AsyncState<R>>(() =>
options.initialState(options)
);
const reset = useCallback(() => setValue(options.initialState(options)), [
setValue,
options,
]);
const setLoading = useCallback(() => setValue(options.setLoading(value)), [
value,
setValue,
]);
const setResult = useCallback(
(result: R) => setValue(options.setResult(result, value)),
[value, setValue]
);
const setError = useCallback(
(error: Error) => setValue(options.setError(error, value)),
[value, setValue]
);
const merge = useCallback(
(state: Partial<AsyncState<R>>) =>
setValue({
...value,
...state,
}),
[value, setValue]
);
return {
value,
set: setValue,
merge,
reset,
setLoading,
setResult,
setError,
};
};
const useIsMounted = (): (() => boolean) => {
const ref = useRef<boolean>(false);
useEffect(() => {
ref.current = true;
return () => {
ref.current = false;
};
}, []);
return () => ref.current;
};
type UseCurrentPromiseReturn<R> = {
set: (promise: Promise<R>) => void;
get: () => Promise<R> | null;
is: (promise: Promise<R>) => boolean;
};
const useCurrentPromise = <R>(): UseCurrentPromiseReturn<R> => {
const ref = useRef<Promise<R> | null>(null);
return {
set: promise => (ref.current = promise),
get: () => ref.current,
is: promise => ref.current === promise,
};
};
export type UseAsyncReturn<
R = UnknownResult,
Args extends any[] = UnknownArgs
> = AsyncState<R> & {
set: (value: AsyncState<R>) => void;
merge: (value: Partial<AsyncState<R>>) => void;
reset: () => void;
execute: (...args: Args) => Promise<R>;
currentPromise: Promise<R> | null;
currentParams: Args | null;
};
// Relaxed interface which accept both async and sync functions
// Accepting sync function is convenient for useAsyncCallback
const useAsyncInternal = <R = UnknownResult, Args extends any[] = UnknownArgs>(
asyncFunction: (...args: Args) => MaybePromise<R>,
params: Args,
options?: UseAsyncOptions<R>
): UseAsyncReturn<R, Args> => {
// Fallback missing params, only for JS users forgetting the deps array, to prevent infinite loops
// https://github.com/slorber/react-async-hook/issues/27
// @ts-ignore
!params && (params = []);
const normalizedOptions = normalizeOptions<R>(options);
const [currentParams, setCurrentParams] = useState<Args | null>(null);
const AsyncState = useAsyncState<R>(normalizedOptions);
const isMounted = useIsMounted();
const CurrentPromise = useCurrentPromise<R>();
// We only want to handle the promise result/error
// if it is the last operation and the comp is still mounted
const shouldHandlePromise = (p: Promise<R>) =>
isMounted() && CurrentPromise.is(p);
const executeAsyncOperation = (...args: Args): Promise<R> => {
// async ensures errors thrown synchronously are caught (ie, bug when formatting api payloads)
// async ensures promise-like and synchronous functions are handled correctly too
// see https://github.com/slorber/react-async-hook/issues/24
const promise: Promise<R> = (async () => asyncFunction(...args))();
setCurrentParams(args);
CurrentPromise.set(promise);
AsyncState.setLoading();
promise.then(
result => {
if (shouldHandlePromise(promise)) {
AsyncState.setResult(result);
}
normalizedOptions.onSuccess(result, {
isCurrent: () => CurrentPromise.is(promise),
});
},
error => {
if (shouldHandlePromise(promise)) {
AsyncState.setError(error);
}
normalizedOptions.onError(error, {
isCurrent: () => CurrentPromise.is(promise),
});
}
);
return promise;
};
const getLatestExecuteAsyncOperation = useGetter(executeAsyncOperation);
const executeAsyncOperationMemo: (...args: Args) => Promise<R> = useCallback(
(...args) => getLatestExecuteAsyncOperation()(...args),
[getLatestExecuteAsyncOperation]
);
// Keep this outside useEffect, because inside isMounted()
// will be true as the component is already mounted when it's run
const isMounting = !isMounted();
useEffect(() => {
const execute = () => getLatestExecuteAsyncOperation()(...params);
isMounting && normalizedOptions.executeOnMount && execute();
!isMounting && normalizedOptions.executeOnUpdate && execute();
}, params);
return {
...AsyncState.value,
set: AsyncState.set,
merge: AsyncState.merge,
reset: AsyncState.reset,
execute: executeAsyncOperationMemo,
currentPromise: CurrentPromise.get(),
currentParams,
};
};
// override to allow passing an async function with no args:
// gives more user-freedom to create an inline async function
export function useAsync<R = UnknownResult, Args extends any[] = UnknownArgs>(
asyncFunction: () => Promise<R>,
params: Args,
options?: UseAsyncOptions<R>
): UseAsyncReturn<R, Args>;
export function useAsync<R = UnknownResult, Args extends any[] = UnknownArgs>(
asyncFunction: (...args: Args) => Promise<R>,
params: Args,
options?: UseAsyncOptions<R>
): UseAsyncReturn<R, Args>;
export function useAsync<R = UnknownResult, Args extends any[] = UnknownArgs>(
asyncFunction: (...args: Args) => Promise<R>,
params: Args,
options?: UseAsyncOptions<R>
): UseAsyncReturn<R, Args> {
return useAsyncInternal(asyncFunction, params, options);
}
type AddArg<H, T extends any[]> = ((h: H, ...t: T) => void) extends ((
...r: infer R
) => void)
? R
: never;
export const useAsyncAbortable = <
R = UnknownResult,
Args extends any[] = UnknownArgs
>(
asyncFunction: (...args: AddArg<AbortSignal, Args>) => Promise<R>,
params: Args,
options?: UseAsyncOptions<R>
): UseAsyncReturn<R, Args> => {
const abortControllerRef = useRef<AbortController>();
// Wrap the original async function and enhance it with abortion login
const asyncFunctionWrapper: (...args: Args) => Promise<R> = async (
...p: Args
) => {
// Cancel previous async call
if (abortControllerRef.current) {
abortControllerRef.current.abort();
}
// Create/store new abort controller for next async call
const abortController = new AbortController();
abortControllerRef.current = abortController;
try {
// @ts-ignore // TODO how to type this?
return await asyncFunction(abortController.signal, ...p);
} finally {
// Unset abortController ref if response is already there,
// as it's not needed anymore to try to abort it (would it be no-op?)
if (abortControllerRef.current === abortController) {
abortControllerRef.current = undefined;
}
}
};
return useAsync(asyncFunctionWrapper, params, options);
};
// keep compat with TS < 3.5
type LegacyOmit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
// Some options are not allowed for useAsyncCallback
export type UseAsyncCallbackOptions<R> =
| LegacyOmit<
Partial<UseAsyncOptionsNormalized<R>>,
'executeOnMount' | 'executeOnUpdate' | 'initialState'
>
| undefined
| null;
export const useAsyncCallback = <
R = UnknownResult,
Args extends any[] = UnknownArgs
>(
asyncFunction: (...args: Args) => MaybePromise<R>,
options?: UseAsyncCallbackOptions<R>
): UseAsyncReturn<R, Args> => {
return useAsyncInternal(
asyncFunction,
// Hacky but in such case we don't need the params,
// because async function is only executed manually
[] as any,
{
...options,
executeOnMount: false,
executeOnUpdate: false,
}
);
}; | the_stack |
import assert = require("assert")
import * as cp from 'child_process'
import { promisify } from 'util'
import { STSClient, AssumeRoleCommand } from '@aws-sdk/client-sts'
import { CreateBucketCommand, DeleteBucketCommand, DeleteBucketPolicyCommand, PutBucketPolicyCommand, S3 } from '@aws-sdk/client-s3'
import { logger } from "./logger"
import Config from "../config"
import { IApplicationData } from "./application"
import { GB } from "../constants"
const exec = promisify(cp.exec)
export enum BUCKET_ACL {
private = 'private',
readonly = 'public-read',
public = 'public-read-write'
}
type MinioCommandExecOuput = {
status: "success" | 'error',
error?: any
[key: string]: any
}
export class MinioAgent {
static readonly MC_TARGET = 'oss'
static readonly BUCKET_ACLS = [
BUCKET_ACL.private,
BUCKET_ACL.readonly,
BUCKET_ACL.public
]
/**
* Storage API entry point
*/
get endpoint() {
return Config.MINIO_CONFIG?.endpoint?.internal
}
static async New() {
const ma = new MinioAgent()
await ma.mc_set_alias()
return ma
}
/**
* @deprecated constructor() is unsupported, use `await MinioAgent.New()` instead
*/
constructor() { }
/**
* Create s3 client
* @returns
*/
getClient() {
return new S3({
endpoint: this.endpoint,
credentials: {
accessKeyId: Config.MINIO_CONFIG.access_key,
secretAccessKey: Config.MINIO_CONFIG.access_secret
},
forcePathStyle: true,
region: Config.MINIO_CONFIG.region
})
}
/**
* Create s3 client of application
* @param app
* @returns
*/
public getApplicationSTSClient(app: IApplicationData) {
return new STSClient({
endpoint: Config.MINIO_CONFIG.endpoint.internal,
credentials: {
accessKeyId: app.appid,
secretAccessKey: app.config.oss_access_secret,
},
region: Config.MINIO_CONFIG.region
})
}
/**
* Generate application full-granted STS
* @param app
* @param duration_seconds
* @returns
*/
public async getApplicationSTS(app: IApplicationData, duration_seconds: number) {
const s3 = this.getApplicationSTSClient(app)
const policy = await this.getSTSPolicy()
const cmd = new AssumeRoleCommand({
DurationSeconds: duration_seconds,
Policy: policy,
RoleArn: 'arn:xxx:xxx:xxx:xxxx',
RoleSessionName: app.appid
})
return await s3.send(cmd)
}
/**
* Create a minio user
* @param username the username aka access_key
* @param password the password aka access_secret
* @returns
*/
public async createUser(username: string, password: string) {
assert.ok(username, 'empty username got')
assert.ok(password, 'empty password got')
const sub_cmd = `admin user add ${MinioAgent.MC_TARGET} ${username} ${password}`
return await this.mc_exec(sub_cmd)
}
/**
* Set an existed policy to the user
* @param username
* @param policy_name
* @returns
*/
public async setUserPolicy(username: string, policy_name: string) {
assert.ok(username, 'empty username got')
assert.ok(policy_name, 'empty policy_name got')
const sub_cmd = `admin policy set ${MinioAgent.MC_TARGET} ${policy_name} user=${username}`
return await this.mc_exec(sub_cmd)
}
/**
* add service account to the user
* @param username
* @returns
*/
public async addServiceAccount(username: string) {
assert.ok(username, 'empty username got')
const sub_cmd = `admin user svcacct add ${MinioAgent.MC_TARGET} ${username}`
return await this.mc_exec(sub_cmd)
}
/**
* add service account to the user
* @param username
* @returns
*/
public async removeServiceAccount(sa_access_key: string) {
assert.ok(sa_access_key, 'empty sa_access_key got')
const sub_cmd = `admin user svcacct remove ${MinioAgent.MC_TARGET} ${sa_access_key}`
return await this.mc_exec(sub_cmd)
}
/**
* Create bucket
* @param name
* @param options
* @returns
*/
public async createBucket(name: string, options: { acl?: BUCKET_ACL, with_lock?: boolean, quota?: number }) {
assert.ok(name, 'empty bubcket name got')
const acl = options.acl || BUCKET_ACL.private
const s3 = this.getClient()
const cmd = new CreateBucketCommand({
Bucket: name,
ACL: acl,
CreateBucketConfiguration: {
LocationConstraint: Config.MINIO_CONFIG.region
},
ObjectLockEnabledForBucket: options?.with_lock ?? false
})
const res = await s3.send(cmd)
if (res?.$metadata?.httpStatusCode === 200) {
await this.setBucketACL(name, acl)
const quota = options?.quota || 1 * GB
await this.setBucketQuota(name, quota)
}
return res
}
/**
* Update bucket
* @param name bucket name
* @param mode bucket mode
* @returns
*/
public async setBucketACL(name: string, mode: BUCKET_ACL) {
assert.ok(name, 'empty bubcket name got')
const s3 = this.getClient()
if (mode === BUCKET_ACL.private) {
const cmd = new DeleteBucketPolicyCommand({ Bucket: name })
return await s3.send(cmd)
}
let policy = ''
if (mode === BUCKET_ACL.readonly) policy = await this.getReadonlyPolicy(name)
if (mode === BUCKET_ACL.public) policy = await this.getPublicPolicy(name)
const cmd = new PutBucketPolicyCommand({ Bucket: name, Policy: policy })
return await s3.send(cmd)
}
/**
* Get bucket stats
* @param name
*/
public async statsBucket(name: string) {
assert.ok(name, 'empty bubcket name got')
type GetBucketUsedSizeOutput = {
prefix: string,
size: number,
objects: number,
isVersions: boolean
} & MinioCommandExecOuput
const sub_cmd = `du ${MinioAgent.MC_TARGET}/${name}`
const res = await this.mc_exec(sub_cmd)
return res as GetBucketUsedSizeOutput
}
/**
* Set bucket quota
* @param name the bucket name
* @param quota bucket quota size in bytes
*/
public async setBucketQuota(name: string, quota: number) {
assert.ok(name, 'empty bubcket name got')
const sub_cmd = `admin bucket quota ${MinioAgent.MC_TARGET}/${name} --hard ${quota}`
return await this.mc_exec(sub_cmd)
}
/**
* Get bucket quota
* @param name
* @returns
*/
public async getBucketQuota(name: string) {
assert.ok(name, 'empty bubcket name got')
const sub_cmd = `admin bucket quota ${MinioAgent.MC_TARGET}/${name}`
return await this.mc_exec(sub_cmd)
}
/**
* Clear bucket quota
* @param name
* @returns
*/
public async clearBucketQuota(name: string) {
assert.ok(name, 'empty bubcket name got')
const sub_cmd = `admin bucket quota ${MinioAgent.MC_TARGET}/${name} --clear`
return await this.mc_exec(sub_cmd)
}
/**
* Delete bucket
* @param name bucket name
* @returns
*/
public async deleteBucket(name: string) {
assert.ok(name, 'empty bubcket name got')
const s3 = this.getClient()
const cmd = new DeleteBucketCommand({ Bucket: name })
return await s3.send(cmd)
}
/**
* Create an user policy
* @param policy_name
* @param policy_json_path
* @returns
*/
public async createUserPolicy(policy_name: string, policy_json_path: string) {
assert.ok(policy_name, 'empty policy_name got')
assert.ok(policy_json_path, 'empty policy_json_path got')
const sub_cmd = `admin policy add ${MinioAgent.MC_TARGET} ${policy_name} ${policy_json_path}`
return await this.mc_exec(sub_cmd)
}
/**
* Execute minio client shell
* @param sub_cmd
* @returns
*/
private async mc_exec(sub_cmd: string) {
const mc_path = process.env.MINIO_CLIENT_PATH || 'mc'
const cmd = `${mc_path} ${sub_cmd} --json`
try {
const { stdout } = await exec(cmd)
const json: MinioCommandExecOuput = JSON.parse(stdout)
return json
} catch (error) {
logger.error(`failed to exec command: {${cmd}}`, error)
return {
status: 'error',
error: error
} as MinioCommandExecOuput
}
}
/**
* Set minio target
* @returns
*/
async mc_set_alias() {
const access_key = Config.MINIO_CONFIG.access_key
const access_secret = Config.MINIO_CONFIG.access_secret
const cmd = `alias set ${MinioAgent.MC_TARGET} ${this.endpoint} ${access_key} ${access_secret}`
return await this.mc_exec(cmd)
}
/**
* Get readonly policy for a bucket
* @param bucket
* @returns
*/
async getReadonlyPolicy(bucket: string) {
const policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"AWS": [
"*"
]
},
"Action": [
"s3:GetObject"
],
"Resource": [
`arn:aws:s3:::${bucket}/*`
]
}
]
}
return JSON.stringify(policy)
}
/**
* Get public policy for a bucket
* @param bucket
* @returns
*/
async getPublicPolicy(bucket: string) {
const policy = {
"Statement": [
{
"Action": [
"s3:GetBucketLocation",
"s3:ListBucket",
"s3:ListBucketMultipartUploads"
],
"Effect": "Allow",
"Principal": {
"AWS": [
"*"
]
},
"Resource": [
`arn:aws:s3:::${bucket}`
]
},
{
"Action": [
"s3:AbortMultipartUpload",
"s3:DeleteObject",
"s3:GetObject",
"s3:ListMultipartUploadParts",
"s3:PutObject"
],
"Effect": "Allow",
"Principal": {
"AWS": [
"*"
]
},
"Resource": [
`arn:aws:s3:::${bucket}/*`
]
}
],
"Version": "2012-10-17"
}
return JSON.stringify(policy)
}
async getSTSPolicy() {
const policy = { "Version": "2012-10-17", "Statement": [{ "Sid": `app-sts-full-grant`, "Effect": "Allow", "Action": "s3:*", "Resource": "arn:aws:s3:::*" }] }
return JSON.stringify(policy)
}
} | the_stack |
import * as Web3 from 'web3';
import * as BigNumber from 'bignumber.js';
import { typedSignatureHash, recoverTypedSignature } from 'eth-sig-util';
declare const localStorage; // possibly missing
export { BigNumber };
// helper types
/**
* [[MicroChannel.proof]] data type
*/
export interface MicroProof {
/**
* Balance value, shifted by token decimals
*/
balance: BigNumber;
/**
* Balance signature
*/
sig?: string;
}
/**
* [[MicroRaiden.channel]] state data blueprint
*/
export interface MicroChannel {
/**
* Sender/client's account address
*/
account: string;
/**
* Receiver/server's account address
*/
receiver: string;
/**
* Open channel block number
*/
block: number;
/**
* Current balance proof
*/
proof: MicroProof;
/**
* Next balance proof, persisted with [[MicroRaiden.confirmPayment]]
*/
next_proof?: MicroProof;
/**
* Cooperative close signature from receiver
*/
closing_sig?: string;
}
/**
* [[MicroRaiden.getChannelInfo]] result
*/
export interface MicroChannelInfo {
/**
* Current channel state, one of 'opened', 'closed' or 'settled'
*/
state: string;
/**
* Block of current state (opened=open block number,
* closed=channel close requested block number, settled=settlement block number)
*/
block: number;
/**
* Current channel deposited sum
*/
deposit: BigNumber;
/**
* Value already taken from the channel
*/
withdrawn: BigNumber;
}
/**
* [[MicroRaiden.getTokenInfo]] result
*/
export interface MicroTokenInfo {
name: string;
symbol: string;
decimals: number;
balance: BigNumber;
}
/**
* Array member type to be sent to eth_signTypedData
*/
interface MsgParam {
type: string;
name: string;
value: string;
}
/**
* ChannelCreated event arguments
*/
interface ChannelCreatedArgs {
_sender_address: string;
_receiver_address: string;
}
/**
* ChannelCloseRequested event arguments
*/
interface ChannelCloseRequestedArgs {
_sender_address: string;
_receiver_address: string;
_open_block_number: BigNumber;
}
/**
* ChannelSettled event arguments
*/
interface ChannelSettledArgs {
_sender_address: string;
_receiver_address: string;
_open_block_number: BigNumber;
}
// utils
/**
* Convert a callback-based func to return a promise
*
* It'll return a function which, when called, will pass all received
* parameters to the wrapped method, and return a promise which will be
* resolved which callback data passed as last parameter
*
* @param obj A object containing the method to be called
* @param method A method name of obj to be promisified
* @returns A method wrapper which returns a promise
*/
export function promisify<T>(obj: any, method: string): (...args: any[]) => Promise<T> {
return (...params) =>
new Promise((resolve, reject) =>
obj[method](...params, (err, res) => err ? reject(err) : resolve(res)));
}
/**
* Promise-based deferred class
*/
export class Deferred<T> {
resolve: (res: T) => void;
reject: (err: Error) => void;
promise = new Promise<T>((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
/**
* Async sleep: returns a promise which will resolve after timeout
*
* @param timeout Timeout before promise is resolved, in milliseconds
* @returns Promise which will be resolved after timeout
*/
export function asyncSleep(timeout: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, timeout));
}
/**
* Encode strings and numbers as hex, left-padded, if required.
*
* 0x prefix not added,
*
* @param val Value to be hex-encoded
* @param zPadLength Left-pad with zeroes to this number of characters
* @returns hex-encoded value
*/
export function encodeHex(val: string|number|BigNumber, zPadLength?: number): string {
/* Encode a string or number as hexadecimal, without '0x' prefix */
if (typeof val === 'number' || val instanceof BigNumber ) {
val = val.toString(16);
} else {
val = Array.from(<string>val).map((char: string) =>
char.charCodeAt(0).toString(16).padStart(2, '0'))
.join('');
}
return val.padStart(zPadLength || 0, '0');
}
/**
* Main MicroRaiden client class
*
* Contains all methods to interact with a MicroRaiden channel through a web3
* instance.
*/
export class MicroRaiden {
/**
* Web3 instance
*/
web3: Web3;
/**
* Currently set channel info. May be loaded through [[loadStoredChannel]],
* [[loadChannelFromBlockchain]], or stored and set manually with [[setChannel]]
*/
channel: MicroChannel;
/**
* Token contract instance
*/
token: Web3.ContractInstance;
/**
* Channel manager contract instance
*/
contract: Web3.ContractInstance;
/**
* Token decimals
*/
decimals: number = 0;
/**
* Challenge period for uncooperative close, setup in channel manager
*/
challenge: number;
/**
* Block number in which channel manager was created, or before.
* Just a hint to avoid [[loadChannelFromBlockchain]] to scan whole network
* for ChannelCreated events, default to 0
*/
startBlock: number;
/**
* MicroRaiden constructor
*
* @param web3 Web3 http url, or object with currentProvider property
* @param contractAddr Channel manager contract address
* @param contractABI Channel manager ABI
* @param tokenAddr Token address, must be the same setup in channel manager
* @param tokenABI Token ABI
* @param startBlock Block in which channel manager was deployed
*/
constructor(
web3: string | { currentProvider: any },
contractAddr: string,
contractABI: any[],
tokenAddr: string,
tokenABI: any[],
startBlock?: number,
) {
if (!web3) {
web3 = 'http://localhost:8545';
}
if (typeof web3 === 'string') {
this.web3 = new Web3(new Web3.providers.HttpProvider(web3));
} else if (web3['currentProvider']) {
this.web3 = new Web3(web3.currentProvider);
} else {
throw new Error('Invalid web3 provider');
}
this.contract = this.web3.eth.contract(contractABI).at(contractAddr);
this.token = this.web3.eth.contract(tokenABI).at(tokenAddr);
this.startBlock = startBlock || 0;
}
// utils
/**
* Convert number to BigNumber
*
* Takes into account configured token, taking in account the token decimals
*
* @param value Number or numeric-string to be converted
* @returns BigNumber representation of value * 10^decimals
*/
num2tkn(value?: number|string): BigNumber {
return new BigNumber(value || 0).shift(this.decimals);
}
/**
* Convert BigNumber to number
*
* Takes into account configured token, taking in account the token decimals
* Caution: it may add imprecisions due to javascript's native number limitations
*
* @param bal Value to be converted
* @returns JS's native number representation of bal
*/
tkn2num(bal: BigNumber): number {
return new BigNumber(bal).shift(-this.decimals).toNumber();
}
/**
* Watch for a particular transaction hash to have given confirmations
*
* @param txHash Transaction hash to wait for
* @param confirmations Number of confirmations to wait after tx is mined
* @returns Promise to mined receipt of transaction */
private async waitTx(txHash: string, confirmations?: number): Promise<Web3.TransactionReceipt> {
confirmations = +confirmations || 0;
const blockStart = await promisify<number>(this.web3.eth, 'getBlockNumber')();
do {
const [ receipt, block ] = await Promise.all([
await promisify<Web3.TransactionReceipt>(this.web3.eth, 'getTransactionReceipt')(txHash),
await promisify<number>(this.web3.eth, 'getBlockNumber')(),
]);
if (!receipt || !receipt.blockNumber) {
console.log('Waiting tx..', block - blockStart);
} else if (block - receipt.blockNumber < confirmations) {
console.log('Waiting confirmations...', block - receipt.blockNumber);
} else {
return receipt;
}
await asyncSleep(2e3);
} while (true);
}
private getBalanceProofSignatureParams(proof: MicroProof): MsgParam[] {
return [
{
type: 'string',
name: 'message_id',
value: 'Sender balance proof signature',
},
{
type: 'address',
name: 'receiver',
value: this.channel.receiver,
},
{
type: 'uint32',
name: 'block_created',
value: '' + this.channel.block,
},
{
type: 'uint192',
name: 'balance',
value: proof.balance.toString(),
},
{
type: 'address',
name: 'contract',
value: this.contract.address,
},
];
}
/**
* Get contract's configured challenge's period
*
* As it calls the contract method, can be used for validating that
* contract's address has code in current network
*
* @returns Promise to challenge period number, in blocks
*/
async getChallengePeriod(): Promise<number> {
this.challenge = (await promisify<BigNumber>(
this.contract.challenge_period,
'call'
)()).toNumber();
if (!(this.challenge > 0))
throw new Error('Invalid challenge');
return this.challenge;
}
// instance methods
/**
* If localStorage is available, try to load a channel from it
*
* Indexed by given account and receiver
*
* @param account Sender/client's account address
* @param receiver Receiver/server's account address
* @returns True if a channel data was found, false otherwise
*/
loadStoredChannel(account: string, receiver: string): boolean {
if (typeof localStorage === 'undefined') {
delete this.channel;
return false;
}
const key = [account, receiver].join('|');
const value = localStorage.getItem(key);
if (value) {
const channel = JSON.parse(value);
if (!channel || !channel.proof || !channel.proof.balance) {
return false;
}
channel.proof.balance = new BigNumber(channel.proof.balance);
if (channel.next_proof)
channel.next_proof.balance = new BigNumber(channel.next_proof.balance);
this.channel = channel;
return true;
} else {
delete this.channel;
return false;
}
}
/**
* Forget current channel and remove it from localStorage, if available
*/
forgetStoredChannel(): void {
if (!this.channel) {
return;
}
if (typeof localStorage !== 'undefined') {
const key = [this.channel.account, this.channel.receiver].join('|');
localStorage.removeItem(key);
}
delete this.channel;
}
/**
* Scan the blockchain for an open channel, and load it with 0 balance
*
* The 0 balance may be overwritten with [[setBalance]] if
* server replies with a updated balance on first request.
* It should ask user for signing the zero-balance proof
* Throws/reject if no open channel was found
*
* @param account Sender/client's account address
* @param receiver Receiver/server's account address
* @returns Promise to channel info, if a channel was found
*/
async loadChannelFromBlockchain(account: string, receiver: string): Promise<MicroChannel> {
const openEvents = await promisify<Web3.DecodedLogEntryEvent<ChannelCreatedArgs>[]>(this.contract.ChannelCreated({
_sender_address: account,
_receiver_address: receiver,
}, {
fromBlock: this.startBlock,
toBlock: 'latest'
}), 'get')();
if (!openEvents || openEvents.length === 0) {
throw new Error('No channel found for this account');
}
const minBlock = Math.min.apply(null, openEvents.map((ev) => ev.blockNumber));
const [ closeEvents, settleEvents, currentBlock, challenge ] = await Promise.all([
promisify<Web3.DecodedLogEntryEvent<ChannelCloseRequestedArgs>[]>(this.contract.ChannelCloseRequested({
_sender_address: account,
_receiver_address: receiver,
}, {
fromBlock: minBlock,
toBlock: 'latest'
}), 'get')(),
promisify<Web3.DecodedLogEntryEvent<ChannelSettledArgs>[]>(this.contract.ChannelSettled({
_sender_address: account,
_receiver_address: receiver,
}, {
fromBlock: minBlock,
toBlock: 'latest'
}), 'get')(),
promisify<number>(this.web3.eth, 'getBlockNumber')(),
this.getChallengePeriod(),
]);
const stillOpen = openEvents.filter((ev) => {
for (let sev of settleEvents) {
if (sev.args._open_block_number.eq(ev.blockNumber))
return false;
}
for (let cev of closeEvents) {
if (cev.args._open_block_number.eq(ev.blockNumber) &&
cev.blockNumber + challenge > currentBlock)
return false;
}
return true;
});
let openChannel: MicroChannel;
for (let ev of stillOpen) {
let channel: MicroChannel = {
account,
receiver,
block: ev.blockNumber,
proof: { balance: new BigNumber(0) },
};
try {
await this.getChannelInfo(channel);
openChannel = channel;
break;
} catch (err) {
console.debug('Invalid channel', channel, err);
continue;
}
}
if (!openChannel) {
throw new Error('No open and valid channels found from ' + stillOpen.length);
}
this.setChannel(openChannel);
return this.channel;
}
/**
* Set [[channel]] info
*
* Can be used to externally [re]store an externally persisted channel info
*
* @param channel Channel info to be set
*/
setChannel(channel: MicroChannel): void {
this.channel = channel;
if (typeof localStorage !== 'undefined') {
const key = [this.channel.account, this.channel.receiver].join('|');
localStorage.setItem(key, JSON.stringify(this.channel));
}
}
/**
* Health check for currently configured channel info
*
* @param channel Channel to test. Default to [[channel]]
* @returns True if channel is valid, false otherwise
*/
isChannelValid(channel?: MicroChannel): boolean {
if (!channel) {
channel = this.channel;
}
if (!channel || !channel.receiver || !channel.block
|| !channel.proof || !channel.account) {
return false;
}
return true;
}
/**
* Get available accounts from web3 providers
*
* @returns Promise to accounts addresses array
*/
async getAccounts(): Promise<string[]> {
return await promisify<string[]>(this.web3.eth, 'getAccounts')();
}
/**
* Get token details such as name, symbol and decimals.
*
* If account is provided, returns also account balance for this token.
*
* @param account Address to be queried for current token balance
* @returns Promise to [[MicroTokenInfo]] data
*/
async getTokenInfo(account?: string): Promise<MicroTokenInfo> {
const [name, symbol, decimals, balance] = await Promise.all([
promisify<string>(this.token.name, 'call')(),
promisify<string>(this.token.symbol, 'call')(),
promisify<BigNumber>(this.token.decimals, 'call')().then((d) => d.toNumber()),
account ? promisify<BigNumber>(this.token.balanceOf, 'call')(account) : null
]);
this.decimals = decimals;
return { name, symbol, decimals, balance };
}
/**
* Get channel details such as current state (one of opened, closed or
* settled), block in which it was set and current deposited amount
*
* @param channel Channel to get info from. Default to [[channel]]
* @returns Promise to [[MicroChannelInfo]] data
*/
async getChannelInfo(channel?: MicroChannel): Promise<MicroChannelInfo> {
if (!channel) {
channel = this.channel;
}
if (!this.isChannelValid(channel)) {
throw new Error('No valid channelInfo');
}
const closeEvents = await promisify<Web3.DecodedLogEntryEvent<ChannelCloseRequestedArgs>[]>(this.contract.ChannelCloseRequested({
_sender_address: channel.account,
_receiver_address: channel.receiver,
_open_block_number: channel.block,
}, {
fromBlock: channel.block,
toBlock: 'latest'
}), 'get')();
let closed: number;
if (!closeEvents || closeEvents.length === 0) {
closed = 0;
} else {
closed = closeEvents[0].blockNumber;
}
const settleEvents = await promisify<Web3.DecodedLogEntryEvent<ChannelSettledArgs>[]>(this.contract.ChannelSettled({
_sender_address: channel.account,
_receiver_address: channel.receiver,
_open_block_number: channel.block,
}, {
fromBlock: closed || channel.block,
toBlock: 'latest'
}), 'get')();
let settled: number;
if (!settleEvents || settleEvents.length === 0) {
settled = 0;
} else {
settled = settleEvents[0].blockNumber;
}
// for settled channel, getChannelInfo call will fail, so we return before
if (settled) {
return {
'state': 'settled',
'block': settled,
'deposit': new BigNumber(0),
'withdrawn': new BigNumber(0),
};
}
const info = await promisify<BigNumber[]>(this.contract.getChannelInfo, 'call')(
channel.account,
channel.receiver,
channel.block,
{ from: channel.account });
if (!(info[1].gt(0))) {
throw new Error('Invalid channel deposit: '+JSON.stringify(info));
}
return {
'state': closed ? 'closed' : 'opened',
'block': closed || channel.block,
'deposit': info[1],
'withdrawn': info[4],
};
}
/**
* Open a channel for account to receiver, depositing some tokens on it
*
* Should work with both ERC20/ERC223 tokens.
* Replaces current [[channel]] data
*
* @param account Sender/client's account address
* @param receiver Receiver/server's account address
* @param deposit Tokens to be initially deposited in the channel
* @returns Promise to [[MicroChannel]] info object
*/
async openChannel(account: string, receiver: string, deposit: BigNumber): Promise<MicroChannel> {
if (this.isChannelValid()) {
console.warn('Already valid channel will be forgotten:', this.channel);
}
// first, check if there's enough balance
const balance = await promisify<BigNumber>(this.token.balanceOf, 'call')(account, { from: account });
if (!(balance.gte(deposit))) {
throw new Error(`Not enough tokens.
Token balance = ${balance}, required = ${deposit}`);
}
console.log('Token balance', this.token.address, balance);
// call transfer to make the deposit, automatic support for ERC20/223 token
let transferTxHash: string;
if (typeof this.token.transfer['address,uint256,bytes'] === 'function') {
// ERC223
// transfer tokens directly to the channel manager contract
transferTxHash = await promisify<string>(this.token.transfer['address,uint256,bytes'], 'sendTransaction')(
this.contract.address,
deposit,
account + receiver.replace(/^0x/i, ''), // _data (3rd param) is sender (20B) + receiver (20B)
{ from: account, gas: 100e3 });
} else {
// ERC20
// send 'approve' transaction to token contract
await promisify<string>(this.token.approve, 'sendTransaction')(
this.contract.address,
deposit,
{ from: account, gas: 130e3 });
// send 'createChannel' transaction to channel manager contract
transferTxHash = await promisify<string>(this.contract.createChannel, 'sendTransaction')(
receiver,
deposit,
{ from: account, gas: 130e3 });
}
console.log('transferTxHash', transferTxHash);
// wait for 'transfer' transaction to be mined
const receipt = await this.waitTx(transferTxHash, 1);
// call getChannelInfo to be sure channel was created
const info = await promisify<BigNumber[]>(this.contract.getChannelInfo, 'call')(
account,
receiver,
receipt.blockNumber,
{ from: account });
if (!(info[1].gt(0))) {
throw new Error('No deposit found!');
}
this.setChannel({
account,
receiver,
block: receipt.blockNumber,
proof: { balance: new BigNumber(0) },
});
// return channel
return this.channel;
}
/**
* Top up current channel, by depositing some [more] tokens to it
*
* Should work with both ERC20/ERC223 tokens
*
* @param deposit Tokens to be deposited in the channel
* @returns Promise to tx hash
*/
async topUpChannel(deposit: BigNumber): Promise<string> {
if (!this.isChannelValid()) {
throw new Error('No valid channelInfo');
}
const account = this.channel.account;
// first, check if there's enough balance
const balance = await promisify<BigNumber>(this.token.balanceOf, 'call')(account, { from: account });
if (!(balance.gte(deposit))) {
throw new Error(`Not enough tokens.
Token balance = ${balance}, required = ${deposit}`);
}
console.log('Token balance', this.token.address, balance);
// automatically support both ERC20 and ERC223 tokens
let transferTxHash: string;
if (typeof this.token.transfer['address,uint256,bytes'] === 'function') {
// ERC223, just send token.transfer transaction
// transfer tokens directly to the channel manager contract
transferTxHash = await promisify<string>(this.token.transfer['address,uint256,bytes'], 'sendTransaction')(
this.contract.address,
deposit,
// sender goes as 3rd param (20B), plus receiver (20B) and blocknumber (4B)
this.channel.account +
this.channel.receiver.replace(/^0x/i, '') +
encodeHex(this.channel.block, 8),
{ from: account, gas: 70e3 });
} else {
// ERC20, approve channel manager contract to handle our tokens, then topUp
// send 'approve' transaction to token contract
await promisify<string>(this.token.approve, 'sendTransaction')(
this.contract.address,
deposit,
{ from: account, gas: 100e3 });
// send 'topUp' transaction to channel manager contract
transferTxHash = await promisify<string>(this.contract.topUp, 'sendTransaction')(
this.channel.receiver,
this.channel.block,
deposit,
{ from: account, gas: 100e3 });
}
console.log('transferTxHash', transferTxHash);
// wait for 'transfer' transaction to be mined
await this.waitTx(transferTxHash, 1);
return transferTxHash;
}
/**
* Close current channel
*
* Optional parameter is signed cooperative close from receiver, if available.
* If cooperative close was successful, channel is already settled after this
* method is resolved.
* Else, it enters 'closed' state, and should be settled after settlement
* period, configured in contract.
*
* @param closingSig Cooperative-close signature from receiver
* @returns Promise to closing tx hash
*/
async closeChannel(closingSig?: string): Promise<string> {
if (!this.isChannelValid()) {
throw new Error('No valid channelInfo');
}
const info = await this.getChannelInfo();
if (info.state !== 'opened') {
throw new Error('Tried closing already closed channel');
}
if (this.channel.closing_sig) {
closingSig = this.channel.closing_sig;
} else if (closingSig) {
this.setChannel(Object.assign(
{},
this.channel,
{ closing_sig: closingSig },
));
}
console.log(`Closing channel. Cooperative = ${closingSig}`);
let proof: MicroProof;
if (closingSig && !this.channel.proof.sig) {
proof = await this.signNewProof(this.channel.proof);
} else {
proof = this.channel.proof;
}
const txHash = closingSig ?
await promisify<string>(this.contract.cooperativeClose, 'sendTransaction')(
this.channel.receiver,
this.channel.block,
proof.balance,
proof.sig,
closingSig,
{ from: this.channel.account, gas: 120e3 }) :
await promisify<string>(this.contract.uncooperativeClose, 'sendTransaction')(
this.channel.receiver,
this.channel.block,
proof.balance,
{ from: this.channel.account , gas: 100e3 });
console.log('closeTxHash', txHash);
await this.waitTx(txHash, 0);
return txHash;
}
/**
* If channel was not cooperatively closed, and after settlement period,
* this function settles the channel, distributing the tokens to sender and
* receiver.
*
* @returns Promise to settlement tx hash
*/
async settleChannel(): Promise<string> {
if (!this.isChannelValid()) {
throw new Error('No valid channelInfo');
}
const [ info, currentBlock ] = await Promise.all([
this.getChannelInfo(),
promisify<number>(this.web3.eth, 'getBlockNumber')()
]);
if (info.state !== 'closed') {
throw new Error(`Tried settling opened or settled channel: ${info.state}`);
} else if (this.challenge && currentBlock < info.block + this.challenge){
throw new Error(`Tried settling inside challenge period: ${currentBlock} < ${info.block} + ${this.challenge}`);
}
const txHash = await promisify<string>(this.contract.settle, 'sendTransaction')(
this.channel.receiver,
this.channel.block,
{ from: this.channel.account, gas: 120e3 });
console.log('settleTxHash', txHash);
await this.waitTx(txHash, 0);
return txHash;
}
/**
* Ask user for signing a string with (personal|eth)_sign
*
* @param msg Data to be signed
* @returns Promise to signature
*/
async signMessage(msg: string): Promise<string> {
if (!this.isChannelValid()) {
throw new Error('No valid channelInfo');
}
const hex = msg.startsWith('0x') ? msg : ( '0x' + encodeHex(msg) );
console.log(`Signing "${msg}" => ${hex}, account: ${this.channel.account}`);
let sig: string;
try {
sig = await promisify<string>(this.web3.personal, 'sign')(hex, this.channel.account);
} catch (err) {
if (err.message &&
(err.message.includes('Method not found') ||
err.message.includes('is not a function') ||
err.message.includes('not supported'))) {
sig = await promisify<string>(this.web3.eth, 'sign')(this.channel.account, hex);
} else {
throw err;
}
}
return sig;
}
/**
* Ask user for signing a channel balance
*
* Notice it's the final balance, not the increment, and that the new
* balance is set in [[MicroChannel.next_proof]], requiring a
* [[confirmPayment]] call to persist it, after successful
* request.
* Implementation can choose to call confirmPayment right after this call
* resolves, assuming request will be successful after payment is signed.
* Tries to use eth_signTypedData (from EIP712), tries to use personal sign
* if it fails.
*
* @param proof Balance proof to be signed
* @returns Promise to signature
*/
async signNewProof(proof?: MicroProof): Promise<MicroProof> {
if (!this.isChannelValid()) {
throw new Error('No valid channelInfo');
}
console.log('signNewProof', proof);
if (!proof) {
proof = this.channel.proof;
}
if (proof.sig) {
return proof;
}
const params = this.getBalanceProofSignatureParams(proof);
let sig: string;
try {
const result = await promisify<{ result: string, error: Error }>(
this.web3.currentProvider, 'sendAsync'
)({
method: 'eth_signTypedData',
params: [params, this.channel.account],
from: this.channel.account
});
if (result.error)
throw result.error;
sig = result.result;
} catch (err) {
if (err.message && err.message.includes('User denied')) {
throw err;
}
console.log('Error on signTypedData', err);
const hash = typedSignatureHash(params);
// ask for signing of the hash
sig = await this.signMessage(hash);
}
//debug
const recovered = recoverTypedSignature({ data: params, sig });
console.log('signTypedData =', sig, recovered);
if (recovered !== this.channel.account) {
throw new Error(`Invalid recovered signature: ${recovered} != ${this.channel.account}. Do your provider support eth_signTypedData?`);
}
proof.sig = sig;
// return signed message
if (proof.balance.equals(this.channel.proof.balance)) {
this.setChannel(Object.assign(
{},
this.channel,
{ proof, next_proof: proof }
));
} else {
this.setChannel(Object.assign(
{},
this.channel,
{ next_proof: proof }
));
}
return proof;
}
/**
* Ask user for signing a payment, which is previous balance incremented of
* amount.
*
* Warnings from [[signNewProof]] applies
*
* @param amount Amount to increment in current balance
* @returns Promise to signature
*/
async incrementBalanceAndSign(amount: BigNumber): Promise<MicroProof> {
if (!this.isChannelValid()) {
throw new Error('No valid channelInfo');
}
const proof: MicroProof = { balance: this.channel.proof.balance.plus(amount) };
// get current deposit
const info = await this.getChannelInfo();
if (info.state !== 'opened') {
throw new Error('Tried signing on closed channel');
} else if (proof.balance.gt(info.deposit)) {
const err = new Error(`Insuficient funds: current = ${info.deposit} , required = ${proof.balance}`);
err['current'] = info.deposit;
err['required'] = proof.balance;
throw err;
}
// get hash for new balance proof
return await this.signNewProof(proof);
}
/**
* Persists [[MicroChannel.next_proof]] to [[MicroChannel.proof]]
*
* This method must be used after successful payment request,
* or right after [[signNewProof]] is resolved,
* if implementation don't care for request status
*/
confirmPayment(proof: MicroProof): void {
if (!this.channel.next_proof
|| !this.channel.next_proof.sig
|| this.channel.next_proof.sig !== proof.sig) {
throw new Error('Invalid provided or stored next signature');
}
const channel = Object.assign(
{},
this.channel,
{ proof: this.channel.next_proof },
);
delete channel.next_proof;
this.setChannel(channel);
}
/**
* Reset the current channel balance.
*
* Used mainly when server replies a balance out-of-sync with current state
* Caution: it sets the balance without verifying it. If possible, prefer
* [[verifyProof]]
*
* @param value Balance value to be set
*/
setBalance(value: BigNumber): void {
if (this.channel.proof.balance.eq(value)) {
return;
}
const channel = Object.assign(
{},
this.channel,
{ proof: { balance: value }, next_proof: undefined },
);
delete channel.next_proof;
this.setChannel(channel);
}
/**
* Verify and set given proof as current, if valid
*
* Used mainly when server replies with an updated balance proof.
*
* @param proof Balance proof, containing balance and signatue
* @returns True if balance is valid and correct, false otherwise
*/
verifyProof(proof: MicroProof): boolean {
if (!proof.sig) {
throw new Error('Proof must contain a signature and its respective balance');
}
const params = this.getBalanceProofSignatureParams(proof);
const recovered = recoverTypedSignature({ data: params, sig: proof.sig });
console.log('verify signTypedData =', params, proof.sig, recovered);
// recovered data from proof must be equal current account
if (recovered !== this.channel.account) {
return false;
}
const channel = Object.assign(
{},
this.channel,
{ proof, next_proof: undefined },
);
delete channel.next_proof;
this.setChannel(channel);
return true;
}
/**
* For testing. Send 0.1 ETH to mint method of contract.
* On TKN tests, it'll issue 50 TKNs to the sender's account.
*
* @param account Sender's account address
* @returns Promise to mint tx receipt
*/
async buyToken(account: string): Promise<Web3.TransactionReceipt> {
const txHash = await promisify<string>(this.token.mint, 'sendTransaction')({
from: account,
value: this.web3.toWei(0.1, 'ether')
});
console.log('mintTxHash', txHash);
return await this.waitTx(txHash, 1);
}
} | the_stack |
import { Loki } from "../../../loki/src/loki";
import { MemoryStorage } from "../../../memory-storage/src/memory_storage";
import { PartitioningAdapter } from "../../src/partitioning_adapter";
interface AB {
a: number;
b: number;
}
interface User {
name: string;
owner: string;
maker: string;
}
describe("partitioning adapter", () => {
let db2: Loki;
it("verify partioning adapter works", (done) => {
const mem = new MemoryStorage();
const adapter = new PartitioningAdapter(mem);
const db = new Loki("sandbox.db");
db.initializePersistence({adapter: adapter});
// Add a collection to the database
const items = db.addCollection<User>("items");
items.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
items.insert({name: "gungnir", owner: "odin", maker: "elves"});
items.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"});
items.insert({name: "draupnir", owner: "odin", maker: "elves"});
const another = db.addCollection<AB>("another");
const ai = another.insert({a: 1, b: 2});
db.saveDatabase().then(() => {
// should have partitioned the data
expect(Object.keys(mem.hashStore).length).toEqual(3);
expect(mem.hashStore.hasOwnProperty("sandbox.db")).toEqual(true);
expect(mem.hashStore.hasOwnProperty("sandbox.db.0")).toEqual(true);
expect(mem.hashStore.hasOwnProperty("sandbox.db.1")).toEqual(true);
// all partitions should have been saved once each
expect(mem.hashStore["sandbox.db"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(1);
// so let's go ahead and update one of our collections to make it dirty
ai.b = 3;
another.update(ai);
// and save again to ensure lastsave is different on for db container and that one collection
return db.saveDatabase();
}).then(() => {
// db container always gets saved since we currently have no 'dirty' flag on it to check
expect(mem.hashStore["sandbox.db"].savecount).toEqual(2);
// we didn't change this
expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(1);
// we updated this collection so it should have been saved again
expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(2);
// ok now lets load from it
db2 = new Loki("sandbox.db");
db2.initializePersistence({adapter: adapter});
return db2.loadDatabase();
}).then(() => {
expect(db2["_collections"].length).toEqual(2);
expect(db2["_collections"][0].count()).toEqual(4);
expect(db2["_collections"][1].count()).toEqual(1);
expect(db2.getCollection<User>("items").findOne({name: "gungnir"}).owner).toEqual("odin");
expect(db2.getCollection<AB>("another").findOne({a: 1}).b).toEqual(3);
}).then(done, done.fail);
});
it("verify partioning adapter with paging mode enabled works", (done) => {
const mem = new MemoryStorage();
// we will use an exceptionally low page size (64bytes) to test with small dataset
// every object will serialize to over 64bytes so that is not a hard limit but when
// we exceed that we will stop adding to page (so for this test 1 doc per page)
const adapter = new PartitioningAdapter(mem, {paging: true, pageSize: 64});
const db = new Loki("sandbox.db");
db.initializePersistence({adapter: adapter});
// Add a collection to the database
const items = db.addCollection<User>("items");
items.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
items.insert({name: "gungnir", owner: "odin", maker: "elves"});
const tyr = items.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"});
items.insert({name: "draupnir", owner: "odin", maker: "elves"});
const another = db.addCollection<AB>("another");
const ai = another.insert({a: 1, b: 2});
// for purposes of our memory storage it is pretty much synchronous
db.saveDatabase().then(() => {
// should have partitioned the data
expect(Object.keys(mem.hashStore).length).toEqual(6);
expect(mem.hashStore.hasOwnProperty("sandbox.db")).toEqual(true);
expect(mem.hashStore.hasOwnProperty("sandbox.db.0.0")).toEqual(true);
expect(mem.hashStore.hasOwnProperty("sandbox.db.0.1")).toEqual(true);
expect(mem.hashStore.hasOwnProperty("sandbox.db.0.2")).toEqual(true);
expect(mem.hashStore.hasOwnProperty("sandbox.db.0.3")).toEqual(true);
expect(mem.hashStore.hasOwnProperty("sandbox.db.1.0")).toEqual(true);
// all partitions should have been saved once each
expect(mem.hashStore["sandbox.db"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.0.1"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.0.2"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.0.3"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.1.0"].savecount).toEqual(1);
// so let's go ahead and update one of our collections to make it dirty
ai.b = 3;
another.update(ai);
// and save again to ensure lastsave is different on for db container and that one collection
return db.saveDatabase();
}).then(() => {
// db container always gets saved since we currently have no 'dirty' flag on it to check
expect(mem.hashStore["sandbox.db"].savecount).toEqual(2);
// we didn't change this
expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.0.2"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.0.3"].savecount).toEqual(1);
// we updated this collection so it should have been saved again
expect(mem.hashStore["sandbox.db.1.0"].savecount).toEqual(2);
// now update a multi page items collection and verify both pages were saved
tyr.maker = "elves";
items.update(tyr);
return db.saveDatabase();
}).then(() => {
expect(mem.hashStore["sandbox.db"].savecount).toEqual(3);
expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.0.1"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.0.2"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.0.3"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.1.0"].savecount).toEqual(2);
// ok now lets load from it
db2 = new Loki("sandbox.db");
db2.initializePersistence({adapter: adapter});
return db2.loadDatabase();
}).then(() => {
expect(db2["_collections"].length).toEqual(2);
expect(db2["_collections"][0].count()).toEqual(4);
expect(db2["_collections"][1].count()).toEqual(1);
expect(db2.getCollection<User>("items").findOne({name: "tyrfing"}).maker).toEqual("elves");
expect(db2.getCollection<AB>("another").findOne({a: 1}).b).toEqual(3);
// verify empty collection saves with paging
db.addCollection("extracoll");
return db.saveDatabase();
}).then(() => {
expect(mem.hashStore["sandbox.db"].savecount).toEqual(4);
expect(mem.hashStore["sandbox.db.0.0"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.0.1"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.0.2"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.0.3"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.1.0"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.2.0"].savecount).toEqual(1);
// now verify loading empty collection works with paging codepath
db2 = new Loki("sandbox.db");
db2.initializePersistence({adapter: adapter});
return db2.loadDatabase();
}).then(() => {
expect(db2["_collections"].length).toEqual(3);
expect(db2["_collections"][0].count()).toEqual(4);
expect(db2["_collections"][1].count()).toEqual(1);
expect(db2["_collections"][2].count()).toEqual(0);
}).then(done, done.fail);
});
it("verify throttled async works as expected", (done) => {
const mem = new MemoryStorage({asyncResponses: true, asyncTimeout: 50});
const adapter = new PartitioningAdapter(mem);
const throttled = true;
const db = new Loki("sandbox.db");
db.initializePersistence({adapter: adapter, throttledSaves: throttled});
// Add a collection to the database
const items = db.addCollection<User>("items");
items.insert({name: "mjolnir", owner: "thor", maker: "dwarves"});
items.insert({name: "gungnir", owner: "odin", maker: "elves"});
const tyr = items.insert({name: "tyrfing", owner: "Svafrlami", maker: "dwarves"});
items.insert({name: "draupnir", owner: "odin", maker: "elves"});
const another = db.addCollection<AB>("another");
const ai = another.insert({a: 1, b: 2});
db.saveDatabase().then(() => {
// should have partitioned the data
expect(Object.keys(mem.hashStore).length).toEqual(3);
expect(mem.hashStore.hasOwnProperty("sandbox.db")).toEqual(true);
expect(mem.hashStore.hasOwnProperty("sandbox.db.0")).toEqual(true);
expect(mem.hashStore.hasOwnProperty("sandbox.db.1")).toEqual(true);
// all partitions should have been saved once each
expect(mem.hashStore["sandbox.db"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(1);
expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(1);
// so let's go ahead and update one of our collections to make it dirty
ai.b = 3;
another.update(ai);
// and save again to ensure lastsave is different on for db container and that one collection
db.saveDatabase().then(() => {
// db container always gets saved since we currently have no 'dirty' flag on it to check
expect(mem.hashStore["sandbox.db"].savecount).toEqual(2);
// we didn't change this
expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(1);
// we updated this collection so it should have been saved again
expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(2);
// now update a multi page items collection and verify both pages were saved
tyr.maker = "elves";
items.update(tyr);
db.saveDatabase().then(() => {
expect(mem.hashStore["sandbox.db"].savecount).toEqual(3);
expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(2);
// ok now lets load from it
let db2 = new Loki("sandbox.db");
db2.initializePersistence({adapter: adapter, throttledSaves: throttled});
db2.loadDatabase().then(() => {
expect(db2["_collections"].length).toEqual(2);
expect(db2["_collections"][0].count()).toEqual(4);
expect(db2["_collections"][1].count()).toEqual(1);
expect(db2.getCollection<User>("items").findOne({name: "tyrfing"}).maker).toEqual("elves");
expect(db2.getCollection<AB>("another").findOne({a: 1}).b).toEqual(3);
// verify empty collection saves with paging
db.addCollection("extracoll");
db.saveDatabase().then(() => {
expect(mem.hashStore["sandbox.db"].savecount).toEqual(4);
expect(mem.hashStore["sandbox.db.0"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.1"].savecount).toEqual(2);
expect(mem.hashStore["sandbox.db.2"].savecount).toEqual(1);
// now verify loading empty collection works with paging codepath
db2 = new Loki("sandbox.db");
db2.initializePersistence({adapter: adapter, throttledSaves: throttled});
db2.loadDatabase().then(() => {
expect(db2["_collections"].length).toEqual(3);
expect(db2["_collections"][0].count()).toEqual(4);
expect(db2["_collections"][1].count()).toEqual(1);
expect(db2["_collections"][2].count()).toEqual(0);
// since async calls are being used, use jasmine done() to indicate test finished
done();
});
});
});
});
});
});
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.