text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { IntegrationAccountPartners } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { LogicManagementClient } from "../logicManagementClient"; import { IntegrationAccountPartner, IntegrationAccountPartnersListNextOptionalParams, IntegrationAccountPartnersListOptionalParams, IntegrationAccountPartnersListResponse, IntegrationAccountPartnersGetOptionalParams, IntegrationAccountPartnersGetResponse, IntegrationAccountPartnersCreateOrUpdateOptionalParams, IntegrationAccountPartnersCreateOrUpdateResponse, IntegrationAccountPartnersDeleteOptionalParams, GetCallbackUrlParameters, IntegrationAccountPartnersListContentCallbackUrlOptionalParams, IntegrationAccountPartnersListContentCallbackUrlResponse, IntegrationAccountPartnersListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing IntegrationAccountPartners operations. */ export class IntegrationAccountPartnersImpl implements IntegrationAccountPartners { private readonly client: LogicManagementClient; /** * Initialize a new instance of the class IntegrationAccountPartners class. * @param client Reference to the service client */ constructor(client: LogicManagementClient) { this.client = client; } /** * Gets a list of integration account partners. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param options The options parameters. */ public list( resourceGroupName: string, integrationAccountName: string, options?: IntegrationAccountPartnersListOptionalParams ): PagedAsyncIterableIterator<IntegrationAccountPartner> { const iter = this.listPagingAll( resourceGroupName, integrationAccountName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage( resourceGroupName, integrationAccountName, options ); } }; } private async *listPagingPage( resourceGroupName: string, integrationAccountName: string, options?: IntegrationAccountPartnersListOptionalParams ): AsyncIterableIterator<IntegrationAccountPartner[]> { let result = await this._list( resourceGroupName, integrationAccountName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, integrationAccountName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, integrationAccountName: string, options?: IntegrationAccountPartnersListOptionalParams ): AsyncIterableIterator<IntegrationAccountPartner> { for await (const page of this.listPagingPage( resourceGroupName, integrationAccountName, options )) { yield* page; } } /** * Gets a list of integration account partners. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param options The options parameters. */ private _list( resourceGroupName: string, integrationAccountName: string, options?: IntegrationAccountPartnersListOptionalParams ): Promise<IntegrationAccountPartnersListResponse> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, options }, listOperationSpec ); } /** * Gets an integration account partner. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param partnerName The integration account partner name. * @param options The options parameters. */ get( resourceGroupName: string, integrationAccountName: string, partnerName: string, options?: IntegrationAccountPartnersGetOptionalParams ): Promise<IntegrationAccountPartnersGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, partnerName, options }, getOperationSpec ); } /** * Creates or updates an integration account partner. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param partnerName The integration account partner name. * @param partner The integration account partner. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, integrationAccountName: string, partnerName: string, partner: IntegrationAccountPartner, options?: IntegrationAccountPartnersCreateOrUpdateOptionalParams ): Promise<IntegrationAccountPartnersCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, partnerName, partner, options }, createOrUpdateOperationSpec ); } /** * Deletes an integration account partner. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param partnerName The integration account partner name. * @param options The options parameters. */ delete( resourceGroupName: string, integrationAccountName: string, partnerName: string, options?: IntegrationAccountPartnersDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, partnerName, options }, deleteOperationSpec ); } /** * Get the content callback url. * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param partnerName The integration account partner name. * @param listContentCallbackUrl The callback url parameters. * @param options The options parameters. */ listContentCallbackUrl( resourceGroupName: string, integrationAccountName: string, partnerName: string, listContentCallbackUrl: GetCallbackUrlParameters, options?: IntegrationAccountPartnersListContentCallbackUrlOptionalParams ): Promise<IntegrationAccountPartnersListContentCallbackUrlResponse> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, partnerName, listContentCallbackUrl, options }, listContentCallbackUrlOperationSpec ); } /** * ListNext * @param resourceGroupName The resource group name. * @param integrationAccountName The integration account name. * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, integrationAccountName: string, nextLink: string, options?: IntegrationAccountPartnersListNextOptionalParams ): Promise<IntegrationAccountPartnersListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, integrationAccountName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/partners", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IntegrationAccountPartnerListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.top, Parameters.filter], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.integrationAccountName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/partners/{partnerName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IntegrationAccountPartner }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.integrationAccountName, Parameters.partnerName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/partners/{partnerName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.IntegrationAccountPartner }, 201: { bodyMapper: Mappers.IntegrationAccountPartner }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.partner, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.integrationAccountName, Parameters.partnerName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/partners/{partnerName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.integrationAccountName, Parameters.partnerName ], headerParameters: [Parameters.accept], serializer }; const listContentCallbackUrlOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/integrationAccounts/{integrationAccountName}/partners/{partnerName}/listContentCallbackUrl", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.WorkflowTriggerCallbackUrl }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.listContentCallbackUrl, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.integrationAccountName, Parameters.partnerName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IntegrationAccountPartnerListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.top, Parameters.filter], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.nextLink, Parameters.integrationAccountName ], headerParameters: [Parameters.accept], serializer };
the_stack
import htmlclean from 'htmlclean'; import { transformAbsoluteUrlToRelative, transformRelativeUrlToInternal, removeTrailingSlashFromUrl, addTrailingSlashToUrl, } from '../src/helpers'; import HtmlParser from '../src/html-parser'; import ResourcesFromCssExtractor from '../src/resources-from-css'; describe('assets extraction from css', () => { test('extract absolute url', () => { const css = '@import url(https://fonts.googleapis.com/css?family=Ubuntu:300,400,400i,500,700);'; const resources = ResourcesFromCssExtractor.extractResourcesFromCSS(css); expect(resources.length).toBe(1); expect(resources[0]).toBe('https://fonts.googleapis.com/css?family=Ubuntu:300,400,400i,500,700'); }); test('extract relative url', () => { const css = 'li.expanded{list-style-image:url(/misc/menu-expanded.png)};'; const resources = ResourcesFromCssExtractor.extractResourcesFromCSS(css); expect(resources.length).toBe(1); expect(resources[0]).toBe('/misc/menu-expanded.png'); }); }); describe('remove and replace elements in page html', () => { test('remove search block', () => { const sourceHtml = ` <header> <div id="search"></div> <h1>title from header</h1> </header> <footer> <p>paragraph from footer</p> </footer> `; const expectedHtml = ` <header> <h1>title from header</h1> </header> <footer> <p>paragraph from footer</p> </footer> `; const htmlParser = new HtmlParser(sourceHtml); htmlParser.replace('#search', ''); const processedHtml = htmlParser.getBodyHtml(); expect(htmlclean(processedHtml)).toBe(htmlclean(expectedHtml)); }); test('replace search block', () => { const sourceHtml = ` <header> <div id="search"></div> <h1>title from header</h1> </header> <footer> <p>paragraph from footer</p> </footer> `; const expectedHtml = ` <header> <div>placeholder</div> <h1>title from header</h1> </header> <footer> <p>paragraph from footer</p> </footer> `; const htmlParser = new HtmlParser(sourceHtml); htmlParser.replace('#search', '<div>placeholder</div>'); const processedHtml = htmlParser.getBodyHtml(); expect(htmlclean(processedHtml)).toBe(htmlclean(expectedHtml)); }); test('replace noscript', () => { const sourceHtml = ` <div> <noscript> <iframe src="https://www.googletagmanager.com/ns.html?id=GTM-12345"></iframe> </noscript> </div> `; const expectedHtml = ` <div> <div>placeholder</div> </div> `; const htmlParser = new HtmlParser(sourceHtml); htmlParser.replace('noscript', '<div>placeholder</div>'); const processedHtml = htmlParser.getBodyHtml(); expect(htmlclean(processedHtml)).toBe(htmlclean(expectedHtml)); }); }); describe('relative urls to internal links', () => { test('relative urls transformation on frontpage page', () => { const pageUrl = 'http://localhost/'; const urls = [ { input: 'relative/url/1', output: '/relative/url/1', }, { input: '../../relative/url/2', output: '/relative/url/2', }, ]; urls.forEach(item => { expect(transformRelativeUrlToInternal(item.input, pageUrl)).toBe(item.output); }); }); test('relative urls transformation on a 4-level page', () => { const pageUrl = 'http://localhost/relative/to/internal/test'; const urls = [ { input: 'relative/url/1', output: '/relative/to/internal/relative/url/1', }, { input: '../../relative/url/2', output: '/relative/relative/url/2', }, { input: 'relative/url/1?query=string#hash', output: '/relative/to/internal/relative/url/1?query=string#hash', }, { input: '?query=string#hash', output: '/relative/to/internal/test?query=string#hash', }, { input: '#hash', output: '#hash', }, { input: '#hash/another/path/to/test/', output: '#hash/another/path/to/test/', }, { input: '2#hash', output: '/relative/to/internal/2#hash', }, { input: '1??query=string&&query2=string2#hash2#hash3', output: '/relative/to/internal/1??query=string&&query2=string2#hash2#hash3', }, ]; urls.forEach(item => { expect(transformRelativeUrlToInternal(item.input, pageUrl)).toBe(item.output); }); }); test('html transformation of relative urls to internal links', () => { const pageUrl = 'http://localhost/relative/to/internal/test'; const sourceHtml = ` <div> <a href="relative/url/1"></a> <img src="../../relative/url/2.png" /> <video> <source src="media/gatsby.webm" /> </video> <video> <track src="media/track.webm" /> </video> <figure> <audio src="media/gatsby.mp3"></audio> </figure> <embed src="media/gatsby.mp3" /> <iframe src="gatsby.html"></iframe> <iframe src="//www.youtube.com/embed/C1XqEcsbBrw"></iframe> <object data="gatsby.pdf"></object> <picture> <source srcset="media/gastby.jpg" media="(min-width: 800px)"/> <img src="media/gastbyimg.jpg" /> </picture> </div> `; const expectedHtml = ` <div> <a href="/relative/to/internal/relative/url/1"></a> <img src="/relative/relative/url/2.png"> <video> <source src="/relative/to/internal/media/gatsby.webm"> </video> <video> <track src="/relative/to/internal/media/track.webm"> </video> <figure> <audio src="/relative/to/internal/media/gatsby.mp3"></audio> </figure> <embed src="/relative/to/internal/media/gatsby.mp3"> <iframe src="/relative/to/internal/gatsby.html"></iframe> <iframe src="//www.youtube.com/embed/C1XqEcsbBrw"></iframe> <object data="/relative/to/internal/gatsby.pdf"></object> <picture> <source srcset="/relative/to/internal/media/gastby.jpg" media="(min-width: 800px)"> <img src="/relative/to/internal/media/gastbyimg.jpg"> </picture> </div> `; const htmlParser = new HtmlParser(sourceHtml); htmlParser.transformRelativeToInternal(pageUrl); const processedHtml = htmlParser.getBodyHtml(); expect(htmlclean(processedHtml)).toBe(htmlclean(expectedHtml)); }); describe('when <base> tag present in input html', () => { test('internal url transformation made based on base tag url', () => { const pageUrl = 'http://localhost/relative/to/internal/test'; const sourceHtml = ` <html> <head> <base href='http://localhost/'> </head> <body> <a href="relative/url/1"></a> <img src="../../relative/url/2.png" /> </body> </html> `; const expectedHtml = ` <a href="/relative/url/1"></a> <img src="/relative/url/2.png"> `; const htmlParser = new HtmlParser(sourceHtml); htmlParser.transformRelativeToInternal(pageUrl); const processedHtml = htmlParser.getBodyHtml(); expect(htmlclean(processedHtml)).toBe(htmlclean(expectedHtml)); }); }); }); describe('absolute urls to relative urls', () => { test('absolute urls to relative urls', () => { const pageUrl = 'http://localhost/'; const urls = [ { input: 'http://localhost/relative/url/1', output: '/relative/url/1', }, { input: 'http://www.localhost/relative/url/1', output: '/relative/url/1', }, { input: 'https://www.localhost/relative/url/1', output: '/relative/url/1', }, { input: 'http://localhost2/relative/url/1', output: 'http://localhost2/relative/url/1', }, ]; urls.forEach(item => { expect(transformAbsoluteUrlToRelative(item.input, pageUrl)).toBe(item.output); }); }); }); describe('trailing slash', () => { test('adding trailing slash', () => { expect(addTrailingSlashToUrl('http://localhost/')).toBe('http://localhost/'); expect(addTrailingSlashToUrl('http://localhost/products')).toBe('http://localhost/products/'); expect(addTrailingSlashToUrl('http://localhost/products?type=shampoo#fragment')).toBe('http://localhost/products/?type=shampoo#fragment'); }); test('removing trailing slash', () => { expect(removeTrailingSlashFromUrl('/')).toBe('/'); expect(removeTrailingSlashFromUrl('http://localhost/')).toBe('http://localhost/'); expect(removeTrailingSlashFromUrl('http://localhost/products')).toBe('http://localhost/products'); expect(removeTrailingSlashFromUrl('http://localhost/products/')).toBe('http://localhost/products'); expect(removeTrailingSlashFromUrl('http://localhost/products/?type=shampoo#fragment')).toBe('http://localhost/products?type=shampoo#fragment'); }); test('appending trailing slash to html elements', () => { const pageUrl = 'http://localhost/products'; const sourceHtml = ` <html> <head> <link rel="alternate" hreflang="en" href="http://localhost/"> <link rel="canonical" href="http://localhost/products"> </head> <body> <a href="/products/shampoo">link to shampoo</a> <a href="/products/lotion/">link to lotion</a> <a href="http://externallink.com/products">external link</a> </body> </html> `; const expectedHtml = ` <html> <head> <link rel="alternate" hreflang="en" href="http://localhost/"> <link rel="canonical" href="http://localhost/products/"> </head> <body> <a href="/products/shampoo/">link to shampoo</a> <a href="/products/lotion/">link to lotion</a> <a href="http://externallink.com/products">external link</a> </body> </html> `; const htmlParser = new HtmlParser(sourceHtml); htmlParser.addTrailingSlash(pageUrl); const processedHtml = htmlParser.getPageHtml(); expect(htmlclean(processedHtml)).toBe(htmlclean(expectedHtml)); }); }); describe('transforming html element text to attribute', () => { test('html snippet containing style tag', () => { const input = '<body><style>h1{color:red;}</style></body>'; const expected = '<style cssText="h1{color:red;}"></style>'; const htmlParser = new HtmlParser(input); htmlParser.transformElementTextToAttribute('style', 'cssText'); const result = htmlParser.getBodyHtml(); expect(result).toBe(expected); }); test('html snippet containing inline script tag', () => { const input = '<body><script>var a=5;</script></body>'; const expected = '<script innerHTML="var a=5;"></script>'; const htmlParser = new HtmlParser(input); htmlParser.transformElementTextToAttribute('script', 'innerHTML'); const result = htmlParser.getBodyHtml(); expect(result).toBe(expected); }); test('html snippet containing script tag with src attribute', () => { const input = '<body><script src="http://localhost/test.js"></script></body>'; const expected = '<script src="http://localhost/test.js"></script>'; const htmlParser = new HtmlParser(input); htmlParser.transformElementTextToAttribute('script', 'innerHTML'); const result = htmlParser.getBodyHtml(); expect(result).toBe(expected); }); describe('when html element text is empty', () => { it('should not create an attribute with empty value', () => { const input = '<body><script></script></body>'; const expected = '<script></script>'; const htmlParser = new HtmlParser(input); htmlParser.transformElementTextToAttribute('script', 'innerHTML'); const result = htmlParser.getBodyHtml(); expect(result).toBe(expected); }); }); }); describe('getting html and body tags', () => { test('getting html tag from html', () => { const input = ` <!DOCTYPE HTML> <html lang="el-gr" dir="ltr"> <head> <meta charset="utf-8" /> </head> <body id="page" class="page isblog " data-config='{"twitter":1,"plusone":1,"facebook":1}'> <h1>hey</h1> </body> </html> `; const expected = '<html lang="el-gr" dir="ltr"></html>'; const htmlParser = new HtmlParser(input); const result = htmlParser.getHtmlTag(); expect(result).toBe(expected); }); test('getting body tag from html', () => { const input = ` <!DOCTYPE HTML> <html lang="el-gr" dir="ltr"> <head> <meta charset="utf-8" /> </head> <body id="page" class="page isblog " data-config='{"twitter":1,"plusone":1}'> <h1>hey</h1> </body> </html> `; const expected = '<body id="page" class="page isblog " data-config="{&quot;twitter&quot;:1,&quot;plusone&quot;:1}"></body>'; const htmlParser = new HtmlParser(input); const result = htmlParser.getBodyTag(); expect(result).toBe(expected); }); }); describe('cloudflare protected emails', () => { test('html elements are parsed and decoded', () => { const input = ` <a href="/cdn-cgi/l/email-protection#6506090a10011606170415001725001d040815090048160c11004b010013"> <span class="__cf_email__" data-cfemail="6506090a10011606170415001725001d040815090048160c11004b010013">[email&#160;protected]</span> </a>`; const expected = '<a href="mailto:cloudscraper@example-site.dev">cloudscraper@example-site.dev</a>'; const htmlParser = new HtmlParser(input); htmlParser.transformCfEmailToOrigin(); const result = htmlParser.getBodyHtml(); expect(htmlclean(result).trim()).toBe(htmlclean(expected).trim()); }); describe('when cf_email html element direct parent is not link', () => { test('html elements are parsed and decoded', () => { const input = ` <a href="/cdn-cgi/l/email-protection#6506090a10011606170415001725001d040815090048160c11004b010013"> <strong> <span class="__cf_email__" data-cfemail="6506090a10011606170415001725001d040815090048160c11004b010013">[email&#160;protected]</span> </strong> </a>`; const expected = '<a href="mailto:cloudscraper@example-site.dev"><strong>cloudscraper@example-site.dev</strong></a>'; const htmlParser = new HtmlParser(input); htmlParser.transformCfEmailToOrigin(); const result = htmlParser.getBodyHtml(); expect(htmlclean(result).trim()).toBe(htmlclean(expected).trim()); }); }); describe('when cf_email html element does not have a link parent', () => { test('input html is unchanged', () => { const input = ` <strong> <span class="__cf_email__" data-cfemail="123">[emailprotected]</span> </strong>`; const htmlParser = new HtmlParser(input); htmlParser.transformCfEmailToOrigin(); const result = htmlParser.getBodyHtml(); expect(htmlclean(result)).toBe(htmlclean(input)); }); }); describe('when cf_email html element parent link does not have href', () => { test('input html is unchanged', () => { const input = ` <a> <span class="__cf_email__" data-cfemail="123">[emailprotected]</span> </a>`; const htmlParser = new HtmlParser(input); htmlParser.transformCfEmailToOrigin(); const result = htmlParser.getBodyHtml(); expect(htmlclean(result)).toBe(htmlclean(input)); }); }); }); test('transforming new line in inline tags', () => { const input = ` <body> <script> var v1 = 1; //comment var v2 = 2; </script> </body> `; const expected = ` <script> var v1 = 1; //comment var v2 = 2; </script> `; const htmlParser = new HtmlParser(input); htmlParser.transformNewLineInInlineTags(); const result = htmlParser.getBodyHtml(); expect(htmlclean(result)).toBe(htmlclean(expected)); }); describe('parsing doctype in html', () => { test('doctype is preserved', () => { const input = ` <!DOCTYPE html> <html> <head></head> <body> <h1>hello</h1> </body> </html> `; const htmlParser = new HtmlParser(input); const result = htmlParser.getPageHtml(); expect(htmlclean(result)).toBe(htmlclean(input)); }); test('doctype is not added', () => { const input = ` <html> <head></head> <body> <h1>hello</h1> </body> </html> `; const htmlParser = new HtmlParser(input); const result = htmlParser.getPageHtml(); expect(htmlclean(result)).toBe(htmlclean(input)); }); test('multiple doctypes', () => { const input = ` <!DOCTYPE html> <!DOCTYPE html> <html> <head></head> <body> <h1>hello</h1> </body> </html> `; const output = ` <!DOCTYPE html> <html> <head></head> <body> <h1>hello</h1> </body> </html> `; const htmlParser = new HtmlParser(input); const result = htmlParser.getPageHtml(); expect(htmlclean(result)).toBe(htmlclean(output)); }); }); describe('html5 <base> tag', () => { describe('when present in input html', () => { it('is parsed and URL is returned', () => { const input = ` <!DOCTYPE html> <html> <head> <base href="https://www.example.com/testpage/" target="_blank"> </head> <body> <h1>hello</h1> </body> </html> `; const htmlParser = new HtmlParser(input); const baseUrl = htmlParser.getBaseUrl(); expect(baseUrl).toBe(htmlclean('https://www.example.com/testpage/')); }); describe('but does not contain href attribute', () => { it('is parsed and returns undefined', () => { const input = ` <!DOCTYPE html> <html> <head> <base target="_blank"> </head> <body> <h1>hello</h1> </body> </html> `; const htmlParser = new HtmlParser(input); const baseUrl = htmlParser.getBaseUrl(); expect(baseUrl).toBeUndefined(); }); }); }); describe('when it is not present in input html', () => { it('is parsed and returns undefined', () => { const input = ` <!DOCTYPE html> <html> <head> </head> <body> <h1>hello</h1> </body> </html> `; const htmlParser = new HtmlParser(input); const baseUrl = htmlParser.getBaseUrl(); expect(baseUrl).toBeUndefined(); }); }); }); describe('replacing strings in page source html', () => { it('should replace malformed string', () => { const sourceHtml = ` <div id="search""></div> `; const expectedHtml = ` <div id="search"></div> `; const htmlParser = new HtmlParser(sourceHtml); htmlParser.replaceString('"">', '">'); const processedHtml = htmlParser.getBodyHtml(); expect(htmlclean(processedHtml)).toBe(htmlclean(expectedHtml)); }); }); describe('remove empty attributes on selected element', () => { it('removes empty attributes', () => { const sourceHtml = ` <html> <head> <link href="" rel="test"> </head> <body> </body> </html> `; const expectedHtml = ` <html> <head> <link rel="test"> </head> <body> </body> </html> `; const htmlParser = new HtmlParser(sourceHtml); htmlParser.removeEmptyAttribute('head link', ['href']); const processedHtml = htmlParser.getPageHtml(); expect(htmlclean(processedHtml)).toBe(htmlclean(expectedHtml)); }); });
the_stack
import { v4 as uuidv4 } from 'uuid'; import { BaseContract } from './../base-contract/baseContract'; import { EffectClientConfig } from './../types/effectClientConfig'; import { Api, Serialize, Numeric } from 'eosjs'; import { GetTableRowsResult, PushTransactionArgs, ReadOnlyTransactResult } from "eosjs/dist/eosjs-rpc-interfaces"; import { MerkleTree } from 'merkletreejs'; import SHA256 from 'crypto-js/sha256'; import CryptoJS from 'crypto-js/core'; import { isBscAddress } from '../utils/bscAddress' import { convertToAsset, parseAsset } from '../utils/asset' import { getCompositeKey } from '../utils/compositeKey' import { TransactResult } from 'eosjs/dist/eosjs-api-interfaces'; import { Task } from '../types/task'; import ecc from 'eosjs-ecc'; import { Signature } from 'eosjs/dist/Signature'; import { Campaign } from '../types/campaign'; import { Batch } from '../types/batch'; import retry from 'async-retry' import { Qualification } from '../types/qualifications'; import { exit } from 'process'; const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)) /** * The Force class is responsible for interacting with the campaigns, templates, batches and tasks on the platform. * It is used for campaign creation, publishing and related campaign functions. * These are the main methods that are needed in order to interact with Effect Network. * */ export class Force extends BaseContract { constructor(api: Api, configuration: EffectClientConfig) { super(api, configuration); } /** * get pending balance * @param accountId ID of the given acccount * @returns the payment rows of the given `accountId` */ getPendingBalance = async (accountId?: number): Promise<GetTableRowsResult> => { const id = this.effectAccount ? this.effectAccount.vAccountRows[0].id : accountId const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'payment', index_position: 3, key_type: 'i64', lower_bound: id, upper_bound: id } return await this.api.rpc.get_table_rows(config) } /** * Get Force Campaigns * @param nextKey - key to start searching from * @param limit - max number of rows to return * @param processCampaign - get campaign content from ipfs * @returns - Campaign Table Rows Result */ getCampaigns = async (nextKey, limit = 20, processCampaign: boolean = true): Promise<GetTableRowsResult> => { const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'campaign', limit: limit, lower_bound: undefined } if (nextKey) { config.lower_bound = nextKey } const campaigns = await this.api.rpc.get_table_rows(config) if (processCampaign) { // Get Campaign Info. for (let i = 0; i < campaigns.rows.length; i++) { campaigns.rows[i] = await this.processCampaign(campaigns.rows[i]) } } return campaigns; } /** * Get Campaign * @param id - id of campaign * @param processCampaign - get campaign content from ipfs * @returns Campaign */ getCampaign = async (id: number, processCampaign: boolean = true): Promise<Campaign> => { const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'campaign', key_type: 'i64', lower_bound: id, upper_bound: id, } let campaign = (await this.api.rpc.get_table_rows(config)).rows[0] if (processCampaign) { campaign = await this.processCampaign(campaign) } return campaign } /** * Get Last Campaign of connected account * @param processCampaign - get campaign content from ipfs * @returns Campaign */ getMyLastCampaign = async (processCampaign: boolean = true): Promise<Campaign> => { const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'campaign', key_type: 'i64', limit: 20, reverse: true } const campaigns = await this.api.rpc.get_table_rows(config) let campaign: Campaign for (let c of campaigns.rows) { if (this.effectAccount.accountName === c.owner[1]) { campaign = c break; } } if (processCampaign) { campaign = await this.processCampaign(campaign) } return campaign } /** * processCampaign * @param campaign * @returns */ processCampaign = async (campaign: Campaign): Promise<Campaign> => { try { // field_0 represents the content type where: // 0: IPFS if (campaign.content.field_0 === 0 && campaign.content.field_1 !== '') { // field_1 represents the IPFS hash campaign.info = await this.getIpfsContent(campaign.content.field_1) } } catch (e) { campaign.info = null console.error('processCampaign', e) } return campaign } getSubmissions = async (nextKey, limit:number = 20): Promise<GetTableRowsResult> => { const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'submission', limit: limit, lower_bound: undefined } if (nextKey) { config.lower_bound = nextKey } const submissions = await this.api.rpc.get_table_rows(config) return submissions; } /** * Get submissions of batch * @param batchId * @param category , can be all, submissions or reservations * @returns */ getSubmissionsOfBatch = async (batchId: number, category = 'all'): Promise<Array<Task>> => { const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'submission', index_position: 3, key_type: 'i64', lower_bound: batchId, upper_bound: batchId, limit: this.config.batchSizeLimit } const data = await this.api.rpc.get_table_rows(config) if (data.more) { // TODO: this should not happen, limit is too high throw new Error('could not retrieve all submissions for batch') } const batchSubmissions = [] for await (const sub of data.rows) { if (batchId === parseInt(sub.batch_id)) { if (category === 'all') { batchSubmissions.push(sub) } else if (category === 'reservations' && !sub.data ) { batchSubmissions.push(sub) } else if (category === 'submissions' && sub.data) { batchSubmissions.push(sub) } } } return batchSubmissions; } /** * Does this make sense? So it might makes sense to iterate through the array in reverse order. * Get Last submission * @returns Task */ getLatestSubmissions = async (): Promise<GetTableRowsResult> => { const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'submission', key_type: 'i64', limit: 20, reverse: true } const task = await this.api.rpc.get_table_rows(config) return task } /** * Get individual task * @param leafHash - leafHash of task * @returns Task */ getTask = async (leafHash: string): Promise<Task> => { const config = { code: this.config.forceContract, scope: this.config.forceContract, limit: 1, table: 'submission', index_position: 2, key_type: 'sha256', lower_bound: leafHash, upper_bound: leafHash } const data = await this.api.rpc.get_table_rows(config) return data[0]; } /** * Get individual task result * @param leafHash - leafHash of task * @returns Task */ getTaskResult = async (leafHash: string): Promise<Task> => { const task = await this.getTask(leafHash) let result: Task | PromiseLike<Task> if (task && task.data) { result = task } return result; } /** * Poll individual task result * @param leafHash leaf hash of task * @param taskResultFound callback function * @param maxTimeout in milliseconds, default 1200000 * @param interval between retries in milliseconds, default 10000 */ pollTaskResult = async (leafHash: string, taskResultFound: Function, maxTimeout = 120000, interval = 10000): Promise<any> => { await retry(async () => { const result = await this.getTaskResult(leafHash) if (result) { return taskResultFound(result) } throw new Error(`Task ${leafHash} not found yet...`) }, { retries: Math.round(maxTimeout / interval), factor: 1, randomize: false, minTimeout: interval }) } /** * Get campaign batches * @param nextKey - key to start searching from * @param limit - max number of rows to return * @returns - Batch Table Rows Result */ getBatches = async (nextKey, limit:number = 20): Promise<GetTableRowsResult> => { const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'batch', limit: limit, lower_bound: undefined } if (nextKey) { config.lower_bound = nextKey } const batches = await this.api.rpc.get_table_rows(config) batches.rows.forEach(batch => { batch.batch_id = getCompositeKey(batch.id, batch.campaign_id) if (batch.tasks_done >= 0 && batch.num_tasks > 0 && batch.tasks_done < (batch.num_tasks * batch.repetitions)) { batch.status = 'Active' } else if (batch.tasks_done > 0 && batch.num_tasks === 0) { batch.status = 'Paused' } else if (batch.num_tasks === batch.tasks_done) { batch.status = 'Completed' } else { batch.status = 'Not Published' } }); return batches; } /** * Get Batches for Campaign * @param campaignId * @returns */ getCampaignBatches = async (campaignId: number): Promise<Array<Batch>> => { const batches = await this.getBatches('', -1) const campaignBatches = [] batches.rows.forEach(batch => { if (campaignId === parseInt(batch.campaign_id)) { campaignBatches.push(batch) } }); return campaignBatches; } /** * Upload campaign data to ipfs * @param campaignIpfs * @returns */ uploadCampaign = async (campaignIpfs: object): Promise<string> => { try { const stringify = JSON.stringify(campaignIpfs) const blob = new this.blob([stringify], { type: 'text/json' }) const formData = new this.formData() formData.append('file', await blob.text()) if (blob.size > 10000000) { throw new Error('Max file size allowed is 10 MB') } else { const requestOptions: RequestInit = { method: 'POST', body: formData } const response = await this.fetch(`${this.config.ipfsNode}/api/v0/add?pin=true`, requestOptions) const campaign = await response.json() return campaign.Hash as string } } catch (err) { console.error(`🔥🔥🔥: ${err}`) return new Error(err).message } } /** * Get the the root hash of a merkle tree given the leaf data * @param campaignId the campaign to create the merkle root for * @param batchId the batch to create the merkle root for * @param dataArray task data * @returns root of merkle tree */ getMerkleTree = (campaignId: number, batchId: number, dataArray: object[]) : any => { const sha256 = x => Buffer.from(ecc.sha256(x), 'hex') const prefixle = CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.create([campaignId, batchId], 8)) const prefixbe = CryptoJS.enc.Hex.parse(prefixle.match(/../g).reverse().join('')) const leaves = dataArray.map(x => SHA256(prefixbe.clone().concat(CryptoJS.enc.Utf8.parse(JSON.stringify(x))))) const tree = new MerkleTree(leaves, sha256) return { root: tree.getRoot().toString('hex'), tree, leaves: tree.getHexLeaves() } } /** * Creates a batch on a Campaign. * @param campaignId * @param batchId * @param content * @returns transaction result */ createBatch = async (campaignId: number, content, repetitions: number): Promise<any> => { let sig: Signature let batchId: number = 0 if ((content.tasks.length * repetitions) > this.config.batchSizeLimit) { throw new Error(`Batch size exceeds limit of ${this.config.batchSizeLimit} (including repetitions)`) } const batches = await this.getCampaignBatches(campaignId); if (batches.length) { batchId = parseInt(Math.max.apply(Math, batches.map(function(b) { return b.id; }))) + 1 } for (let i in content.tasks) { content.tasks[i].link_id = uuidv4(); } const hash = await this.uploadCampaign(content) const {root, leaves} = this.getMerkleTree(campaignId, batchId, content.tasks) const campaignOwner = this.effectAccount.accountName if (isBscAddress(campaignOwner)) { // mkbatch_params params = {8, id, campaign_id, content, task_merkle_root}; const serialbuff = new Serialize.SerialBuffer() serialbuff.push(8) serialbuff.pushUint32(batchId) serialbuff.pushUint32(campaignId) serialbuff.push(0) serialbuff.pushString(hash) serialbuff.pushUint8ArrayChecked(Serialize.hexToUint8Array(root), 32) sig = await this.generateSignature(serialbuff) } const campaign = await this.getCampaign(campaignId) const [reward, symbol] = parseAsset(campaign.reward.quantity) const batchPrice = reward * content.tasks.length * repetitions // TODO: below code copied from vaccount module, can we just call that code? let vaccSig: Signature; await this.updatevAccountRows() const amount = convertToAsset(batchPrice.toString()) const fromAccount = this.effectAccount.accountName const toAccountId = this.config.forceVaccountId const fromAccountId = this.effectAccount.vAccountRows[0].id const nonce = this.effectAccount.vAccountRows[0].nonce if (isBscAddress(fromAccount)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(1) serialbuff.pushUint32(nonce) serialbuff.pushArray(Numeric.decimalToBinary(8, fromAccountId.toString())) serialbuff.pushArray(Numeric.decimalToBinary(8, toAccountId.toString())) serialbuff.pushAsset(amount + ' ' + this.config.efxSymbol) serialbuff.pushName(this.config.efxTokenContract) vaccSig = await this.generateSignature(serialbuff) } let batchPk = getCompositeKey(batchId, campaignId) let pubSig: Signature; if (isBscAddress(fromAccount)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(17) serialbuff.pushNumberAsUint64(batchPk) pubSig = await this.generateSignature(serialbuff) } const authorization = [{ actor: isBscAddress(campaignOwner) ? this.config.eosRelayerAccount : campaignOwner, permission: isBscAddress(campaignOwner) ? this.config.eosRelayerPermission : this.effectAccount.permission }] // console.log("batch composite key", batchPk) const actions = [{ account: this.config.forceContract, name: 'mkbatch', authorization, data: { id: batchId, campaign_id: campaignId, content: { field_0: 0, field_1: hash }, task_merkle_root: root, repetitions: repetitions, qualis: null, payer: isBscAddress(campaignOwner) ? this.config.eosRelayerAccount : campaignOwner, sig: isBscAddress(campaignOwner) ? sig.toString() : null }, }, { account: this.config.accountContract, name: 'vtransfer', authorization, data: { from_id: fromAccountId, to_id: toAccountId, quantity: { quantity: amount + ' ' + this.config.efxSymbol, contract: this.config.efxTokenContract, }, sig: isBscAddress(fromAccount) ? vaccSig.toString() : null, fee: null, memo: batchPk }, }, { account: this.config.forceContract, name: 'publishbatch', authorization, data: { account_id: this.effectAccount.vAccountRows[0].id, batch_id: batchPk, num_tasks: content.tasks.length, sig: isBscAddress(fromAccount) ? pubSig.toString() : null, }, }] const transaction = await this.sendTransaction(campaignOwner, actions); return { transaction, id: batchId, leaves } } /** * deletes a batch from a force Campaign. * @param campaignId existing campaign ID * @returns transaction result */ deleteBatch = async (id: number, campaignId: number): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { let sig: Signature const owner = this.effectAccount.accountName if (isBscAddress(owner)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(12) serialbuff.pushUint32(id) serialbuff.pushUint32(campaignId) sig = await this.generateSignature(serialbuff) } const action = { account: this.config.forceContract, name: 'rmbatch', authorization: [{ actor: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, permission: isBscAddress(owner) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { id: id, campaign_id: campaignId, sig: isBscAddress(owner) ? sig.toString() : null } } return await this.sendTransaction(owner, action) } /** * pause batch which contains active tasks * @param id batch ID * @param campaignId campaign ID * @returns transaction */ pauseBatch = async (batch: Batch) => { let sig: Signature const owner = this.effectAccount.accountName let vaccount = ['name', owner] const batchPK = getCompositeKey(batch.id, batch.campaign_id) // console.log(batch) // console.log(batch.id, batch.campaign_id, batchPK) if (isBscAddress(owner)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(16) serialbuff.pushNumberAsUint64(batchPK) vaccount = ['address', owner] sig = await this.generateSignature(serialbuff) } const reservations = await this.getSubmissionsOfBatch(batchPK, 'reservations') // console.log(reservations) if (reservations.length) { const action = { account: this.config.forceContract, name: 'closebatch', authorization: [{ actor: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, permission: isBscAddress(owner) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { batch_id: batchPK, owner: vaccount, sig: isBscAddress(owner) ? sig.toString() : null } } return await this.sendTransaction(owner, action) } else { throw new Error('No active tasks found for batch.') } } resumeBatch = async (batch: Batch) => { let sig: Signature const owner = this.effectAccount.accountName const batchPK = getCompositeKey(batch.id, batch.campaign_id) if (isBscAddress(owner)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(17) serialbuff.pushNumberAsUint64(batchPK) sig = await this.generateSignature(serialbuff) } const content = await this.getIpfsContent(batch.content.field_1) if (content.tasks.length > 0) { const action = { account: this.config.forceContract, name: 'publishbatch', authorization: [{ actor: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, permission: isBscAddress(owner) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { batch_id: batchPK, num_tasks: content.tasks.length, sig: isBscAddress(owner) ? sig.toString() : null } } return await this.sendTransaction(owner, action) } else { throw new Error('No active tasks found for batch.') } } /** * creates a force Campaign. * @param hash campaign data on IPFS * @param quantity the amount of tokens rewarded * @returns transaction result */ createCampaign = async (hash: string, quantity: string, qualis?: Array<object>): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { let sig: Signature const owner = this.effectAccount.accountName if (isBscAddress(owner)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(9) serialbuff.push(0) serialbuff.pushString(hash) sig = await this.generateSignature(serialbuff) } const action = { account: this.config.forceContract, name: 'mkcampaign', authorization: [{ actor: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, permission: isBscAddress(owner) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { owner: [isBscAddress(owner) ? 'address' : 'name', owner], content: { field_0: 0, field_1: hash }, reward: { quantity: convertToAsset(quantity) + ' ' + this.config.efxSymbol, contract: this.config.efxTokenContract }, qualis: qualis ? qualis : [], payer: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, sig: isBscAddress(owner) ? sig.toString() : null } } return await this.sendTransaction(owner, action) } /** * updates a force Campaign. * @param campaignId existing campaign ID * @param hash campaign data on IPFS * @param quantity the amount of tokens rewarded * @returns transaction result */ editCampaign = async (campaignId: number, hash: string, quantity: string, qualis?: Array<object>): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { let sig: Signature const owner = this.effectAccount.accountName if (isBscAddress(owner)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(10) serialbuff.pushUint32(campaignId) serialbuff.push(0) serialbuff.pushString(hash) sig = await this.generateSignature(serialbuff) } const action = { account: this.config.forceContract, name: 'editcampaign', authorization: [{ actor: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, permission: isBscAddress(owner) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { campaign_id: campaignId, owner: [isBscAddress(owner) ? 'address' : 'name', owner], content: { field_0: 0, field_1: hash }, reward: { quantity: convertToAsset(quantity) + ' ' + this.config.efxSymbol, contract: this.config.efxTokenContract }, qualis: qualis ? qualis : [], payer: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, sig: isBscAddress(owner) ? sig.toString() : null } } return await this.sendTransaction(owner, action) } /** * deletes a force Campaign. * @param campaignId existing campaign ID * @returns transaction result */ deleteCampaign = async (campaignId: number): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { let sig: Signature const owner = this.effectAccount.accountName if (isBscAddress(owner)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(11) serialbuff.pushUint32(campaignId) sig = await this.generateSignature(serialbuff) } const action = { account: this.config.forceContract, name: 'rmcampaign', authorization: [{ actor: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, permission: isBscAddress(owner) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { campaign_id: campaignId, owner: [isBscAddress(owner) ? 'address' : 'name', owner], sig: isBscAddress(owner) ? sig.toString() : null } } return await this.sendTransaction(owner, action) } /** * Makes a campaign (uploadCampaign & createCampaign combined) * @param content * @param quantity * @returns */ makeCampaign = async (content: object, quantity: string): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { // upload to ipfs const hash = await this.uploadCampaign(content) // create campaign return await this.createCampaign(hash, quantity) } reserveFreeTask = async (batch: Batch, tasks: Array<any>, submissions: Array<Task>): Promise<any> => { let taskIndex // First go through the submissions and get all the indexes of the tasks that are done const indexes = [] const userIndexes = [] const treeLeaves = await this.getTreeLeaves(batch.campaign_id, batch.id, tasks) for await (const sub of submissions) { const index = await this.getTaskIndexFromLeaf(batch.campaign_id, batch.id, sub.leaf_hash, tasks, treeLeaves) indexes.push(index) if (sub.account_id === this.effectAccount.vAccountRows[0].id) { userIndexes.push(index) } } if (indexes.length > 0) { // create object, which holds the count of the task indexes in the submissions const indexesCount = {} for (let i = 0; i < batch.num_tasks; i++) { indexesCount[i] = 0 } for (const num of indexes) { indexesCount[num] = indexesCount[num] ? indexesCount[num] + 1 : 1 } // grab the first available index, that the user hasn't done yet const availableIndex = Object.keys(indexesCount).find(key => indexesCount[key] < batch.repetitions && !this.didWorkerDoTask(userIndexes, key)) taskIndex = availableIndex ? parseInt(availableIndex) : null } else { // no submissions yet in batch taskIndex = 0 } // if the taskIndex is empty, it means that there are no available tasks anymore if (taskIndex === null) { throw new Error('no available tasks') } // console.log("make new reservation for task index", taskIndex) return this.reserveTask(batch.id, taskIndex, batch.campaign_id, tasks) } didWorkerDoTask = (userIndexes, key): Boolean => { const item = userIndexes.find(i => parseInt(i) === parseInt(key)) return item !== null && item !== undefined } reserveOrClaimTask = async (batch: Batch, tasks: Array<any>): Promise<Task> => { const submissions = await this.getSubmissionsOfBatch(batch.batch_id) const reservations = submissions.filter(s => !s.data || !s.data.length) // get a reservation for the user // could be an active reservation of the user, or an expired/released reservation in the batch let reservation = null const accountId = this.effectAccount.vAccountRows[0].id for (const rv of reservations) { if (rv.account_id !== null && parseInt((new Date(new Date(rv.submitted_on) + 'UTC').getTime() / 1000).toString()) + parseInt(this.config.releaseTaskDelaySec.toFixed(0)) < parseInt((Date.now() / 1000).toFixed(0))) { // found expired reservation reservation = rv reservation.isExpired = true // console.log('found expired reservation') } else if (rv.account_id === null) { // found a released reservation // console.log('found released reservation') reservation = rv reservation.isReleased = true } else if (rv.account_id === accountId) { // console.log('found own reservation') // found own reservation reservation = rv break // stop searching when we find own reservation } } let tx if (reservation) { // There is a reservation available that is either from the user OR is expired/released if (reservation.isExpired) { // (re) claim expired task tx = await this.claimExpiredTask(reservation.id, reservation.account_id) } else if (reservation.isReleased) { // (re) claim released task tx = await this.reclaimTask(reservation.id) } } else { // console.log('make new reservation') // User doesn't have reservation yet, so let's make one! tx = await this.reserveFreeTask(batch, tasks, submissions) } if (tx) { await this.waitTransaction(tx); if (reservation) { // reclaiming successfull! only thing that should be changed is account_id reservation.account_id = accountId } else { // we didn't have a reservation before, so we made a new reservation. lets retrieve it const submissions = await this.getSubmissionsOfBatch(batch.batch_id) reservation = submissions.find(s => (!s.data || !s.data.length) && s.account_id === accountId) } } if (!reservation) { // Try it one more time before throwing an error await sleep(1000) const submissions = await this.getSubmissionsOfBatch(batch.batch_id) reservation = submissions.find(s => (!s.data || !s.data.length) && s.account_id === accountId) if (!reservation) { throw new Error('Could not find reservation') } } reservation.task_index = await this.getTaskIndexFromLeaf(batch.campaign_id, batch.id, reservation.leaf_hash, tasks) return reservation } /** * reserve a task in a batch * @param batchId * @param taskIndex * @param campaignId * @param tasks * @returns */ reserveTask = async (batchId: number, taskIndex: number, campaignId: number, tasks: Array<any>, sendTransaction = true): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs | Object> => { let sig: Signature const user = this.effectAccount.accountName const accountId = this.effectAccount.vAccountRows[0].id const buf2hex = x => x.toString('hex') const hex2bytes = x => Serialize.hexToUint8Array(x) const sha256 = x => Buffer.from(ecc.sha256(x), 'hex') const prefixle = CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.create([campaignId, batchId], 8)) const prefixbe = CryptoJS.enc.Hex.parse(prefixle.match(/../g).reverse().join('')) const leaves = tasks.map(x => SHA256(prefixbe.clone().concat(CryptoJS.enc.Utf8.parse(JSON.stringify(x))))) const tree = new MerkleTree(leaves, sha256) const proof = tree.getProof(leaves[taskIndex]) const hexproof = proof.map(x => buf2hex(x.data)) const pos = proof.map(x => (x.position === 'right') ? 1 : 0) if (isBscAddress(user)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(6) serialbuff.pushUint8ArrayChecked(hex2bytes(CryptoJS.enc.Hex.stringify(leaves[taskIndex])), 32) serialbuff.pushUint32(campaignId) serialbuff.pushUint32(batchId) sig = await this.generateSignature(serialbuff) } const action = { account: this.config.forceContract, name: 'reservetask', authorization: [{ actor: isBscAddress(user) ? this.config.eosRelayerAccount : user, permission: isBscAddress(user) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { proof: hexproof, position: pos, data: CryptoJS.enc.Hex.stringify(CryptoJS.enc.Utf8.parse(JSON.stringify(tasks[taskIndex]))), campaign_id: campaignId, batch_id: batchId, account_id: accountId, payer: isBscAddress(user) ? this.config.eosRelayerAccount : user, sig: isBscAddress(user) ? sig.toString() : null } } if (sendTransaction) { return await this.sendTransaction(user, action); } else { return action } } /** * release and reclaim expired task. * @param taskId */ claimExpiredTask = async (taskId: number, account_id?: number): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { let releaseSig: Signature, reclaimSig: Signature const user = this.effectAccount.accountName const accountId = this.effectAccount.vAccountRows[0].id if (isBscAddress(user)) { const releaseBuff = new Serialize.SerialBuffer() releaseBuff.push(14) releaseBuff.pushNumberAsUint64(taskId) releaseBuff.pushUint32(accountId) const reclaimBuff = new Serialize.SerialBuffer() reclaimBuff.push(15) reclaimBuff.pushNumberAsUint64(taskId) reclaimBuff.pushUint32(accountId) releaseSig = await this.generateSignature(releaseBuff) reclaimSig = await this.generateSignature(reclaimBuff) } const actions = [] // if the task is not realeased yet, release it first if (account_id) { // console.log('account id: ', account_id) actions.push({ account: this.config.forceContract, name: 'releasetask', authorization: [{ actor: isBscAddress(user) ? this.config.eosRelayerAccount : user, permission: isBscAddress(user) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { task_id: taskId, account_id: accountId, payer: isBscAddress(user) ? this.config.eosRelayerAccount : user, sig: isBscAddress(user) ? releaseSig.toString() : null } }) } actions.push({ account: this.config.forceContract, name: 'reclaimtask', authorization: [{ actor: isBscAddress(user) ? this.config.eosRelayerAccount : user, permission: isBscAddress(user) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { task_id: taskId, account_id: accountId, payer: isBscAddress(user) ? this.config.eosRelayerAccount : user, sig: isBscAddress(user) ? reclaimSig.toString() : null } }) return await this.sendTransaction(user, actions); } /** * Release a task reservation. * @param taskId * @returns */ releaseTask = async (taskId: number): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { let sig: Signature const user = this.effectAccount.accountName const accountId = this.effectAccount.vAccountRows[0].id if (isBscAddress(user)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(14) serialbuff.pushNumberAsUint64(taskId) serialbuff.pushUint32(accountId) sig = await this.generateSignature(serialbuff) } const action = [{ account: this.config.forceContract, name: 'releasetask', authorization: [{ actor: isBscAddress(user) ? this.config.eosRelayerAccount : user, permission: isBscAddress(user) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { task_id: taskId, account_id: accountId, payer: isBscAddress(user) ? this.config.eosRelayerAccount : user, sig: isBscAddress(user) ? sig.toString() : null } }] return await this.sendTransaction(user, action); } /** * Reclaim a released task reservation. * @param taskId * @returns */ reclaimTask = async (taskId: number): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { let sig: Signature const user = this.effectAccount.accountName const accountId = this.effectAccount.vAccountRows[0].id if (isBscAddress(user)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(15) serialbuff.pushNumberAsUint64(taskId) serialbuff.pushUint32(accountId) sig = await this.generateSignature(serialbuff) } const action = [{ account: this.config.forceContract, name: 'reclaimtask', authorization: [{ actor: isBscAddress(user) ? this.config.eosRelayerAccount : user, permission: isBscAddress(user) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { task_id: taskId, account_id: accountId, payer: isBscAddress(user) ? this.config.eosRelayerAccount : user, sig: isBscAddress(user) ? sig.toString() : null } }] return await this.sendTransaction(user, action); } /** * Submits a Task in a Batch * @param batchId * @param submissionId * @param data * @param accountId * @returns */ submitTask = async (batchId: number, submissionId: number, data: string): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { let sig: Signature const accountId = this.effectAccount.vAccountRows[0].id const user = this.effectAccount.accountName if (isBscAddress(user)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(5) serialbuff.pushNumberAsUint64(submissionId) serialbuff.pushString(data) sig = await this.generateSignature(serialbuff) } const action = { account: this.config.forceContract, name: 'submittask', authorization: [{ actor: isBscAddress(user) ? this.config.eosRelayerAccount : user, permission: isBscAddress(user) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { task_id: submissionId, data: data, account_id: accountId, batch_id: batchId, payer: isBscAddress(user) ? this.config.eosRelayerAccount : user, sig: isBscAddress(user) ? sig.toString() : null } } return await this.sendTransaction(user, action); } /** * Receive tokens from completed tasks. * @param paymentId * @returns */ payout = async (): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { let sig: Signature let actions = [] const accountId = this.effectAccount.vAccountRows[0].id const user = this.effectAccount.accountName const payments = await this.getPendingBalance(accountId) if (isBscAddress(user)) { const serialbuff = new Serialize.SerialBuffer() serialbuff.push(13) serialbuff.pushUint32(accountId) sig = await this.generateSignature(serialbuff) } if (payments) { for (const payment of payments.rows) { // payout is only possible after x amount of days have passed since the last_submission_time if (((new Date(new Date(payment.last_submission_time) + 'UTC').getTime() / 1000) + this.config.payoutDelaySec) < ((Date.now() / 1000))) { actions.push({ account: this.config.forceContract, name: 'payout', authorization: [{ actor: isBscAddress(user) ? this.config.eosRelayerAccount : user, permission: isBscAddress(user) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { payment_id: payment.id, sig: isBscAddress(user) ? sig.toString() : null } }) } } } else { throw new Error('No pending payouts found'); } return await this.sendTransaction(user, actions); } /** * Get task index from merkle leaf * @param leafHash * @param tasks * @returns */ getTaskIndexFromLeaf = async function (campaignId: number, batchId:number, leafHash: string, tasks: Array<Task>, leaves?: Array<String>): Promise<number> { let taskIndex: number; const treeLeaves = leaves ? leaves : await this.getTreeLeaves(campaignId, batchId, tasks) for (let i = 0; i < treeLeaves.length; i++) { if (treeLeaves[i].substring(2) === leafHash) { taskIndex = i } } return taskIndex } /** * Get the tree leaves * @param campaignId * @param batchId * @param tasks * @returns */ getTreeLeaves = async function (campaignId: number, batchId:number, tasks: Array<Task>): Promise<Array<String>> { const prefixle = CryptoJS.enc.Hex.stringify(CryptoJS.lib.WordArray.create([campaignId, batchId], 8)) const prefixbe = CryptoJS.enc.Hex.parse(prefixle.match(/../g).reverse().join('')) const sha256 = (x: string) => Buffer.from(ecc.sha256(x), 'hex') const leaves = tasks.map(x => SHA256(prefixbe.clone().concat(CryptoJS.enc.Utf8.parse(JSON.stringify(x))))) const tree = new MerkleTree(leaves, sha256) const treeLeaves = tree.getHexLeaves() return treeLeaves } /** * Create a Qualification andassign it to a campaign */ createQualification = async (name: string, description: string, type: number, image?: string, ishidden?: string): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { const qualification = { name, description, type, image, ishidden } let sig: Signature const owner = this.effectAccount.accountName const accountId = this.effectAccount.vAccountRows[0].id const hash = await this.uploadCampaign(qualification) // console.log('Upload succesful, hash: ', hash) if (isBscAddress(owner)) { // mkquali_params params = {18, account_id, content}; // (.push 18) (.pushUint32 acc-id) (.push 0) (.pushString content)))) const serialbuff = new Serialize.SerialBuffer() serialbuff.push(18) serialbuff.pushUint32(accountId) serialbuff.push(0) serialbuff.pushString(hash) sig = await this.generateSignature(serialbuff) // console.log('Signature generated', sig) } const action = { account: this.config.forceContract, name: 'mkquali', authorization: [{ actor: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, permission: isBscAddress(owner) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { content: { field_0: 0, field_1: hash }, account_id: accountId, payer: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, sig: isBscAddress(owner) ? sig.toString() : null } } return await this.sendTransaction(owner, action) } /** * Assign a qualification to a user. * @param qualificationId * @param user * @returns Transacation */ assignQualification = async (ids: Array<number> | number, accountId: number): Promise<ReadOnlyTransactResult | TransactResult | PushTransactionArgs> => { let qualificationIds = [] if (!Array.isArray(ids)) { qualificationIds.push(ids) } else { qualificationIds = [...ids] } let sig: Signature const owner = this.effectAccount.accountName const actions = [] for (let i = 0; i < qualificationIds.length; i++) { const qid = qualificationIds[i]; if (isBscAddress(owner)) { // rmbatch_params params = {19, quali_id, user_id}; // (.push 19) (.pushUint32 id) (.pushUint32 user-id)))) const serialbuff = new Serialize.SerialBuffer() serialbuff.push(19) serialbuff.pushUint32(qid) serialbuff.pushUint32(accountId) sig = await this.generateSignature(serialbuff) } actions.push({ account: this.config.forceContract, name: 'assignquali', authorization: [{ actor: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, permission: isBscAddress(owner) ? this.config.eosRelayerPermission : this.effectAccount.permission }], data: { quali_id: qid, user_id: accountId, payer: isBscAddress(owner) ? this.config.eosRelayerAccount : owner, sig: isBscAddress(owner) ? sig.toString() : null } }) } return await this.sendTransaction(owner, actions) } /** * Get Qualification * @param id - id of campaign * @param processCampaign - get campaign content from ipfs * @returns Qualification */ getQualification = async (id: number, processQualification: boolean = true): Promise<Qualification> => { const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'quali', key_type: 'i64', lower_bound: id, upper_bound: id, } let qualification = (await this.api.rpc.get_table_rows(config)).rows[0] if (processQualification) { // Get Quali Info. qualification = await this.processQualification(qualification) } return qualification } /** * Get User Qualifications * @param id - id xof the user * @returns Array<Qualification> */ getAssignedQualifications = async (userId: number): Promise<any[]> => { const userIdHex = userId.toString(16) // potential hex implementation. const hex32 = ("00000000" + userIdHex).slice(-8) const lower = hex32.padEnd(16, '0') const upper = hex32.padEnd(16, 'F') const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'userquali', lower_bound: parseInt(lower, 16), upper_bound: parseInt(upper, 16), } const qualifications = await this.api.rpc.get_table_rows(config) const userQualis = [] for (let i = 0; i < qualifications.rows.length; i++) { const quali = await this.getQualification(qualifications.rows[i].quali_id) userQualis.push(quali) } return userQualis; } /** * Get Force Qualifications * @param nextKey - key to start searching from * @param limit - max number of rows to return * @param processCampaign - get qualification content from ipfs * @returns - Qualification Table Rows Result */ getQualifications = async (nextKey, limit = 20, processQualifications: boolean = true): Promise<GetTableRowsResult> => { const config = { code: this.config.forceContract, scope: this.config.forceContract, table: 'quali', limit: limit, lower_bound: undefined } if (nextKey) { config.lower_bound = nextKey } const qualifications = await this.api.rpc.get_table_rows(config) if (processQualifications) { // Get Quali Info. for (let i = 0; i < qualifications.rows.length; i++) { qualifications.rows[i] = await this.processQualification(qualifications.rows[i]) } } return qualifications; } /** * processQualification * @param qualification * @returns Promise<Qualification> - Qualification with content */ processQualification = async (qualification: Qualification): Promise<Qualification> => { try { // field_0 represents the content type where: // 0: IPFS if (qualification.content.field_0 === 0 && qualification.content.field_1 !== '') { // field_1 represents the IPFS hash qualification.info = await this.getIpfsContent(qualification.content.field_1) } } catch (e) { qualification.info = null console.error('processCampaign', e) } return qualification } }
the_stack
import { Matrix4 } from 'three' import { Debug, Log, ParserRegistry } from '../globals' import StructureParser from './structure-parser' import { buildUnitcellAssembly, calculateBondsBetween, calculateBondsWithin } from '../structure/structure-utils' import { ChemCompHetero } from '../structure/structure-constants' import Entity from '../structure/entity' import Unitcell from '../symmetry/unitcell' import Assembly, { AssemblyPart } from '../symmetry/assembly' import { decodeMsgpack, decodeMmtf } from '../../lib/mmtf.es6' const SstrucMap: {[k: string]: number} = { '0': 'i'.charCodeAt(0), // pi helix '1': 's'.charCodeAt(0), // bend '2': 'h'.charCodeAt(0), // alpha helix '3': 'e'.charCodeAt(0), // extended '4': 'g'.charCodeAt(0), // 3-10 helix '5': 'b'.charCodeAt(0), // bridge '6': 't'.charCodeAt(0), // turn '7': 'l'.charCodeAt(0), // coil '-1': ''.charCodeAt(0) // NA } class MmtfParser extends StructureParser { get type () { return 'mmtf' } get isBinary () { return true } _parse () { // https://github.com/rcsb/mmtf if (Debug) Log.time('MmtfParser._parse ' + this.name) let i, il, j, jl, groupData const s = this.structure const sd: {[k: string]: any} = decodeMmtf(decodeMsgpack(this.streamer.data)) // structure header const headerFields = [ 'depositionDate', 'releaseDate', 'resolution', 'rFree', 'rWork', 'experimentalMethods' ] headerFields.forEach(function (name) { if (sd[ name ] !== undefined) { s.header[ name ] = sd[ name ] } }) let numBonds, numAtoms, numGroups, numChains, numModels let chainsPerModel s.id = sd.structureId s.title = sd.title s.atomStore.addField('formalCharge', 1, 'int8') if (this.firstModelOnly || this.asTrajectory) { numModels = 1 numChains = sd.chainsPerModel[ 0 ] numGroups = 0 for (i = 0, il = numChains; i < il; ++i) { numGroups += sd.groupsPerChain[ i ] } numAtoms = 0 for (i = 0, il = numGroups; i < il; ++i) { groupData = sd.groupList[ sd.groupTypeList[ i ] ] numAtoms += groupData.atomNameList.length } numBonds = sd.numBonds chainsPerModel = [ numChains ] } else { numBonds = sd.numBonds numAtoms = sd.numAtoms numGroups = sd.numGroups numChains = sd.numChains numModels = sd.numModels chainsPerModel = sd.chainsPerModel } numBonds += numGroups // add numGroups to have space for polymer bonds // if (this.asTrajectory) { for (i = 0, il = sd.numModels; i < il; ++i) { const frame = new Float32Array(numAtoms * 3) const frameAtomOffset = numAtoms * i for (j = 0; j < numAtoms; ++j) { const j3 = j * 3 const offset = j + frameAtomOffset frame[ j3 ] = sd.xCoordList[ offset ] frame[ j3 + 1 ] = sd.yCoordList[ offset ] frame[ j3 + 2 ] = sd.zCoordList[ offset ] } s.frames.push(frame) } } // bondStore const bAtomIndex1 = new Uint32Array(numBonds) const bAtomIndex2 = new Uint32Array(numBonds) const bBondOrder = new Uint8Array(numBonds) const aGroupIndex = new Uint32Array(numAtoms) const aFormalCharge = new Int8Array(numAtoms) const gChainIndex = new Uint32Array(numGroups) const gAtomOffset = new Uint32Array(numGroups) const gAtomCount = new Uint16Array(numGroups) const cModelIndex = new Uint16Array(numChains) const cGroupOffset = new Uint32Array(numChains) const cGroupCount = new Uint32Array(numChains) const mChainOffset = new Uint32Array(numModels) const mChainCount = new Uint32Array(numModels) // set-up model-chain relations let chainOffset = 0 for (i = 0, il = numModels; i < il; ++i) { const modelChainCount = chainsPerModel[ i ] mChainOffset[ i ] = chainOffset mChainCount[ i ] = modelChainCount for (j = 0; j < modelChainCount; ++j) { cModelIndex[ j + chainOffset ] = i } chainOffset += modelChainCount } // set-up chain-residue relations const groupsPerChain = sd.groupsPerChain let groupOffset = 0 for (i = 0, il = numChains; i < il; ++i) { const chainGroupCount = groupsPerChain[ i ] cGroupOffset[ i ] = groupOffset cGroupCount[ i ] = chainGroupCount for (j = 0; j < chainGroupCount; ++j) { gChainIndex[ j + groupOffset ] = i } groupOffset += chainGroupCount } /// /// // get data from group map let atomOffset = 0 let bondOffset = 0 for (i = 0, il = numGroups; i < il; ++i) { groupData = sd.groupList[ sd.groupTypeList[ i ] ] const groupAtomCount = groupData.atomNameList.length const groupFormalChargeList = groupData.formalChargeList const groupBondAtomList = groupData.bondAtomList const groupBondOrderList = groupData.bondOrderList for (j = 0, jl = groupBondOrderList.length; j < jl; ++j) { bAtomIndex1[ bondOffset ] = atomOffset + groupBondAtomList[ j * 2 ] bAtomIndex2[ bondOffset ] = atomOffset + groupBondAtomList[ j * 2 + 1 ] bBondOrder[ bondOffset ] = groupBondOrderList[ j ] bondOffset += 1 } // gAtomOffset[ i ] = atomOffset gAtomCount[ i ] = groupAtomCount for (j = 0; j < groupAtomCount; ++j) { aGroupIndex[ atomOffset ] = i aFormalCharge[ atomOffset ] = groupFormalChargeList[ j ] atomOffset += 1 } } // extra bonds const bondAtomList = sd.bondAtomList if (bondAtomList) { if (sd.bondOrderList) { bBondOrder.set(sd.bondOrderList, bondOffset) } for (i = 0, il = bondAtomList.length; i < il; i += 2) { const atomIndex1 = bondAtomList[ i ] const atomIndex2 = bondAtomList[ i + 1 ] if (atomIndex1 < numAtoms && atomIndex2 < numAtoms) { bAtomIndex1[ bondOffset ] = atomIndex1 bAtomIndex2[ bondOffset ] = atomIndex2 bondOffset += 1 } } } // s.bondStore.length = bBondOrder.length s.bondStore.count = bondOffset s.bondStore.atomIndex1 = bAtomIndex1 s.bondStore.atomIndex2 = bAtomIndex2 s.bondStore.bondOrder = bBondOrder s.atomStore.length = numAtoms s.atomStore.count = numAtoms s.atomStore.residueIndex = aGroupIndex s.atomStore.atomTypeId = new Uint16Array(numAtoms) s.atomStore.x = sd.xCoordList.subarray(0, numAtoms) s.atomStore.y = sd.yCoordList.subarray(0, numAtoms) s.atomStore.z = sd.zCoordList.subarray(0, numAtoms) s.atomStore.serial = sd.atomIdList.subarray(0, numAtoms) s.atomStore.bfactor = sd.bFactorList.subarray(0, numAtoms) s.atomStore.altloc = sd.altLocList.subarray(0, numAtoms) s.atomStore.occupancy = sd.occupancyList.subarray(0, numAtoms) s.atomStore.formalCharge = aFormalCharge s.residueStore.length = numGroups s.residueStore.count = numGroups s.residueStore.chainIndex = gChainIndex s.residueStore.residueTypeId = sd.groupTypeList s.residueStore.atomOffset = gAtomOffset s.residueStore.atomCount = gAtomCount s.residueStore.resno = sd.groupIdList.subarray(0, numGroups) s.residueStore.sstruc = sd.secStructList.subarray(0, numGroups) s.residueStore.inscode = sd.insCodeList.subarray(0, numGroups) s.chainStore.length = numChains s.chainStore.count = numChains s.chainStore.entityIndex = new Uint16Array(numChains) s.chainStore.modelIndex = cModelIndex s.chainStore.residueOffset = cGroupOffset s.chainStore.residueCount = cGroupCount s.chainStore.chainname = sd.chainNameList.subarray(0, numChains * 4) s.chainStore.chainid = sd.chainIdList.subarray(0, numChains * 4) s.modelStore.length = numModels s.modelStore.count = numModels s.modelStore.chainOffset = mChainOffset s.modelStore.chainCount = mChainCount // let groupTypeDict: {[k: number]: any} = {} for (i = 0, il = sd.groupList.length; i < il; ++i) { const groupType = sd.groupList[ i ] const atomTypeIdList: number[] = [] for (j = 0, jl = groupType.atomNameList.length; j < jl; ++j) { const element = groupType.elementList[ j ].toUpperCase() const atomname = groupType.atomNameList[ j ] atomTypeIdList.push(s.atomMap.add(atomname, element)) } const chemCompType = groupType.chemCompType.toUpperCase() const hetFlag = ChemCompHetero.includes(chemCompType) const numGroupBonds = groupType.bondOrderList.length const atomIndices1 = new Array(numGroupBonds) const atomIndices2 = new Array(numGroupBonds) for (j = 0; j < numGroupBonds; ++j) { atomIndices1[ j ] = groupType.bondAtomList[ j * 2 ] atomIndices2[ j ] = groupType.bondAtomList[ j * 2 + 1 ] } const bonds = { atomIndices1: atomIndices1, atomIndices2: atomIndices2, bondOrders: groupType.bondOrderList } groupTypeDict[ i ] = s.residueMap.add( groupType.groupName, atomTypeIdList, hetFlag, chemCompType, bonds ) } for (i = 0, il = numGroups; i < il; ++i) { s.residueStore.residueTypeId[ i ] = groupTypeDict[ s.residueStore.residueTypeId[ i ] ] } for (i = 0, il = s.atomStore.count; i < il; ++i) { const residueIndex = s.atomStore.residueIndex[ i ] const residueType = s.residueMap.list[ s.residueStore.residueTypeId[ residueIndex ] ] const resAtomOffset = s.residueStore.atomOffset[ residueIndex ] s.atomStore.atomTypeId[ i ] = residueType.atomTypeIdList[ i - resAtomOffset ] } if (sd.secStructList) { const secStructLength: number = sd.secStructList.length for (i = 0, il = s.residueStore.count; i < il; ++i) { // with ( i % secStructLength ) secStruct entries are reused const sstruc = SstrucMap[ s.residueStore.sstruc[ i % secStructLength ] ] if (sstruc !== undefined) s.residueStore.sstruc[ i ] = sstruc } } // if (sd.entityList) { sd.entityList.forEach(function (e: Entity, i: number) { s.entityList[ i ] = new Entity( s, i, e.description, e.type, e.chainIndexList ) }) } if (sd.bioAssemblyList) { sd.bioAssemblyList.forEach(function (_assembly: any, k: number) { const id = k + 1 const assembly = new Assembly('' + id) s.biomolDict[ 'BU' + id ] = assembly let chainToPart: {[k: string]: AssemblyPart} = {} _assembly.transformList.forEach(function (_transform: any) { const matrix = new Matrix4().fromArray(_transform.matrix).transpose() const chainList: string[] = _transform.chainIndexList.map(function (chainIndex: number) { let chainname = '' for (let k = 0; k < 4; ++k) { const code = sd.chainNameList[ chainIndex * 4 + k ] if (code) { chainname += String.fromCharCode(code) } else { break } } return chainname }) const part = chainToPart[ chainList.toString() ] if (part) { part.matrixList.push(matrix) } else { chainToPart[ chainList.toString() ] = assembly.addPart([ matrix ], chainList) } }) }) } if (sd.ncsOperatorList) { const ncsName = 'NCS' const ncsAssembly = new Assembly(ncsName) const ncsPart = ncsAssembly.addPart() sd.ncsOperatorList.forEach(function (_operator: number[]) { const matrix = new Matrix4().fromArray(_operator).transpose() ncsPart.matrixList.push(matrix) }) if (ncsPart.matrixList.length > 0) { s.biomolDict[ ncsName ] = ncsAssembly } } const uc = sd.unitCell if (uc && Array.isArray(uc) && uc[ 0 ]) { s.unitcell = new Unitcell({ a: uc[ 0 ], b: uc[ 1 ], c: uc[ 2 ], alpha: uc[ 3 ], beta: uc[ 4 ], gamma: uc[ 5 ], spacegroup: sd.spaceGroup }) } else { s.unitcell = undefined } // calculate backbone bonds calculateBondsBetween(s, true) // calculate rung bonds calculateBondsWithin(s, true) s.finalizeAtoms() s.finalizeBonds() buildUnitcellAssembly(s) if (Debug) Log.timeEnd('MmtfParser._parse ' + this.name) } } ParserRegistry.add('mmtf', MmtfParser) export default MmtfParser
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Provides an Elastic MapReduce Cluster, a web service that makes it easy to process large amounts of data efficiently. See [Amazon Elastic MapReduce Documentation](https://aws.amazon.com/documentation/elastic-mapreduce/) for more information. * * To configure [Instance Groups](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-group-configuration.html#emr-plan-instance-groups) for [task nodes](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-master-core-task-nodes.html#emr-plan-task), see the `aws.emr.InstanceGroup` resource. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const cluster = new aws.emr.Cluster("cluster", { * releaseLabel: "emr-4.6.0", * applications: ["Spark"], * additionalInfo: `{ * "instanceAwsClientConfiguration": { * "proxyPort": 8099, * "proxyHost": "myproxy.example.com" * } * } * `, * terminationProtection: false, * keepJobFlowAliveWhenNoSteps: true, * ec2Attributes: { * subnetId: aws_subnet.main.id, * emrManagedMasterSecurityGroup: aws_security_group.sg.id, * emrManagedSlaveSecurityGroup: aws_security_group.sg.id, * instanceProfile: aws_iam_instance_profile.emr_profile.arn, * }, * masterInstanceGroup: { * instanceType: "m4.large", * }, * coreInstanceGroup: { * instanceType: "c4.large", * instanceCount: 1, * ebsConfigs: [{ * size: "40", * type: "gp2", * volumesPerInstance: 1, * }], * bidPrice: "0.30", * autoscalingPolicy: `{ * "Constraints": { * "MinCapacity": 1, * "MaxCapacity": 2 * }, * "Rules": [ * { * "Name": "ScaleOutMemoryPercentage", * "Description": "Scale out if YARNMemoryAvailablePercentage is less than 15", * "Action": { * "SimpleScalingPolicyConfiguration": { * "AdjustmentType": "CHANGE_IN_CAPACITY", * "ScalingAdjustment": 1, * "CoolDown": 300 * } * }, * "Trigger": { * "CloudWatchAlarmDefinition": { * "ComparisonOperator": "LESS_THAN", * "EvaluationPeriods": 1, * "MetricName": "YARNMemoryAvailablePercentage", * "Namespace": "AWS/ElasticMapReduce", * "Period": 300, * "Statistic": "AVERAGE", * "Threshold": 15.0, * "Unit": "PERCENT" * } * } * } * ] * } * `, * }, * ebsRootVolumeSize: 100, * tags: { * role: "rolename", * env: "env", * }, * bootstrapActions: [{ * path: "s3://elasticmapreduce/bootstrap-actions/run-if", * name: "runif", * args: [ * "instance.isMaster=true", * "echo running on master node", * ], * }], * configurationsJson: ` [ * { * "Classification": "hadoop-env", * "Configurations": [ * { * "Classification": "export", * "Properties": { * "JAVA_HOME": "/usr/lib/jvm/java-1.8.0" * } * } * ], * "Properties": {} * }, * { * "Classification": "spark-env", * "Configurations": [ * { * "Classification": "export", * "Properties": { * "JAVA_HOME": "/usr/lib/jvm/java-1.8.0" * } * } * ], * "Properties": {} * } * ] * `, * serviceRole: aws_iam_role.iam_emr_service_role.arn, * }); * ``` * * The `aws.emr.Cluster` resource typically requires two IAM roles, one for the EMR Cluster to use as a service, and another to place on your Cluster Instances to interact with AWS from those instances. The suggested role policy template for the EMR service is `AmazonElasticMapReduceRole`, and `AmazonElasticMapReduceforEC2Role` for the EC2 profile. See the [Getting Started](https://docs.aws.amazon.com/ElasticMapReduce/latest/ManagementGuide/emr-gs-launch-sample-cluster.html) guide for more information on these IAM roles. * ### Instance Fleet * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const example = new aws.emr.Cluster("example", { * masterInstanceFleet: { * instanceTypeConfigs: [{ * instanceType: "m4.xlarge", * }], * targetOnDemandCapacity: 1, * }, * coreInstanceFleet: { * instanceTypeConfigs: [ * { * bidPriceAsPercentageOfOnDemandPrice: 80, * ebsConfigs: [{ * size: 100, * type: "gp2", * volumesPerInstance: 1, * }], * instanceType: "m3.xlarge", * weightedCapacity: 1, * }, * { * bidPriceAsPercentageOfOnDemandPrice: 100, * ebsConfigs: [{ * size: 100, * type: "gp2", * volumesPerInstance: 1, * }], * instanceType: "m4.xlarge", * weightedCapacity: 1, * }, * { * bidPriceAsPercentageOfOnDemandPrice: 100, * ebsConfigs: [{ * size: 100, * type: "gp2", * volumesPerInstance: 1, * }], * instanceType: "m4.2xlarge", * weightedCapacity: 2, * }, * ], * launchSpecifications: { * spotSpecifications: [{ * allocationStrategy: "capacity-optimized", * blockDurationMinutes: 0, * timeoutAction: "SWITCH_TO_ON_DEMAND", * timeoutDurationMinutes: 10, * }], * }, * name: "core fleet", * targetOnDemandCapacity: 2, * targetSpotCapacity: 2, * }, * }); * const task = new aws.emr.InstanceFleet("task", { * clusterId: example.id, * instanceTypeConfigs: [ * { * bidPriceAsPercentageOfOnDemandPrice: 100, * ebsConfigs: [{ * size: 100, * type: "gp2", * volumesPerInstance: 1, * }], * instanceType: "m4.xlarge", * weightedCapacity: 1, * }, * { * bidPriceAsPercentageOfOnDemandPrice: 100, * ebsConfigs: [{ * size: 100, * type: "gp2", * volumesPerInstance: 1, * }], * instanceType: "m4.2xlarge", * weightedCapacity: 2, * }, * ], * launchSpecifications: { * spotSpecifications: [{ * allocationStrategy: "capacity-optimized", * blockDurationMinutes: 0, * timeoutAction: "TERMINATE_CLUSTER", * timeoutDurationMinutes: 10, * }], * }, * targetOnDemandCapacity: 1, * targetSpotCapacity: 1, * }); * ``` * ### Enable Debug Logging * * [Debug logging in EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-debugging.html) is implemented as a step. It is highly recommended that you utilize the resource options configuration with `ignoreChanges` if other steps are being managed outside of this provider. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * // ... other configuration ... * const example = new aws.emr.Cluster("example", {steps: [{ * actionOnFailure: "TERMINATE_CLUSTER", * name: "Setup Hadoop Debugging", * hadoopJarStep: [{ * jar: "command-runner.jar", * args: ["state-pusher-script"], * }], * }]}); * ``` * ### Multiple Node Master Instance Group * * Available in EMR version 5.23.0 and later, an EMR Cluster can be launched with three master nodes for high availability. Additional information about this functionality and its requirements can be found in the [EMR Management Guide](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-ha.html). * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * // This configuration is for illustrative purposes and highlights * // only relevant configurations for working with this functionality. * // Map public IP on launch must be enabled for public (Internet accessible) subnets * // ... other configuration ... * const exampleSubnet = new aws.ec2.Subnet("exampleSubnet", {mapPublicIpOnLaunch: true}); * // ... other configuration ... * const exampleCluster = new aws.emr.Cluster("exampleCluster", { * releaseLabel: "emr-5.24.1", * terminationProtection: true, * ec2Attributes: { * subnetId: exampleSubnet.id, * }, * masterInstanceGroup: { * instanceCount: 3, * }, * coreInstanceGroup: {}, * }); * ``` * ### Bootable Cluster * * **NOTE:** This configuration demonstrates a minimal configuration needed to boot an example EMR Cluster. It is not meant to display best practices. As with all examples, use at your own risk. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const mainVpc = new aws.ec2.Vpc("mainVpc", { * cidrBlock: "168.31.0.0/16", * enableDnsHostnames: true, * tags: { * name: "emr_test", * }, * }); * const mainSubnet = new aws.ec2.Subnet("mainSubnet", { * vpcId: mainVpc.id, * cidrBlock: "168.31.0.0/20", * tags: { * name: "emr_test", * }, * }); * // IAM role for EMR Service * const iamEmrServiceRole = new aws.iam.Role("iamEmrServiceRole", {assumeRolePolicy: `{ * "Version": "2008-10-17", * "Statement": [ * { * "Sid": "", * "Effect": "Allow", * "Principal": { * "Service": "elasticmapreduce.amazonaws.com" * }, * "Action": "sts:AssumeRole" * } * ] * } * `}); * // IAM Role for EC2 Instance Profile * const iamEmrProfileRole = new aws.iam.Role("iamEmrProfileRole", {assumeRolePolicy: `{ * "Version": "2008-10-17", * "Statement": [ * { * "Sid": "", * "Effect": "Allow", * "Principal": { * "Service": "ec2.amazonaws.com" * }, * "Action": "sts:AssumeRole" * } * ] * } * `}); * const emrProfile = new aws.iam.InstanceProfile("emrProfile", {role: iamEmrProfileRole.name}); * const cluster = new aws.emr.Cluster("cluster", { * releaseLabel: "emr-4.6.0", * applications: ["Spark"], * ec2Attributes: { * subnetId: mainSubnet.id, * emrManagedMasterSecurityGroup: aws_security_group.allow_all.id, * emrManagedSlaveSecurityGroup: aws_security_group.allow_all.id, * instanceProfile: emrProfile.arn, * }, * masterInstanceGroup: { * instanceType: "m5.xlarge", * }, * coreInstanceGroup: { * instanceCount: 1, * instanceType: "m5.xlarge", * }, * tags: { * role: "rolename", * dns_zone: "env_zone", * env: "env", * name: "name-env", * }, * bootstrapActions: [{ * path: "s3://elasticmapreduce/bootstrap-actions/run-if", * name: "runif", * args: [ * "instance.isMaster=true", * "echo running on master node", * ], * }], * configurationsJson: ` [ * { * "Classification": "hadoop-env", * "Configurations": [ * { * "Classification": "export", * "Properties": { * "JAVA_HOME": "/usr/lib/jvm/java-1.8.0" * } * } * ], * "Properties": {} * }, * { * "Classification": "spark-env", * "Configurations": [ * { * "Classification": "export", * "Properties": { * "JAVA_HOME": "/usr/lib/jvm/java-1.8.0" * } * } * ], * "Properties": {} * } * ] * `, * serviceRole: iamEmrServiceRole.arn, * }); * const allowAccess = new aws.ec2.SecurityGroup("allowAccess", { * description: "Allow inbound traffic", * vpcId: mainVpc.id, * ingress: [{ * fromPort: 0, * toPort: 0, * protocol: "-1", * cidrBlocks: mainVpc.cidrBlock, * }], * egress: [{ * fromPort: 0, * toPort: 0, * protocol: "-1", * cidrBlocks: ["0.0.0.0/0"], * }], * tags: { * name: "emr_test", * }, * }, { * dependsOn: [mainSubnet], * }); * const gw = new aws.ec2.InternetGateway("gw", {vpcId: mainVpc.id}); * const routeTable = new aws.ec2.RouteTable("routeTable", { * vpcId: mainVpc.id, * routes: [{ * cidrBlock: "0.0.0.0/0", * gatewayId: gw.id, * }], * }); * const mainRouteTableAssociation = new aws.ec2.MainRouteTableAssociation("mainRouteTableAssociation", { * vpcId: mainVpc.id, * routeTableId: routeTable.id, * }); * //## * const iamEmrServicePolicy = new aws.iam.RolePolicy("iamEmrServicePolicy", { * role: iamEmrServiceRole.id, * policy: `{ * "Version": "2012-10-17", * "Statement": [{ * "Effect": "Allow", * "Resource": "*", * "Action": [ * "ec2:AuthorizeSecurityGroupEgress", * "ec2:AuthorizeSecurityGroupIngress", * "ec2:CancelSpotInstanceRequests", * "ec2:CreateNetworkInterface", * "ec2:CreateSecurityGroup", * "ec2:CreateTags", * "ec2:DeleteNetworkInterface", * "ec2:DeleteSecurityGroup", * "ec2:DeleteTags", * "ec2:DescribeAvailabilityZones", * "ec2:DescribeAccountAttributes", * "ec2:DescribeDhcpOptions", * "ec2:DescribeInstanceStatus", * "ec2:DescribeInstances", * "ec2:DescribeKeyPairs", * "ec2:DescribeNetworkAcls", * "ec2:DescribeNetworkInterfaces", * "ec2:DescribePrefixLists", * "ec2:DescribeRouteTables", * "ec2:DescribeSecurityGroups", * "ec2:DescribeSpotInstanceRequests", * "ec2:DescribeSpotPriceHistory", * "ec2:DescribeSubnets", * "ec2:DescribeVpcAttribute", * "ec2:DescribeVpcEndpoints", * "ec2:DescribeVpcEndpointServices", * "ec2:DescribeVpcs", * "ec2:DetachNetworkInterface", * "ec2:ModifyImageAttribute", * "ec2:ModifyInstanceAttribute", * "ec2:RequestSpotInstances", * "ec2:RevokeSecurityGroupEgress", * "ec2:RunInstances", * "ec2:TerminateInstances", * "ec2:DeleteVolume", * "ec2:DescribeVolumeStatus", * "ec2:DescribeVolumes", * "ec2:DetachVolume", * "iam:GetRole", * "iam:GetRolePolicy", * "iam:ListInstanceProfiles", * "iam:ListRolePolicies", * "iam:PassRole", * "s3:CreateBucket", * "s3:Get*", * "s3:List*", * "sdb:BatchPutAttributes", * "sdb:Select", * "sqs:CreateQueue", * "sqs:Delete*", * "sqs:GetQueue*", * "sqs:PurgeQueue", * "sqs:ReceiveMessage" * ] * }] * } * `, * }); * const iamEmrProfilePolicy = new aws.iam.RolePolicy("iamEmrProfilePolicy", { * role: iamEmrProfileRole.id, * policy: `{ * "Version": "2012-10-17", * "Statement": [{ * "Effect": "Allow", * "Resource": "*", * "Action": [ * "cloudwatch:*", * "dynamodb:*", * "ec2:Describe*", * "elasticmapreduce:Describe*", * "elasticmapreduce:ListBootstrapActions", * "elasticmapreduce:ListClusters", * "elasticmapreduce:ListInstanceGroups", * "elasticmapreduce:ListInstances", * "elasticmapreduce:ListSteps", * "kinesis:CreateStream", * "kinesis:DeleteStream", * "kinesis:DescribeStream", * "kinesis:GetRecords", * "kinesis:GetShardIterator", * "kinesis:MergeShards", * "kinesis:PutRecord", * "kinesis:SplitShard", * "rds:Describe*", * "s3:*", * "sdb:*", * "sns:*", * "sqs:*" * ] * }] * } * `, * }); * ``` * * ## Import * * EMR clusters can be imported using the `id`, e.g. * * ```sh * $ pulumi import aws:emr/cluster:Cluster cluster j-123456ABCDEF * ``` * * Since the API does not return the actual values for Kerberos configurations, environments with those configurations will need to use the resource options configuration block `ignoreChanges` argument available to all provider resources to prevent perpetual differences, e.g. terraform resource "aws_emr_cluster" "example" { * * # ... other configuration ... * * lifecycle { * * ignore_changes = [kerberos_attributes] * * } } */ export class Cluster extends pulumi.CustomResource { /** * Get an existing Cluster resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ClusterState, opts?: pulumi.CustomResourceOptions): Cluster { return new Cluster(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:emr/cluster:Cluster'; /** * Returns true if the given object is an instance of Cluster. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is Cluster { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Cluster.__pulumiType; } /** * JSON string for selecting additional features such as adding proxy information. Note: Currently there is no API to retrieve the value of this argument after EMR cluster creation from provider, therefore this provider cannot detect drift from the actual EMR cluster if its value is changed outside this provider. */ public readonly additionalInfo!: pulumi.Output<string | undefined>; /** * List of applications for the cluster. Valid values are: `Flink`, `Hadoop`, `Hive`, `Mahout`, `Pig`, `Spark`, and `JupyterHub` (as of EMR 5.14.0). Case insensitive. */ public readonly applications!: pulumi.Output<string[] | undefined>; public /*out*/ readonly arn!: pulumi.Output<string>; /** * IAM role for automatic scaling policies. The IAM role provides permissions that the automatic scaling feature requires to launch and terminate EC2 instances in an instance group. */ public readonly autoscalingRole!: pulumi.Output<string | undefined>; /** * Ordered list of bootstrap actions that will be run before Hadoop is started on the cluster nodes. See below. */ public readonly bootstrapActions!: pulumi.Output<outputs.emr.ClusterBootstrapAction[] | undefined>; public /*out*/ readonly clusterState!: pulumi.Output<string>; /** * Configuration classification that applies when provisioning cluster instances, which can include configurations for applications and software that run on the cluster. List of `configuration` blocks. */ public readonly configurations!: pulumi.Output<string | undefined>; /** * JSON string for supplying list of configurations for the EMR cluster. */ public readonly configurationsJson!: pulumi.Output<string | undefined>; /** * Configuration block to use an [Instance Fleet](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-fleet.html) for the core node type. Cannot be specified if any `coreInstanceGroup` configuration blocks are set. Detailed below. */ public readonly coreInstanceFleet!: pulumi.Output<outputs.emr.ClusterCoreInstanceFleet>; /** * Configuration block to use an [Instance Group](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-group-configuration.html#emr-plan-instance-groups) for the [core node type](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-master-core-task-nodes.html#emr-plan-core). */ public readonly coreInstanceGroup!: pulumi.Output<outputs.emr.ClusterCoreInstanceGroup>; /** * Custom Amazon Linux AMI for the cluster (instead of an EMR-owned AMI). Available in Amazon EMR version 5.7.0 and later. */ public readonly customAmiId!: pulumi.Output<string | undefined>; /** * Size in GiB of the EBS root device volume of the Linux AMI that is used for each EC2 instance. Available in Amazon EMR version 4.x and later. */ public readonly ebsRootVolumeSize!: pulumi.Output<number | undefined>; /** * Attributes for the EC2 instances running the job flow. See below. */ public readonly ec2Attributes!: pulumi.Output<outputs.emr.ClusterEc2Attributes | undefined>; /** * Switch on/off run cluster with no steps or when all steps are complete (default is on) */ public readonly keepJobFlowAliveWhenNoSteps!: pulumi.Output<boolean>; /** * Kerberos configuration for the cluster. See below. */ public readonly kerberosAttributes!: pulumi.Output<outputs.emr.ClusterKerberosAttributes | undefined>; /** * AWS KMS customer master key (CMK) key ID or arn used for encrypting log files. This attribute is only available with EMR version 5.30.0 and later, excluding EMR 6.0.0. */ public readonly logEncryptionKmsKeyId!: pulumi.Output<string | undefined>; /** * S3 bucket to write the log files of the job flow. If a value is not provided, logs are not created. */ public readonly logUri!: pulumi.Output<string | undefined>; /** * Configuration block to use an [Instance Fleet](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-fleet.html) for the master node type. Cannot be specified if any `masterInstanceGroup` configuration blocks are set. Detailed below. */ public readonly masterInstanceFleet!: pulumi.Output<outputs.emr.ClusterMasterInstanceFleet>; /** * Configuration block to use an [Instance Group](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-group-configuration.html#emr-plan-instance-groups) for the [master node type](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-master-core-task-nodes.html#emr-plan-master). */ public readonly masterInstanceGroup!: pulumi.Output<outputs.emr.ClusterMasterInstanceGroup>; /** * Public DNS name of the master EC2 instance. */ public /*out*/ readonly masterPublicDns!: pulumi.Output<string>; /** * Name of the step. */ public readonly name!: pulumi.Output<string>; /** * Release label for the Amazon EMR release. */ public readonly releaseLabel!: pulumi.Output<string>; /** * Way that individual Amazon EC2 instances terminate when an automatic scale-in activity occurs or an `instance group` is resized. */ public readonly scaleDownBehavior!: pulumi.Output<string>; /** * Security configuration name to attach to the EMR cluster. Only valid for EMR clusters with `releaseLabel` 4.8.0 or greater. */ public readonly securityConfiguration!: pulumi.Output<string | undefined>; /** * IAM role that will be assumed by the Amazon EMR service to access AWS resources. */ public readonly serviceRole!: pulumi.Output<string>; /** * Number of steps that can be executed concurrently. You can specify a maximum of 256 steps. Only valid for EMR clusters with `releaseLabel` 5.28.0 or greater (default is 1). */ public readonly stepConcurrencyLevel!: pulumi.Output<number | undefined>; /** * List of steps to run when creating the cluster. See below. It is highly recommended to utilize the lifecycle resource options block with `ignoreChanges` if other steps are being managed outside of this provider. */ public readonly steps!: pulumi.Output<outputs.emr.ClusterStep[]>; /** * list of tags to apply to the EMR Cluster. If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * Map of tags assigned to the resource, including those inherited from the provider `defaultTags` configuration block. */ public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Switch on/off termination protection (default is `false`, except when using multiple master nodes). Before attempting to destroy the resource when termination protection is enabled, this configuration must be applied with its value set to `false`. */ public readonly terminationProtection!: pulumi.Output<boolean>; /** * Whether the job flow is visible to all IAM users of the AWS account associated with the job flow. Default value is `true`. */ public readonly visibleToAllUsers!: pulumi.Output<boolean | undefined>; /** * Create a Cluster resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ClusterArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ClusterArgs | ClusterState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ClusterState | undefined; inputs["additionalInfo"] = state ? state.additionalInfo : undefined; inputs["applications"] = state ? state.applications : undefined; inputs["arn"] = state ? state.arn : undefined; inputs["autoscalingRole"] = state ? state.autoscalingRole : undefined; inputs["bootstrapActions"] = state ? state.bootstrapActions : undefined; inputs["clusterState"] = state ? state.clusterState : undefined; inputs["configurations"] = state ? state.configurations : undefined; inputs["configurationsJson"] = state ? state.configurationsJson : undefined; inputs["coreInstanceFleet"] = state ? state.coreInstanceFleet : undefined; inputs["coreInstanceGroup"] = state ? state.coreInstanceGroup : undefined; inputs["customAmiId"] = state ? state.customAmiId : undefined; inputs["ebsRootVolumeSize"] = state ? state.ebsRootVolumeSize : undefined; inputs["ec2Attributes"] = state ? state.ec2Attributes : undefined; inputs["keepJobFlowAliveWhenNoSteps"] = state ? state.keepJobFlowAliveWhenNoSteps : undefined; inputs["kerberosAttributes"] = state ? state.kerberosAttributes : undefined; inputs["logEncryptionKmsKeyId"] = state ? state.logEncryptionKmsKeyId : undefined; inputs["logUri"] = state ? state.logUri : undefined; inputs["masterInstanceFleet"] = state ? state.masterInstanceFleet : undefined; inputs["masterInstanceGroup"] = state ? state.masterInstanceGroup : undefined; inputs["masterPublicDns"] = state ? state.masterPublicDns : undefined; inputs["name"] = state ? state.name : undefined; inputs["releaseLabel"] = state ? state.releaseLabel : undefined; inputs["scaleDownBehavior"] = state ? state.scaleDownBehavior : undefined; inputs["securityConfiguration"] = state ? state.securityConfiguration : undefined; inputs["serviceRole"] = state ? state.serviceRole : undefined; inputs["stepConcurrencyLevel"] = state ? state.stepConcurrencyLevel : undefined; inputs["steps"] = state ? state.steps : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["terminationProtection"] = state ? state.terminationProtection : undefined; inputs["visibleToAllUsers"] = state ? state.visibleToAllUsers : undefined; } else { const args = argsOrState as ClusterArgs | undefined; if ((!args || args.releaseLabel === undefined) && !opts.urn) { throw new Error("Missing required property 'releaseLabel'"); } if ((!args || args.serviceRole === undefined) && !opts.urn) { throw new Error("Missing required property 'serviceRole'"); } inputs["additionalInfo"] = args ? args.additionalInfo : undefined; inputs["applications"] = args ? args.applications : undefined; inputs["autoscalingRole"] = args ? args.autoscalingRole : undefined; inputs["bootstrapActions"] = args ? args.bootstrapActions : undefined; inputs["configurations"] = args ? args.configurations : undefined; inputs["configurationsJson"] = args ? args.configurationsJson : undefined; inputs["coreInstanceFleet"] = args ? args.coreInstanceFleet : undefined; inputs["coreInstanceGroup"] = args ? args.coreInstanceGroup : undefined; inputs["customAmiId"] = args ? args.customAmiId : undefined; inputs["ebsRootVolumeSize"] = args ? args.ebsRootVolumeSize : undefined; inputs["ec2Attributes"] = args ? args.ec2Attributes : undefined; inputs["keepJobFlowAliveWhenNoSteps"] = args ? args.keepJobFlowAliveWhenNoSteps : undefined; inputs["kerberosAttributes"] = args ? args.kerberosAttributes : undefined; inputs["logEncryptionKmsKeyId"] = args ? args.logEncryptionKmsKeyId : undefined; inputs["logUri"] = args ? args.logUri : undefined; inputs["masterInstanceFleet"] = args ? args.masterInstanceFleet : undefined; inputs["masterInstanceGroup"] = args ? args.masterInstanceGroup : undefined; inputs["name"] = args ? args.name : undefined; inputs["releaseLabel"] = args ? args.releaseLabel : undefined; inputs["scaleDownBehavior"] = args ? args.scaleDownBehavior : undefined; inputs["securityConfiguration"] = args ? args.securityConfiguration : undefined; inputs["serviceRole"] = args ? args.serviceRole : undefined; inputs["stepConcurrencyLevel"] = args ? args.stepConcurrencyLevel : undefined; inputs["steps"] = args ? args.steps : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["terminationProtection"] = args ? args.terminationProtection : undefined; inputs["visibleToAllUsers"] = args ? args.visibleToAllUsers : undefined; inputs["arn"] = undefined /*out*/; inputs["clusterState"] = undefined /*out*/; inputs["masterPublicDns"] = undefined /*out*/; inputs["tagsAll"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Cluster.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Cluster resources. */ export interface ClusterState { /** * JSON string for selecting additional features such as adding proxy information. Note: Currently there is no API to retrieve the value of this argument after EMR cluster creation from provider, therefore this provider cannot detect drift from the actual EMR cluster if its value is changed outside this provider. */ additionalInfo?: pulumi.Input<string>; /** * List of applications for the cluster. Valid values are: `Flink`, `Hadoop`, `Hive`, `Mahout`, `Pig`, `Spark`, and `JupyterHub` (as of EMR 5.14.0). Case insensitive. */ applications?: pulumi.Input<pulumi.Input<string>[]>; arn?: pulumi.Input<string>; /** * IAM role for automatic scaling policies. The IAM role provides permissions that the automatic scaling feature requires to launch and terminate EC2 instances in an instance group. */ autoscalingRole?: pulumi.Input<string>; /** * Ordered list of bootstrap actions that will be run before Hadoop is started on the cluster nodes. See below. */ bootstrapActions?: pulumi.Input<pulumi.Input<inputs.emr.ClusterBootstrapAction>[]>; clusterState?: pulumi.Input<string>; /** * Configuration classification that applies when provisioning cluster instances, which can include configurations for applications and software that run on the cluster. List of `configuration` blocks. */ configurations?: pulumi.Input<string>; /** * JSON string for supplying list of configurations for the EMR cluster. */ configurationsJson?: pulumi.Input<string>; /** * Configuration block to use an [Instance Fleet](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-fleet.html) for the core node type. Cannot be specified if any `coreInstanceGroup` configuration blocks are set. Detailed below. */ coreInstanceFleet?: pulumi.Input<inputs.emr.ClusterCoreInstanceFleet>; /** * Configuration block to use an [Instance Group](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-group-configuration.html#emr-plan-instance-groups) for the [core node type](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-master-core-task-nodes.html#emr-plan-core). */ coreInstanceGroup?: pulumi.Input<inputs.emr.ClusterCoreInstanceGroup>; /** * Custom Amazon Linux AMI for the cluster (instead of an EMR-owned AMI). Available in Amazon EMR version 5.7.0 and later. */ customAmiId?: pulumi.Input<string>; /** * Size in GiB of the EBS root device volume of the Linux AMI that is used for each EC2 instance. Available in Amazon EMR version 4.x and later. */ ebsRootVolumeSize?: pulumi.Input<number>; /** * Attributes for the EC2 instances running the job flow. See below. */ ec2Attributes?: pulumi.Input<inputs.emr.ClusterEc2Attributes>; /** * Switch on/off run cluster with no steps or when all steps are complete (default is on) */ keepJobFlowAliveWhenNoSteps?: pulumi.Input<boolean>; /** * Kerberos configuration for the cluster. See below. */ kerberosAttributes?: pulumi.Input<inputs.emr.ClusterKerberosAttributes>; /** * AWS KMS customer master key (CMK) key ID or arn used for encrypting log files. This attribute is only available with EMR version 5.30.0 and later, excluding EMR 6.0.0. */ logEncryptionKmsKeyId?: pulumi.Input<string>; /** * S3 bucket to write the log files of the job flow. If a value is not provided, logs are not created. */ logUri?: pulumi.Input<string>; /** * Configuration block to use an [Instance Fleet](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-fleet.html) for the master node type. Cannot be specified if any `masterInstanceGroup` configuration blocks are set. Detailed below. */ masterInstanceFleet?: pulumi.Input<inputs.emr.ClusterMasterInstanceFleet>; /** * Configuration block to use an [Instance Group](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-group-configuration.html#emr-plan-instance-groups) for the [master node type](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-master-core-task-nodes.html#emr-plan-master). */ masterInstanceGroup?: pulumi.Input<inputs.emr.ClusterMasterInstanceGroup>; /** * Public DNS name of the master EC2 instance. */ masterPublicDns?: pulumi.Input<string>; /** * Name of the step. */ name?: pulumi.Input<string>; /** * Release label for the Amazon EMR release. */ releaseLabel?: pulumi.Input<string>; /** * Way that individual Amazon EC2 instances terminate when an automatic scale-in activity occurs or an `instance group` is resized. */ scaleDownBehavior?: pulumi.Input<string>; /** * Security configuration name to attach to the EMR cluster. Only valid for EMR clusters with `releaseLabel` 4.8.0 or greater. */ securityConfiguration?: pulumi.Input<string>; /** * IAM role that will be assumed by the Amazon EMR service to access AWS resources. */ serviceRole?: pulumi.Input<string>; /** * Number of steps that can be executed concurrently. You can specify a maximum of 256 steps. Only valid for EMR clusters with `releaseLabel` 5.28.0 or greater (default is 1). */ stepConcurrencyLevel?: pulumi.Input<number>; /** * List of steps to run when creating the cluster. See below. It is highly recommended to utilize the lifecycle resource options block with `ignoreChanges` if other steps are being managed outside of this provider. */ steps?: pulumi.Input<pulumi.Input<inputs.emr.ClusterStep>[]>; /** * list of tags to apply to the EMR Cluster. If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Map of tags assigned to the resource, including those inherited from the provider `defaultTags` configuration block. */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Switch on/off termination protection (default is `false`, except when using multiple master nodes). Before attempting to destroy the resource when termination protection is enabled, this configuration must be applied with its value set to `false`. */ terminationProtection?: pulumi.Input<boolean>; /** * Whether the job flow is visible to all IAM users of the AWS account associated with the job flow. Default value is `true`. */ visibleToAllUsers?: pulumi.Input<boolean>; } /** * The set of arguments for constructing a Cluster resource. */ export interface ClusterArgs { /** * JSON string for selecting additional features such as adding proxy information. Note: Currently there is no API to retrieve the value of this argument after EMR cluster creation from provider, therefore this provider cannot detect drift from the actual EMR cluster if its value is changed outside this provider. */ additionalInfo?: pulumi.Input<string>; /** * List of applications for the cluster. Valid values are: `Flink`, `Hadoop`, `Hive`, `Mahout`, `Pig`, `Spark`, and `JupyterHub` (as of EMR 5.14.0). Case insensitive. */ applications?: pulumi.Input<pulumi.Input<string>[]>; /** * IAM role for automatic scaling policies. The IAM role provides permissions that the automatic scaling feature requires to launch and terminate EC2 instances in an instance group. */ autoscalingRole?: pulumi.Input<string>; /** * Ordered list of bootstrap actions that will be run before Hadoop is started on the cluster nodes. See below. */ bootstrapActions?: pulumi.Input<pulumi.Input<inputs.emr.ClusterBootstrapAction>[]>; /** * Configuration classification that applies when provisioning cluster instances, which can include configurations for applications and software that run on the cluster. List of `configuration` blocks. */ configurations?: pulumi.Input<string>; /** * JSON string for supplying list of configurations for the EMR cluster. */ configurationsJson?: pulumi.Input<string>; /** * Configuration block to use an [Instance Fleet](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-fleet.html) for the core node type. Cannot be specified if any `coreInstanceGroup` configuration blocks are set. Detailed below. */ coreInstanceFleet?: pulumi.Input<inputs.emr.ClusterCoreInstanceFleet>; /** * Configuration block to use an [Instance Group](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-group-configuration.html#emr-plan-instance-groups) for the [core node type](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-master-core-task-nodes.html#emr-plan-core). */ coreInstanceGroup?: pulumi.Input<inputs.emr.ClusterCoreInstanceGroup>; /** * Custom Amazon Linux AMI for the cluster (instead of an EMR-owned AMI). Available in Amazon EMR version 5.7.0 and later. */ customAmiId?: pulumi.Input<string>; /** * Size in GiB of the EBS root device volume of the Linux AMI that is used for each EC2 instance. Available in Amazon EMR version 4.x and later. */ ebsRootVolumeSize?: pulumi.Input<number>; /** * Attributes for the EC2 instances running the job flow. See below. */ ec2Attributes?: pulumi.Input<inputs.emr.ClusterEc2Attributes>; /** * Switch on/off run cluster with no steps or when all steps are complete (default is on) */ keepJobFlowAliveWhenNoSteps?: pulumi.Input<boolean>; /** * Kerberos configuration for the cluster. See below. */ kerberosAttributes?: pulumi.Input<inputs.emr.ClusterKerberosAttributes>; /** * AWS KMS customer master key (CMK) key ID or arn used for encrypting log files. This attribute is only available with EMR version 5.30.0 and later, excluding EMR 6.0.0. */ logEncryptionKmsKeyId?: pulumi.Input<string>; /** * S3 bucket to write the log files of the job flow. If a value is not provided, logs are not created. */ logUri?: pulumi.Input<string>; /** * Configuration block to use an [Instance Fleet](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-fleet.html) for the master node type. Cannot be specified if any `masterInstanceGroup` configuration blocks are set. Detailed below. */ masterInstanceFleet?: pulumi.Input<inputs.emr.ClusterMasterInstanceFleet>; /** * Configuration block to use an [Instance Group](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-instance-group-configuration.html#emr-plan-instance-groups) for the [master node type](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-master-core-task-nodes.html#emr-plan-master). */ masterInstanceGroup?: pulumi.Input<inputs.emr.ClusterMasterInstanceGroup>; /** * Name of the step. */ name?: pulumi.Input<string>; /** * Release label for the Amazon EMR release. */ releaseLabel: pulumi.Input<string>; /** * Way that individual Amazon EC2 instances terminate when an automatic scale-in activity occurs or an `instance group` is resized. */ scaleDownBehavior?: pulumi.Input<string>; /** * Security configuration name to attach to the EMR cluster. Only valid for EMR clusters with `releaseLabel` 4.8.0 or greater. */ securityConfiguration?: pulumi.Input<string>; /** * IAM role that will be assumed by the Amazon EMR service to access AWS resources. */ serviceRole: pulumi.Input<string>; /** * Number of steps that can be executed concurrently. You can specify a maximum of 256 steps. Only valid for EMR clusters with `releaseLabel` 5.28.0 or greater (default is 1). */ stepConcurrencyLevel?: pulumi.Input<number>; /** * List of steps to run when creating the cluster. See below. It is highly recommended to utilize the lifecycle resource options block with `ignoreChanges` if other steps are being managed outside of this provider. */ steps?: pulumi.Input<pulumi.Input<inputs.emr.ClusterStep>[]>; /** * list of tags to apply to the EMR Cluster. If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Switch on/off termination protection (default is `false`, except when using multiple master nodes). Before attempting to destroy the resource when termination protection is enabled, this configuration must be applied with its value set to `false`. */ terminationProtection?: pulumi.Input<boolean>; /** * Whether the job flow is visible to all IAM users of the AWS account associated with the job flow. Default value is `true`. */ visibleToAllUsers?: pulumi.Input<boolean>; }
the_stack
import {Oas20Document} from "../src/models/2.0/document.model"; import {OasLibraryUtils} from "../src/library.utils"; import {OasNodePath, OasNodePathSegment} from "../src/models/node-path"; import {OasNode, OasValidationProblem} from "../src/models/node.model"; import {Oas30Document} from "../src/models/3.0/document.model"; import {Oas30Operation} from "../src/models/3.0/operation.model"; import {Oas30Header} from "../src/models/3.0/header.model"; describe("Node Path Parser", () => { it("Info", () => { let path: OasNodePath = new OasNodePath("/info"); let segments: OasNodePathSegment[] = path["_segments"]; expect(segments.length).toEqual(1); expect(segments[0].value()).toEqual("info"); }); it("Just Path Segments", () => { let path: OasNodePath = new OasNodePath("/foo/bar/baz"); let segments: OasNodePathSegment[] = path["_segments"]; expect(segments.length).toEqual(3); expect(segments[0].value()).toEqual("foo"); expect(segments[1].value()).toEqual("bar"); expect(segments[2].value()).toEqual("baz"); }); it("Path and Index Segments", () => { let path: OasNodePath = new OasNodePath("/foo/bar[10]/baz[/zippy]/crash"); let segments: OasNodePathSegment[] = path["_segments"]; expect(segments.length).toEqual(6); expect(segments[0].value()).toEqual("foo"); expect(segments[1].value()).toEqual("bar"); expect(segments[2].value()).toEqual('10'); expect(segments[3].value()).toEqual("baz"); expect(segments[4].value()).toEqual("/zippy"); expect(segments[5].value()).toEqual("crash"); }); it("Multiple Index Segments", () => { let path: OasNodePath = new OasNodePath("/foo/bar[10][baz]/res1[10][3][6]"); let segments: OasNodePathSegment[] = path["_segments"]; expect(segments.length).toEqual(8); expect(segments[0].value()).toEqual("foo"); expect(segments[1].value()).toEqual("bar"); expect(segments[2].value()).toEqual('10'); expect(segments[3].value()).toEqual("baz"); expect(segments[4].value()).toEqual("res1"); expect(segments[5].value()).toEqual('10'); expect(segments[6].value()).toEqual('3'); expect(segments[7].value()).toEqual('6'); }); }); describe("Node Path (Create 2.0)", () => { let library: OasLibraryUtils; beforeEach(() => { library = new OasLibraryUtils(); }); it("Info", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let node: OasNode = document.info; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/info"; expect(actual).toEqual(expected); }); it("Tag External Documentation", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let node: OasNode = document.tags[0].externalDocs; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/tags[0]/externalDocs"; expect(actual).toEqual(expected); }); it("Path Item", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let node: OasNode = document.paths.pathItem("/pet"); let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/paths[/pet]"; expect(actual).toEqual(expected); }); it("Path Response", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let node: OasNode = document.paths.pathItem("/pet/{petId}").get.responses.response("200"); let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/paths[/pet/{petId}]/get/responses[200]"; expect(actual).toEqual(expected); }); it("Path Parameter Schema", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let node: OasNode = document.paths.pathItem("/user/{username}").put.parameters[1].schema; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/paths[/user/{username}]/put/parameters[1]/schema"; expect(actual).toEqual(expected); }); it("Definition", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let node: OasNode = document.definitions.definition("Order"); let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/definitions[Order]"; expect(actual).toEqual(expected); }); it("Definition Schema Property XML", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let node: OasNode = document.definitions.definition("Pet").properties["photoUrls"].xml; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/definitions[Pet]/properties[photoUrls]/xml"; expect(actual).toEqual(expected); }); it("Security Scheme", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let node: OasNode = document.securityDefinitions.securityScheme("petstore_auth"); let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/securityDefinitions[petstore_auth]"; expect(actual).toEqual(expected); }); it("Parameter Definition", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let node: OasNode = document.parameters.parameter("limitParam"); let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/parameters[limitParam]"; expect(actual).toEqual(expected); }); it("Default Response", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let node: OasNode = document.paths.pathItem("/user").post.responses.default; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/paths[/user]/post/responses[default]"; expect(actual).toEqual(expected); }); }); describe("Node Path (Resolve 2.0)", () => { let library: OasLibraryUtils; beforeEach(() => { library = new OasLibraryUtils(); }); it("Root", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/"); let resolvedNode: OasNode = path.resolve(document); let expectedObj: any = json; let actualObj: any = library.writeNode(resolvedNode); expect(actualObj).toEqual(expectedObj); }); it("Info", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/info"); let resolvedNode: OasNode = path.resolve(document); let expectedObj: any = json.info; let actualObj: any = library.writeNode(resolvedNode); expect(actualObj).toEqual(expectedObj); }); it("Definition Schema Property XML", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/definitions[Pet]/properties[photoUrls]/xml"); let resolvedNode: OasNode = path.resolve(document); let expectedNode: OasNode = document.definitions.definition("Pet").properties["photoUrls"].xml; let actualNode: any = resolvedNode; expect(actualNode).toEqual(expectedNode); }); it("Definition", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/definitions[Order]"); let resolvedNode: OasNode = path.resolve(document); let expectedNode: OasNode = document.definitions.definition("Order"); let actualNode: any = resolvedNode; expect(actualNode).toEqual(expectedNode); }); it("Path Response", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/paths[/pet/{petId}]/get/responses[200]"); let resolvedNode: OasNode = path.resolve(document); let expectedNode: OasNode = document.paths.pathItem("/pet/{petId}").get.responses.response("200"); let actualNode: any = resolvedNode; expect(actualNode).toEqual(expectedNode); }); it("Tag External Documentation", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/tags[0]/externalDocs"); let resolvedNode: OasNode = path.resolve(document); let expectedNode: OasNode = document.tags[0].externalDocs; let actualNode: any = resolvedNode; expect(actualNode).toEqual(expectedNode); }); it("Security Scheme", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/securityDefinitions[petstore_auth]"); let resolvedNode: OasNode = path.resolve(document); let expectedNode: OasNode = document.securityDefinitions.securityScheme("petstore_auth"); let actualNode: any = resolvedNode; expect(actualNode).toEqual(expectedNode); }); it("Default Response", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/paths[/user]/post/responses[default]"); let resolvedNode: OasNode = path.resolve(document); let expectedNode: OasNode = document.paths.pathItem("/user").post.responses.default; let actualNode: any = resolvedNode; expect(actualNode).toEqual(expectedNode); }); }); describe("Node Path (Create 3.0)", () => { let library: OasLibraryUtils; beforeEach(() => { library = new OasLibraryUtils(); }); it("Info", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let node: OasNode = document.info; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/info"; expect(actual).toEqual(expected); }); it("Contact", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let node: OasNode = document.info.contact; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/info/contact"; expect(actual).toEqual(expected); }); it("Request Body", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let node: OasNode = (document.paths.pathItem("/foo").get as Oas30Operation).requestBody; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/paths[/foo]/get/requestBody"; expect(actual).toEqual(expected); }); it("Request Body Example", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let node: OasNode = (document.paths.pathItem("/foo").get as Oas30Operation).requestBody.getMediaType("application/xml").examples["user"]; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/paths[/foo]/get/requestBody/content[application/xml]/examples[user]"; expect(actual).toEqual(expected); }); it("Server", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let node: OasNode = document.servers[2].getServerVariable("port"); let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/servers[2]/variables[port]"; expect(actual).toEqual(expected); }); it("Callback", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let node: OasNode = document.components.callbacks["Callback1"].pathItem("$request.header#/put-url").put; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/components/callbacks[Callback1][$request.header#/put-url]/put"; expect(actual).toEqual(expected); }); it("Parameter", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let node: OasNode = document.paths.pathItem("/foo").get.parameters[1]; let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/paths[/foo]/get/parameters[1]"; expect(actual).toEqual(expected); }); it("Parameter Definition", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let node: OasNode = document.components.getParameterDefinition("Param2"); let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/components/parameters[Param2]"; expect(actual).toEqual(expected); }); it("Validation Problem", () => { let json: any = readJSON('tests/fixtures/paths/3.0/validation-problem.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; library.validate(document); let node: OasValidationProblem = document.info.validationProblem("INF-001"); let path: OasNodePath = library.createNodePath(node); let actual: string = path.toString(); let expected: string = "/info/_validationProblems[INF-001]"; expect(actual).toEqual(expected); }); }); describe("Node Path (Resolve 3.0)", () => { let library: OasLibraryUtils; beforeEach(() => { library = new OasLibraryUtils(); }); it("Root", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let path: OasNodePath = new OasNodePath("/"); let resolvedNode: OasNode = path.resolve(document); let expectedObj: any = json; let actualObj: any = library.writeNode(resolvedNode); expect(actualObj).toEqual(expectedObj); }); it("Info", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let path: OasNodePath = new OasNodePath("/info"); let resolvedNode: OasNode = path.resolve(document); let expectedObj: any = json.info; let actualObj: any = library.writeNode(resolvedNode); expect(actualObj).toEqual(expectedObj); }); it("Contact N/A", () => { let json: any = readJSON('tests/fixtures/paths/3.0/contact-na.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let path: OasNodePath = new OasNodePath("/info/contact"); let resolvedNode: OasNode = path.resolve(document); expect(resolvedNode).toBeNull(); }); it("Callback Request Body", () => { let json: any = readJSON('tests/fixtures/paths/3.0/example.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let path: OasNodePath = new OasNodePath("/components/callbacks[Callback2][$request.body#/url]/post/requestBody/content[application/json]"); let resolvedNode: OasNode = path.resolve(document); let expectedObj: any = json.components.callbacks["Callback2"]["$request.body#/url"].post.requestBody.content["application/json"]; let actualObj: any = library.writeNode(resolvedNode); expect(actualObj).toEqual(expectedObj); }); it("Encoding Header", () => { let json: any = readJSON('tests/fixtures/paths/3.0/encoding-header.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; let path: OasNodePath = new OasNodePath("/paths[/encoding/header]/post/requestBody/content[multipart/form-data]/encoding[historyMetadata]/headers[X-Header-1]"); let resolvedNode: OasNode = path.resolve(document); let expectedObj: any = json.paths["/encoding/header"].post.requestBody.content["multipart/form-data"].encoding["historyMetadata"].headers["X-Header-1"]; let actualObj: any = library.writeNode(resolvedNode); expect(actualObj).toEqual(expectedObj); let header: Oas30Header = (document.paths.pathItem("/encoding/header").post as Oas30Operation) .requestBody.getMediaType("multipart/form-data").getEncoding("historyMetadata").getHeader("X-Header-1"); let headerPath: OasNodePath = library.createNodePath(header); expect(headerPath.toString()).toEqual("/paths[/encoding/header]/post/requestBody/content[multipart/form-data]/encoding[historyMetadata]/headers[X-Header-1]"); }); it("Validation Problem", () => { let json: any = readJSON('tests/fixtures/paths/3.0/validation-problem.json'); let document: Oas30Document = library.createDocument(json) as Oas30Document; // Generate validation problems in the data model. library.validate(document); let path: OasNodePath = new OasNodePath("/info/_validationProblems[INF-001]"); let resolvedNode: OasNode = path.resolve(document); let resolvedProblem: OasValidationProblem = resolvedNode as OasValidationProblem; expect(resolvedProblem.errorCode).toEqual("INF-001"); expect(resolvedProblem.message).toEqual(`API is missing a title.`); }); }); describe("Node Path Contains", () => { let library: OasLibraryUtils; beforeEach(() => { library = new OasLibraryUtils(); }); it("Root Document", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/"); expect(path.contains(document)).toBeTruthy(); }); it("Info", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/info"); expect(path.contains(document)).toBeTruthy(); expect(path.contains(document.info)).toBeTruthy(); path = new OasNodePath("/externalDocs"); expect(path.contains(document)).toBeTruthy(); expect(path.contains(document.info)).toBeFalsy(); }); it("Schema Definition", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/definitions[Order]"); expect(path.contains(document)).toBeTruthy(); expect(path.contains(document.info)).toBeFalsy(); expect(path.contains(document.definitions.definition("Order"))).toBeTruthy(); expect(path.contains(document.definitions.definition("Category"))).toBeFalsy(); }); it("Paths", () => { let json: any = readJSON('tests/fixtures/paths/2.0/pet-store.json'); let document: Oas20Document = library.createDocument(json) as Oas20Document; let path: OasNodePath = new OasNodePath("/paths[/pet]/post/parameters[0]"); expect(path.contains(document)).toBeTruthy(); expect(path.contains(document.info)).toBeFalsy(); expect(path.contains(document.definitions.definition("Order"))).toBeFalsy(); expect(path.contains(document.definitions.definition("Category"))).toBeFalsy(); expect(path.contains(document.paths.pathItem("/pet"))).toBeTruthy(); expect(path.contains(document.paths.pathItem("/pet").post)).toBeTruthy(); expect(path.contains(document.paths.pathItem("/pet").post.parameters[0])).toBeTruthy(); expect(path.contains(document.paths.pathItem("/pet").put)).toBeFalsy(); expect(path.contains(document.paths.pathItem("/pet/findByStatus"))).toBeFalsy(); }); });
the_stack
'use strict' import { Algebra } from 'sparqljs' import { BGPCache } from './engine/cache/bgp-cache' import { Bindings, BindingBase } from './rdf/bindings' import { BlankNode, Literal, NamedNode, Term } from 'rdf-js' import { includes, union } from 'lodash' import { parseZone, Moment, ISO_8601 } from 'moment' import { Pipeline } from './engine/pipeline/pipeline' import { PipelineStage } from './engine/pipeline/pipeline-engine' import { termToString, stringToTerm } from 'rdf-string' import * as crypto from 'crypto' import * as DataFactory from '@rdfjs/data-model' import * as uuid from 'uuid/v4' import BGPStageBuilder from './engine/stages/bgp-stage-builder' import ExecutionContext from './engine/context/execution-context' import ContextSymbols from './engine/context/symbols' import Graph from './rdf/graph' /** * RDF related utilities */ export namespace rdf { /** * Test if two triple (patterns) are equals * @param a - First triple (pattern) * @param b - Second triple (pattern) * @return True if the two triple (patterns) are equals, False otherwise */ export function tripleEquals (a: Algebra.TripleObject, b: Algebra.TripleObject): boolean { return a.subject === b.subject && a.predicate === b.predicate && a.object === b.object } /** * Convert an string RDF Term to a RDFJS representation * @see https://rdf.js.org/data-model-spec * @param term - A string-based term representation * @return A RDF.js term */ export function fromN3 (term: string): Term { return stringToTerm(term) } /** * Convert an RDFJS term to a string-based representation * @see https://rdf.js.org/data-model-spec * @param term A RDFJS term * @return A string-based term representation */ export function toN3 (term: Term): string { return termToString(term) } /** * Parse a RDF Literal to its Javascript representation * @see https://www.w3.org/TR/rdf11-concepts/#section-Datatypes * @param value - Literal value * @param type - Literal datatype * @return Javascript representation of the literal */ export function asJS (value: string, type: string | null): any { switch (type) { case XSD('integer'): case XSD('byte'): case XSD('short'): case XSD('int'): case XSD('unsignedByte'): case XSD('unsignedShort'): case XSD('unsignedInt'): case XSD('number'): case XSD('float'): case XSD('decimal'): case XSD('double'): case XSD('long'): case XSD('unsignedLong'): case XSD('positiveInteger'): case XSD('nonPositiveInteger'): case XSD('negativeInteger'): case XSD('nonNegativeInteger'): return Number(value) case XSD('boolean'): return value === 'true' || value === '1' case XSD('dateTime'): case XSD('dateTimeStamp'): case XSD('date'): case XSD('time'): case XSD('duration'): return parseZone(value, ISO_8601) case XSD('hexBinary'): return Buffer.from(value, 'hex') case XSD('base64Binary'): return Buffer.from(value, 'base64') default: return value } } /** * Creates an IRI in RDFJS format * @param value - IRI value * @return A new IRI in RDFJS format */ export function createIRI (value: string): NamedNode { if (value.startsWith('<') && value.endsWith('>')) { return DataFactory.namedNode(value.slice(0, value.length - 1)) } return DataFactory.namedNode(value) } /** * Creates a Blank Node in RDFJS format * @param value - Blank node value * @return A new Blank Node in RDFJS format */ export function createBNode (value?: string): BlankNode { return DataFactory.blankNode(value) } /** * Creates a Literal in RDFJS format, without any datatype or language tag * @param value - Literal value * @return A new literal in RDFJS format */ export function createLiteral (value: string): Literal { return DataFactory.literal(value) } /** * Creates an typed Literal in RDFJS format * @param value - Literal value * @param type - Literal type (integer, float, dateTime, ...) * @return A new typed Literal in RDFJS format */ export function createTypedLiteral (value: any, type: string): Literal { return DataFactory.literal(`${value}`, createIRI(type)) } /** * Creates a Literal with a language tag in RDFJS format * @param value - Literal value * @param language - Language tag (en, fr, it, ...) * @return A new Literal with a language tag in RDFJS format */ export function createLangLiteral (value: string, language: string): Literal { return DataFactory.literal(value, language) } /** * Creates an integer Literal in RDFJS format * @param value - Integer * @return A new integer in RDFJS format */ export function createInteger (value: number): Literal { return createTypedLiteral(value, XSD('integer')) } /** * Creates an float Literal in RDFJS format * @param value - Float * @return A new float in RDFJS format */ export function createFloat (value: number): Literal { return createTypedLiteral(value, XSD('float')) } /** * Creates a Literal from a boolean, in RDFJS format * @param value - Boolean * @return A new boolean in RDFJS format */ export function createBoolean (value: boolean): Literal { return value ? createTrue() : createFalse() } /** * Creates a True boolean, in RDFJS format * @return A new boolean in RDFJS format */ export function createTrue (): Literal { return createTypedLiteral('true', XSD('boolean')) } /** * Creates a False boolean, in RDFJS format * @return A new boolean in RDFJS format */ export function createFalse (): Literal { return createTypedLiteral('false', XSD('boolean')) } /** * Creates a Literal from a Moment.js date, in RDFJS format * @param date - Date, in Moment.js format * @return A new date literal in RDFJS format */ export function createDate (date: Moment): Literal { return createTypedLiteral(date.toISOString(), XSD('dateTime')) } /** * Creates an unbounded literal, used when a variable is not bounded in a set of bindings * @return A new literal in RDFJS format */ export function createUnbound (): Literal { return createLiteral('UNBOUND') } /** * Clone a literal and replace its value with another one * @param base - Literal to clone * @param newValue - New literal value * @return The literal with its new value */ export function shallowCloneTerm (term: Term, newValue: string): Term { if (termIsLiteral(term)) { if (term.language !== '') { return createLangLiteral(newValue, term.language) } return createTypedLiteral(newValue, term.datatype.value) } return createLiteral(newValue) } /** * Test if a RDFJS Term is a Literal * @param term - RDFJS Term * @return True of the term is a Literal, False otherwise */ export function termIsLiteral (term: Term): term is Literal { return term.termType === 'Literal' } /** * Test if a RDFJS Term is an IRI, i.e., a NamedNode * @param term - RDFJS Term * @return True of the term is an IRI, False otherwise */ export function termIsIRI (term: Term): term is NamedNode { return term.termType === 'NamedNode' } /** * Test if a RDFJS Term is a Blank Node * @param term - RDFJS Term * @return True of the term is a Blank Node, False otherwise */ export function termIsBNode (term: Term): term is BlankNode { return term.termType === 'BlankNode' } /** * Test if a RDFJS Literal is a number * @param literal - RDFJS Literal * @return True of the Literal is a number, False otherwise */ export function literalIsNumeric (literal: Literal): boolean { switch (literal.datatype.value) { case XSD('integer'): case XSD('byte'): case XSD('short'): case XSD('int'): case XSD('unsignedByte'): case XSD('unsignedShort'): case XSD('unsignedInt'): case XSD('number'): case XSD('float'): case XSD('decimal'): case XSD('double'): case XSD('long'): case XSD('unsignedLong'): case XSD('positiveInteger'): case XSD('nonPositiveInteger'): case XSD('negativeInteger'): case XSD('nonNegativeInteger'): return true default: return false } } /** * Test if a RDFJS Literal is a date * @param literal - RDFJS Literal * @return True of the Literal is a date, False otherwise */ export function literalIsDate (literal: Literal): boolean { return literal.datatype.value === XSD('dateTime') } /** * Test if a RDFJS Literal is a boolean * @param term - RDFJS Literal * @return True of the Literal is a boolean, False otherwise */ export function literalIsBoolean (literal: Literal): boolean { return literal.datatype.value === XSD('boolean') } /** * Test if two RDFJS Terms are equals * @param a - First Term * @param b - Second Term * @return True if the two RDFJS Terms are equals, False */ export function termEquals (a: Term, b: Term): boolean { if (termIsLiteral(a) && termIsLiteral(b)) { if (literalIsDate(a) && literalIsDate(b)) { const valueA = asJS(a.value, a.datatype.value) const valueB = asJS(b.value, b.datatype.value) // use Moment.js isSame function to compare two dates return valueA.isSame(valueB) } return a.value === b.value && a.datatype.value === b.datatype.value && a.language === b.language } return a.value === b.value } /** * Create a RDF triple in Object representation * @param {string} subj - Triple's subject * @param {string} pred - Triple's predicate * @param {string} obj - Triple's object * @return A RDF triple in Object representation */ export function triple (subj: string, pred: string, obj: string): Algebra.TripleObject { return { subject: subj, predicate: pred, object: obj } } /** * Count the number of variables in a Triple Pattern * @param {Object} triple - Triple Pattern to process * @return The number of variables in the Triple Pattern */ export function countVariables (triple: Algebra.TripleObject): number { let count = 0 if (isVariable(triple.subject)) { count++ } if (isVariable(triple.predicate)) { count++ } if (isVariable(triple.object)) { count++ } return count } /** * Return True if a string is a SPARQL variable * @param str - String to test * @return True if the string is a SPARQL variable, False otherwise */ export function isVariable (str: string): boolean { if (typeof str !== 'string') { return false } return str.startsWith('?') } /** * Return True if a string is a RDF Literal * @param str - String to test * @return True if the string is a RDF Literal, False otherwise */ export function isLiteral (str: string): boolean { return str.startsWith('"') } /** * Return True if a string is a RDF IRI/URI * @param str - String to test * @return True if the string is a RDF IRI/URI, False otherwise */ export function isIRI (str: string): boolean { return (!isVariable(str)) && (!isLiteral(str)) } /** * Get the value (excluding datatype & language tags) of a RDF literal * @param literal - RDF Literal * @return The literal's value */ export function getLiteralValue (literal: string): string { if (literal.startsWith('"')) { let stopIndex = literal.length - 1 if (literal.includes('"^^<') && literal.endsWith('>')) { stopIndex = literal.lastIndexOf('"^^<') } else if (literal.includes('"@') && !literal.endsWith('"')) { stopIndex = literal.lastIndexOf('"@') } return literal.slice(1, stopIndex) } return literal } /** * Hash Triple (pattern) to assign it an unique ID * @param triple - Triple (pattern) to hash * @return An unique ID to identify the Triple (pattern) */ export function hashTriple (triple: Algebra.TripleObject): string { return `s=${triple.subject}&p=${triple.predicate}&o=${triple.object}` } /** * Create an IRI under the XSD namespace * (<http://www.w3.org/2001/XMLSchema#>) * @param suffix - Suffix appended to the XSD namespace to create an IRI * @return An new IRI, under the XSD namespac */ export function XSD (suffix: string): string { return `http://www.w3.org/2001/XMLSchema#${suffix}` } /** * Create an IRI under the RDF namespace * (<http://www.w3.org/1999/02/22-rdf-syntax-ns#>) * @param suffix - Suffix appended to the RDF namespace to create an IRI * @return An new IRI, under the RDF namespac */ export function RDF (suffix: string): string { return `http://www.w3.org/1999/02/22-rdf-syntax-ns#${suffix}` } /** * Create an IRI under the SEF namespace * (<https://callidon.github.io/sparql-engine/functions#>) * @param suffix - Suffix appended to the SES namespace to create an IRI * @return An new IRI, under the SES namespac */ export function SEF (suffix: string): string { return `https://callidon.github.io/sparql-engine/functions#${suffix}` } /** * Create an IRI under the SES namespace * (<https://callidon.github.io/sparql-engine/search#>) * @param suffix - Suffix appended to the SES namespace to create an IRI * @return An new IRI, under the SES namespac */ export function SES (suffix: string): string { return `https://callidon.github.io/sparql-engine/search#${suffix}` } } /** * SPARQL related utilities */ export namespace sparql { /** * Hash Basic Graph pattern to assign them an unique ID * @param bgp - Basic Graph Pattern to hash * @param md5 - True if the ID should be hashed to md5, False to keep it as a plain text string * @return An unique ID to identify the BGP */ export function hashBGP (bgp: Algebra.TripleObject[], md5: boolean = false): string { const hashedBGP = bgp.map(rdf.hashTriple).join(';') if (!md5) { return hashedBGP } const hash = crypto.createHash('md5') hash.update(hashedBGP) return hash.digest('hex') } /** * Get the set of SPARQL variables in a triple pattern * @param pattern - Triple Pattern * @return The set of SPARQL variables in the triple pattern */ export function variablesFromPattern (pattern: Algebra.TripleObject): string[] { const res: string[] = [] if (rdf.isVariable(pattern.subject)) { res.push(pattern.subject) } if (rdf.isVariable(pattern.predicate)) { res.push(pattern.predicate) } if (rdf.isVariable(pattern.object)) { res.push(pattern.object) } return res } /** * Perform a join ordering of a set of triple pattern, i.e., a BGP. * Sort pattern such as they creates a valid left linear tree without cartesian products (unless it's required to evaluate the BGP) * @param patterns - Set of triple pattern * @return Order set of triple patterns */ export function leftLinearJoinOrdering (patterns: Algebra.TripleObject[]): Algebra.TripleObject[] { const results: Algebra.TripleObject[] = [] const x = new Set() if (patterns.length > 0) { // sort pattern by join predicate let p = patterns.shift()! let variables = variablesFromPattern(p) results.push(p) while (patterns.length > 0) { // find the next pattern with a common join predicate let index = patterns.findIndex(pattern => { return includes(variables, pattern.subject) || includes(variables, pattern.predicate) || includes(variables, pattern.object) }) // if not found, trigger a cartesian product with the first pattern of the sorted set if (index < 0) { index = 0 } // get the new pattern to join with p = patterns.splice(index, 1)[0] variables = union(variables, variablesFromPattern(p)) results.push(p) } } return results } } /** * Utilities related to SPARQL query evaluation * @author Thomas Minier */ export namespace evaluation { /** * Evaluate a Basic Graph pattern on a RDF graph using a cache * @param bgp - Basic Graph pattern to evaluate * @param graph - RDF graph * @param cache - Cache used * @return A pipeline stage that produces the evaluation results */ export function cacheEvalBGP (patterns: Algebra.TripleObject[], graph: Graph, cache: BGPCache, builder: BGPStageBuilder, context: ExecutionContext): PipelineStage<Bindings> { const bgp = { patterns, graphIRI: graph.iri } const [subsetBGP, missingBGP] = cache.findSubset(bgp) // case 1: no subset of the BGP are in cache => classic evaluation (most frequent) if (subsetBGP.length === 0) { // we cannot cache the BGP if the query has a LIMIT and/or OFFSET modiifier // otherwise we will cache incomplete results. So, we just evaluate the BGP if (context.hasProperty(ContextSymbols.HAS_LIMIT_OFFSET) && context.getProperty(ContextSymbols.HAS_LIMIT_OFFSET)) { return graph.evalBGP(patterns, context) } // generate an unique writer ID const writerID = uuid() // evaluate the BGP while saving all solutions into the cache const iterator = Pipeline.getInstance().tap(graph.evalBGP(patterns, context), b => { cache.update(bgp, b, writerID) }) // commit the cache entry when the BGP evaluation is done return Pipeline.getInstance().finalize(iterator, () => { cache.commit(bgp, writerID) }) } // case 2: no missing patterns => the complete BGP is in the cache if (missingBGP.length === 0) { return cache.getAsPipeline(bgp, () => graph.evalBGP(patterns, context)) } const cachedBGP = { patterns: subsetBGP, graphIRI: graph.iri } // case 3: evaluate the subset BGP using the cache, then join with the missing patterns const iterator = cache.getAsPipeline(cachedBGP, () => graph.evalBGP(subsetBGP, context)) return builder.execute(iterator, missingBGP, context) } } /** * Bound a triple pattern using a set of bindings, i.e., substitute variables in the triple pattern * using the set of bindings provided * @param triple - Triple pattern * @param bindings - Set of bindings * @return An new, bounded triple pattern */ export function applyBindings (triple: Algebra.TripleObject, bindings: Bindings): Algebra.TripleObject { const newTriple = Object.assign({}, triple) if (triple.subject.startsWith('?') && bindings.has(triple.subject)) { newTriple.subject = bindings.get(triple.subject)! } if (triple.predicate.startsWith('?') && bindings.has(triple.predicate)) { newTriple.predicate = bindings.get(triple.predicate)! } if (triple.object.startsWith('?') && bindings.has(triple.object)) { newTriple.object = bindings.get(triple.object)! } return newTriple } /** * Recursively apply bindings to every triple in a SPARQL group pattern * @param group - SPARQL group pattern to process * @param bindings - Set of bindings to use * @return A new SPARQL group pattern with triples bounded */ export function deepApplyBindings (group: Algebra.PlanNode, bindings: Bindings): Algebra.PlanNode { switch (group.type) { case 'bgp': // WARNING property paths are not supported here const triples = (group as Algebra.BGPNode).triples as Algebra.TripleObject[] const bgp: Algebra.BGPNode = { type: 'bgp', triples: triples.map(t => bindings.bound(t)) } return bgp case 'group': case 'optional': case 'service': case 'union': const newGroup: Algebra.GroupNode = { type: group.type, patterns: (group as Algebra.GroupNode).patterns.map(g => deepApplyBindings(g, bindings)) } return newGroup case 'query': let subQuery: Algebra.RootNode = (group as Algebra.RootNode) subQuery.where = subQuery.where.map(g => deepApplyBindings(g, bindings)) return subQuery default: return group } } /** * Extends all set of bindings produced by an iterator with another set of bindings * @param source - Source {@link PipelineStage} * @param bindings - Bindings added to each set of bindings procuded by the iterator * @return A {@link PipelineStage} that extends bindins produced by the source iterator */ export function extendByBindings (source: PipelineStage<Bindings>, bindings: Bindings): PipelineStage<Bindings> { return Pipeline.getInstance().map(source, (b: Bindings) => bindings.union(b)) }
the_stack
import "mocha"; import { canfulfill, RequestEnvelope } from "ask-sdk-model"; import { expect } from "chai"; import * as _ from "lodash"; import * as simple from "simple-mock"; import { AlexaEvent, AlexaPlatform, AlexaReply, ITransition, IVoxaEvent, IVoxaIntentEvent, IVoxaReply, Model, State, VoxaApp, } from "../src"; import { AlexaRequestBuilder } from "./tools"; import { variables } from "./variables"; import { views } from "./views"; import { UnknownState } from "../src/errors"; import { StateMachine } from "../src/StateMachine/StateMachine"; const rb = new AlexaRequestBuilder(); describe("VoxaApp", () => { let statesDefinition: any; let event: RequestEnvelope; beforeEach(() => { event = rb.getIntentRequest("SomeIntent"); simple.mock(AlexaPlatform, "apiRequest").resolveWith(true); statesDefinition = { DisplayElementSelected: { tell: "ExitIntent.Farewell", to: "die" }, SomeIntent: { tell: "ExitIntent.Farewell", to: "die" }, initState: { to: "endState" }, secondState: { to: "initState" }, thirdState: () => Promise.resolve({ to: "endState" }), }; }); it("should have the APL Template directive before the APL Command directive in the Alexa Platform", () => { // The APL Template should always be before the APL Command in the directives array in order to work. // Don't ask why, that's how Amazon likes it. const voxaApp = new VoxaApp({ variables, views }); const platform = new AlexaPlatform(voxaApp); const APLTemplateIndex = voxaApp.directiveHandlers.findIndex( (directive) => directive.key === "alexaAPLTemplate", ); const APLCommandIndex = voxaApp.directiveHandlers.findIndex( (directive) => directive.key === "alexaAPLCommand", ); expect(APLTemplateIndex).to.be.lessThan(APLCommandIndex); }); it("should have the APLT Template directive before the APLT Command directive in the Alexa Platform", () => { // The APLT Template should always be before the APLT Command in the directives array in order to work. // Don't ask why, that's how Amazon likes it. const voxaApp = new VoxaApp({ variables, views }); const platform = new AlexaPlatform(voxaApp); const APLTTemplateIndex = voxaApp.directiveHandlers.findIndex( (directive) => directive.key === "alexaAPLTTemplate", ); const APLTCommandIndex = voxaApp.directiveHandlers.findIndex( (directive) => directive.key === "alexaAPLTCommand", ); expect(APLTTemplateIndex).to.be.lessThan(APLTCommandIndex); }); it("should include the state in the session attributes", async () => { const voxaApp = new VoxaApp({ variables, views }); const platform = new AlexaPlatform(voxaApp); voxaApp.onIntent("LaunchIntent", () => { return { to: "secondState", sayp: "This is my message", flow: "yield" }; }); voxaApp.onState("secondState", () => ({})); const launchEvent = new AlexaEvent(rb.getIntentRequest("LaunchIntent")); launchEvent.platform = platform; const reply = (await voxaApp.execute( launchEvent, new AlexaReply(), )) as AlexaReply; expect(reply.sessionAttributes.state).to.equal("secondState"); expect(reply.response.shouldEndSession).to.be.false; }); it("should include outputAttributes in the session attributes", async () => { const voxaApp = new VoxaApp({ variables, views }); const platform = new AlexaPlatform(voxaApp); voxaApp.onIntent("LaunchIntent", (request) => { request.session.outputAttributes.foo = "bar"; return { to: "secondState", sayp: "This is my message", flow: "yield" }; }); voxaApp.onState("secondState", () => ({})); const launchEvent = new AlexaEvent(rb.getIntentRequest("LaunchIntent")); launchEvent.platform = platform; const reply = (await voxaApp.execute( launchEvent, new AlexaReply(), )) as AlexaReply; expect(reply.sessionAttributes.foo).to.equal("bar"); }); it("should add the message key from the transition to the reply", async () => { const voxaApp = new VoxaApp({ variables, views }); const platform = new AlexaPlatform(voxaApp); voxaApp.onIntent("LaunchIntent", () => ({ sayp: "This is my message" })); const launchEvent = new AlexaEvent(rb.getIntentRequest("LaunchIntent")); launchEvent.platform = platform; const reply = (await voxaApp.execute( launchEvent, new AlexaReply(), )) as AlexaReply; expect(reply.speech).to.deep.equal("<speak>This is my message</speak>"); }); it("should throw an error if trying to render a missing view", async () => { const voxaApp = new VoxaApp({ variables, views }); const platform = new AlexaPlatform(voxaApp); voxaApp.onIntent("LaunchIntent", () => ({ ask: "Missing.View" })); const launchEvent = new AlexaEvent(rb.getIntentRequest("LaunchIntent")); launchEvent.platform = platform; const reply = (await voxaApp.execute( launchEvent, new AlexaReply(), )) as AlexaReply; // expect(reply.error).to.be.an("error"); expect(reply.speech).to.equal( "<speak>An unrecoverable error occurred.</speak>", ); }); it("should allow multiple reply paths in reply key", async () => { const voxaApp = new VoxaApp({ variables, views }); const platform = new AlexaPlatform(voxaApp); voxaApp.onIntent("LaunchIntent", (voxaEvent) => { voxaEvent.model.count = 0; return { say: ["Count.Say", "Count.Tell"] }; }); const launchEvent = new AlexaEvent(rb.getIntentRequest("LaunchIntent")); launchEvent.platform = platform; const reply = (await voxaApp.execute( launchEvent, new AlexaReply(), )) as AlexaReply; expect(reply.speech).to.deep.equal("<speak>0\n0</speak>"); }); it("should display element selected request", async () => { const voxaApp = new VoxaApp({ variables, views }); const alexaEvent = rb.getDisplayElementSelectedRequest("token"); voxaApp.onIntent("Display.ElementSelected", { tell: "ExitIntent.Farewell", to: "die", }); const alexaSkill = new AlexaPlatform(voxaApp); const reply = await alexaSkill.execute(alexaEvent); expect(_.get(reply, "response.outputSpeech.ssml")).to.equal( "<speak>Ok. For more info visit example.com site.</speak>", ); }); it("should be able to just pass through some intents to states", async () => { const voxaApp = new VoxaApp({ variables, views }); let called = false; voxaApp.onIntent("LoopOffIntent", () => { called = true; return { tell: "ExitIntent.Farewell", to: "die" }; }); const alexa = new AlexaPlatform(voxaApp); const loopOffEvent = rb.getIntentRequest("AMAZON.LoopOffIntent"); await alexa.execute(loopOffEvent); expect(called).to.be.true; }); describe("onBeforeStateChanged", () => { it("should accept onBeforeStateChanged callbacks", () => { const voxaApp = new VoxaApp({ variables, views }); voxaApp.onBeforeStateChanged(simple.stub()); }); it("should execute handlers before each state", async () => { const voxaApp = new VoxaApp({ variables, views }); const platform = new AlexaPlatform(voxaApp); voxaApp.onBeforeStateChanged( (voxaEvent: IVoxaEvent, voxaReply: IVoxaReply, state: State) => { voxaEvent.model.previousState = state.name; }, ); voxaApp.onIntent("SomeIntent", (voxaEvent: IVoxaIntentEvent) => { expect(voxaEvent.model.previousState).to.equal("SomeIntent"); return { flow: "terminate", sayp: "done", }; }); const reply = await platform.execute(event); expect(reply.speech).to.equal("<speak>done</speak>"); }); }); it("should set properties on request and have those available in the state callbacks", async () => { const voxaApp = new VoxaApp({ views, variables }); statesDefinition.SomeIntent = simple.spy((request) => { expect(request.model).to.not.be.undefined; expect(request.model).to.be.an.instanceOf(Model); return { tell: "ExitIntent.Farewell", to: "die" }; }); _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const platform = new AlexaPlatform(voxaApp); const alexaEvent = event; await platform.execute(alexaEvent); expect(statesDefinition.SomeIntent.called).to.be.true; expect(statesDefinition.SomeIntent.lastCall.threw).to.be.not.ok; }); // it("should simply set an empty session if serialize is missing", async () => { // const voxaApp = new VoxaApp({ views, variables }); // statesDefinition.entry = simple.spy((request) => { // request.model = null; // return { ask: "Ask", to: "initState" }; // }); // _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state)); // const reply = await voxaApp.execute(event, new AlexaReply()) as AlexaReply; // // expect(reply.error).to.be.undefined; // expect(statesDefinition.entry.called).to.be.true; // expect(statesDefinition.entry.lastCall.threw).to.be.not.ok; // expect(reply.sessionAttributes).to.deep.equal(new Model({ state: "initState" })); // }); it("should allow async serialization in Model", async () => { class PromisyModel extends Model { public serialize() { // eslint-disable-line class-methods-use-this return Promise.resolve({ value: 1, }); } } const voxaApp = new VoxaApp({ views, variables, Model: PromisyModel }); statesDefinition.SomeIntent = simple.spy((request) => { expect(request.model).to.not.be.undefined; expect(request.model).to.be.an.instanceOf(PromisyModel); return { ask: "Ask", to: "initState" }; }); _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const platform = new AlexaPlatform(voxaApp); const reply = (await platform.execute(event)) as AlexaReply; expect(statesDefinition.SomeIntent.called).to.be.true; expect(statesDefinition.SomeIntent.lastCall.threw).to.be.not.ok; expect(reply.sessionAttributes).to.deep.equal({ model: { value: 1 }, state: "initState", }); }); it("should let model.deserialize return a Promise", async () => { class PromisyModel extends Model { public static async deserialize(data: any) { const model = new PromisyModel(); model.didDeserialize = "yep"; return model; } } const voxaApp = new VoxaApp({ views, variables, Model: PromisyModel }); const platform = new AlexaPlatform(voxaApp); const alexaEvent = new AlexaEvent(event); alexaEvent.platform = platform; statesDefinition.SomeIntent = simple.spy((request) => { expect(request.model).to.not.be.undefined; expect(request.model).to.be.an.instanceOf(PromisyModel); expect(request.model.didDeserialize).to.eql("yep"); return { say: "ExitIntent.Farewell", to: "die" }; }); _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const sessionEvent = rb.getIntentRequest("SomeIntent"); _.set(sessionEvent, "session.attributes", { model: { foo: "bar" } }); await voxaApp.execute(alexaEvent, new AlexaReply()); expect(statesDefinition.SomeIntent.called).to.be.true; expect(statesDefinition.SomeIntent.lastCall.threw).to.be.not.ok; }); it("should call onSessionEnded callbacks if state is die", async () => { const voxaApp = new VoxaApp({ Model, views, variables }); const platform = new AlexaPlatform(voxaApp); const alexaEvent = event; _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const onSessionEnded = simple.stub(); voxaApp.onSessionEnded(onSessionEnded); await platform.execute(alexaEvent); expect(onSessionEnded.called).to.be.true; }); it("should call onBeforeReplySent callbacks", async () => { const voxaApp = new VoxaApp({ Model, views, variables }); const platform = new AlexaPlatform(voxaApp); const alexaEvent = new AlexaEvent(event); alexaEvent.platform = platform; _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const onBeforeReplySent = simple.stub(); voxaApp.onBeforeReplySent(onBeforeReplySent); await voxaApp.execute(alexaEvent, new AlexaReply()); expect(onBeforeReplySent.called).to.be.true; }); it("should fulfill request", async () => { const canFulfillIntent: canfulfill.CanFulfillIntent = { canFulfill: "YES", slots: { slot1: { canFulfill: "YES", canUnderstand: "YES", }, }, }; const voxaApp = new VoxaApp({ views, variables }); const alexaSkill = new AlexaPlatform(voxaApp); voxaApp.onCanFulfillIntentRequest( (alexaEvent: AlexaEvent, alexaReply: AlexaReply) => { alexaReply.fulfillIntent("YES"); alexaReply.fulfillSlot("slot1", "YES", "YES"); return alexaReply; }, ); event = rb.getCanFulfillIntentRequestRequest("NameIntent", { slot1: "something", }); const reply = (await alexaSkill.execute(event)) as AlexaReply; expect(reply.response.card).to.be.undefined; expect(reply.response.reprompt).to.be.undefined; expect(reply.response.outputSpeech).to.be.undefined; expect(reply.response.canFulfillIntent).to.deep.equal(canFulfillIntent); }); it("should fulfill request with default intents", async () => { const canFulfillIntent = { canFulfill: "YES", slots: { slot1: { canFulfill: "YES", canUnderstand: "YES", }, }, }; const defaultFulfillIntents = ["NameIntent"]; const voxaApp = new VoxaApp({ views, variables }); const alexaSkill = new AlexaPlatform(voxaApp, { defaultFulfillIntents }); event = rb.getCanFulfillIntentRequestRequest("NameIntent", { slot1: "something", }); const reply = (await alexaSkill.execute(event)) as AlexaReply; expect(reply.response.card).to.be.undefined; expect(reply.response.reprompt).to.be.undefined; expect(reply.response.outputSpeech).to.be.undefined; expect(reply.response.canFulfillIntent).to.deep.equal(canFulfillIntent); }); it("should return MAYBE fulfill response to CanFulfillIntentRequest", async () => { const canFulfillIntent: canfulfill.CanFulfillIntent = { canFulfill: "MAYBE", slots: { slot1: { canFulfill: "YES", canUnderstand: "YES", }, }, }; const voxaApp = new VoxaApp({ views, variables }); const alexaSkill = new AlexaPlatform(voxaApp); voxaApp.onCanFulfillIntentRequest( (alexaEvent: AlexaEvent, alexaReply: AlexaReply) => { alexaReply.fulfillIntent("MAYBE"); alexaReply.fulfillSlot("slot1", "YES", "YES"); return alexaReply; }, ); event = rb.getCanFulfillIntentRequestRequest("NameIntent", { slot1: "something", }); const reply = (await alexaSkill.execute(event)) as AlexaReply; expect(reply.response.card).to.be.undefined; expect(reply.response.reprompt).to.be.undefined; expect(reply.response.outputSpeech).to.be.undefined; expect(reply.response.canFulfillIntent).to.deep.equal(canFulfillIntent); }); it("should not fulfill request", async () => { const canFulfillIntent: canfulfill.CanFulfillIntent = { canFulfill: "NO", }; const voxaApp = new VoxaApp({ views, variables }); const alexaSkill = new AlexaPlatform(voxaApp); voxaApp.onCanFulfillIntentRequest( (alexaEvent: AlexaEvent, alexaReply: AlexaReply) => { alexaReply.fulfillIntent("NO"); return alexaReply; }, ); event = rb.getCanFulfillIntentRequestRequest("NameIntent", { slot1: "something", }); const reply = (await alexaSkill.execute(event)) as AlexaReply; expect(reply.response.card).to.be.undefined; expect(reply.response.reprompt).to.be.undefined; expect(reply.response.outputSpeech).to.be.undefined; expect(reply.response.canFulfillIntent).to.deep.equal(canFulfillIntent); }); it("should not fulfill request with wrong values", async () => { const canFulfillIntent: canfulfill.CanFulfillIntent = { canFulfill: "NO", slots: { slot1: { canFulfill: "NO", canUnderstand: "NO", }, }, }; const voxaApp = new VoxaApp({ views, variables }); const alexaSkill = new AlexaPlatform(voxaApp); voxaApp.onCanFulfillIntentRequest( (alexaEvent: AlexaEvent, alexaReply: AlexaReply) => { alexaReply.fulfillIntent("yes"); alexaReply.fulfillSlot("slot1", "yes", "yes"); return alexaReply; }, ); event = rb.getCanFulfillIntentRequestRequest("NameIntent", { slot1: "something", }); const reply = (await alexaSkill.execute(event)) as AlexaReply; expect(reply.response.card).to.be.undefined; expect(reply.response.reprompt).to.be.undefined; expect(reply.response.outputSpeech).to.be.undefined; expect(reply.response.canFulfillIntent).to.deep.equal(canFulfillIntent); }); describe("onUnhandledState", () => { afterEach(() => { simple.restore(); }); it("should crash if there's an unhandled state", async () => { const voxaApp = new VoxaApp({ Model, views, variables }); const platform = new AlexaPlatform(voxaApp); const launchEvent = rb.getIntentRequest("LaunchIntent"); statesDefinition.LaunchIntent = simple.stub().resolveWith(null); _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const reply = await platform.execute(launchEvent); expect(reply.speech).to.equal( "<speak>An unrecoverable error occurred.</speak>", ); }); it("should call onUnhandledState if state controller is for a specific intent", async () => { const voxaApp = new VoxaApp({ Model, views, variables }); const launchEvent = rb.getIntentRequest("LaunchIntent"); const onUnhandledState = simple.stub().returnWith( Promise.resolve({ flow: "terminate", sayp: "Unhandled State", }), ); voxaApp.onUnhandledState(onUnhandledState); voxaApp.onIntent("LaunchIntent", { to: "otherState", }); voxaApp.onState( "otherState", { flow: "terminate", sayp: "Other State", }, "SomeIntent", ); const platform = new AlexaPlatform(voxaApp); const reply = await platform.execute(launchEvent); expect(reply.speech).to.equal("<speak>Unhandled State</speak>"); expect(onUnhandledState.called).to.be.true; }); it( "should call onUnhandledState callbacks when the state" + " machine transition throws a UnhandledState error", async () => { const voxaApp = new VoxaApp({ Model, views, variables }); const platform = new AlexaPlatform(voxaApp); const launchEvent = rb.getIntentRequest("LaunchIntent"); const onUnhandledState = simple.stub().returnWith( Promise.resolve({ tell: "ExitIntent.Farewell", to: "die", }), ); voxaApp.onUnhandledState(onUnhandledState); statesDefinition.LaunchIntent = simple.stub().resolveWith(null); _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const reply = await platform.execute(launchEvent); expect(onUnhandledState.called).to.be.true; expect(reply.speech).to.equal( "<speak>Ok. For more info visit example.com site.</speak>", ); }, ); it("should call onUnhandledState for intents without a handler", async () => { const voxaApp = new VoxaApp({ Model, views, variables }); const platform = new AlexaPlatform(voxaApp); const launchEvent = rb.getIntentRequest("RandomIntent"); const onUnhandledState = simple.stub().returnWith( Promise.resolve({ tell: "ExitIntent.Farewell", to: "die", }), ); voxaApp.onUnhandledState(onUnhandledState); statesDefinition.LaunchIntent = simple.stub().resolveWith(null); _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const reply = await platform.execute(launchEvent); expect(onUnhandledState.called).to.be.true; expect(reply.speech).to.equal( "<speak>Ok. For more info visit example.com site.</speak>", ); }); it("should call onUnhandledState when UnknownState is thrown", async () => { const voxaApp = new VoxaApp({ Model, views, variables }); const platform = new AlexaPlatform(voxaApp); const launchEvent = rb.getIntentRequest("RandomIntent"); voxaApp.onUnhandledState( (voxaEvent: IVoxaEvent, stateName: string): any => { expect(stateName).to.equal("RandomIntent"); return { tell: "ExitIntent.Farewell", to: "die", }; }, ); voxaApp.onError((voxaEvent: IVoxaEvent, err: Error) => { expect(err.message).to.equal("RandomIntent went unhandled"); }); statesDefinition.LaunchIntent = simple.stub().resolveWith(null); _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const reply = await platform.execute(launchEvent); expect(reply.speech).to.equal( "<speak>Ok. For more info visit example.com site.</speak>", ); }); it("should crash with an UnknownState Error", async () => { simple .mock(StateMachine.prototype, "getCurrentState") .throwWith(new UnknownState("RandomIntent")); const voxaApp = new VoxaApp({ Model, views, variables }); const platform = new AlexaPlatform(voxaApp); const launchEvent = rb.getIntentRequest("RandomIntent"); statesDefinition.LaunchIntent = simple.stub().resolveWith(null); _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); voxaApp.onError((voxaEvent: IVoxaEvent, err: Error) => { expect(err.message).to.equal("RandomIntent went unhandled"); }); const reply = await platform.execute(launchEvent); expect(reply.speech).to.equal( "<speak>An unrecoverable error occurred.</speak>", ); }); it("should crash with a generic Error", async () => { simple .mock(StateMachine.prototype, "getCurrentState") .throwWith(new Error("Common Error")); const voxaApp = new VoxaApp({ Model, views, variables }); const platform = new AlexaPlatform(voxaApp); const launchEvent = rb.getIntentRequest("LaunchIntent"); statesDefinition.LaunchIntent = simple.stub().resolveWith(null); _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); voxaApp.onError((voxaEvent: IVoxaEvent, err: Error) => { expect(err.message).to.equal("Common Error"); }); const reply = await platform.execute(launchEvent); expect(reply.speech).to.equal( "<speak>An unrecoverable error occurred.</speak>", ); }); }); it("should include all directives in the reply", async () => { const voxaApp = new VoxaApp({ Model, variables, views }); const platform = new AlexaPlatform(voxaApp); const alexaEvent = new AlexaEvent(event); alexaEvent.platform = platform; voxaApp.onIntent("SomeIntent", () => ({ alexaPlayAudio: { behavior: "REPLACE_ALL", offsetInMilliseconds: 0, token: "123", url: "url", }, tell: "ExitIntent.Farewell", to: "entry", })); const reply = (await voxaApp.execute( alexaEvent, new AlexaReply(), )) as AlexaReply; expect(reply.response.directives).to.not.be.undefined; expect(reply.response.directives).to.have.length(1); expect(reply.response.directives).to.deep.equal([ { audioItem: { metadata: {}, stream: { offsetInMilliseconds: 0, token: "123", url: "url", }, }, playBehavior: "REPLACE_ALL", type: "AudioPlayer.Play", }, ]); }); it("should include all directives in the reply even if die", async () => { const voxaApp = new VoxaApp({ Model, variables, views }); const platform = new AlexaPlatform(voxaApp); const alexaEvent = new AlexaEvent(event); alexaEvent.platform = platform; voxaApp.onIntent("SomeIntent", () => ({ alexaPlayAudio: { behavior: "REPLACE_ALL", offsetInMilliseconds: 0, token: "123", url: "url", }, say: "ExitIntent.Farewell", })); const reply = (await voxaApp.execute( alexaEvent, new AlexaReply(), )) as AlexaReply; expect(reply.response.directives).to.not.be.undefined; expect(reply.response.directives).to.have.length(1); expect(reply.response.directives).to.deep.equal([ { audioItem: { metadata: {}, stream: { offsetInMilliseconds: 0, token: "123", url: "url", }, }, playBehavior: "REPLACE_ALL", type: "AudioPlayer.Play", }, ]); }); it("should render all messages after each transition", async () => { const launchEvent = rb.getIntentRequest("LaunchIntent"); const voxaApp = new VoxaApp({ Model, views, variables }); const platform = new AlexaPlatform(voxaApp); const alexaEvent = launchEvent; statesDefinition.LaunchIntent = { to: "fourthState", }; statesDefinition.fourthState = (request: IVoxaEvent) => { request.model.count = 0; return { say: "Count.Say", to: "fifthState" }; }; statesDefinition.fifthState = (request: IVoxaEvent) => { request.model.count = 1; return { tell: "Count.Tell", to: "die" }; }; _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const reply = await platform.execute(alexaEvent); expect(reply.speech).to.deep.equal("<speak>0\n1</speak>"); }); it("should call onIntentRequest callbacks before the statemachine", async () => { const voxaApp = new VoxaApp({ views, variables }); const platform = new AlexaPlatform(voxaApp); const alexaEvent = new AlexaEvent(event); alexaEvent.platform = platform; _.map(statesDefinition, (state: any, name: string) => voxaApp.onState(name, state), ); const stubResponse = "STUB RESPONSE"; const stub = simple.stub().resolveWith(stubResponse); voxaApp.onIntentRequest(stub); const reply = (await voxaApp.execute( alexaEvent, new AlexaReply(), )) as AlexaReply; expect(stub.called).to.be.true; expect(reply).to.not.equal(stubResponse); expect(reply.speech).to.equal( "<speak>Ok. For more info visit example.com site.</speak>", ); }); describe("onRequestStarted", () => { it("should return the onError response for exceptions thrown in onRequestStarted", async () => { const voxaApp = new VoxaApp({ views, variables }); const platform = new AlexaPlatform(voxaApp); const alexaEvent = new AlexaEvent(event); alexaEvent.platform = platform; const spy = simple.spy(() => { throw new Error("FAIL!"); }); voxaApp.onRequestStarted(spy); await voxaApp.execute(alexaEvent, new AlexaReply()); expect(spy.called).to.be.true; }); }); describe("Reply", () => { it("should pick up the say and reprompt statements", async () => { const voxaApp = new VoxaApp({ views, variables }); const platform = new AlexaPlatform(voxaApp); const launchEvent = rb.getIntentRequest("LaunchIntent"); voxaApp.onIntent("LaunchIntent", { flow: "yield", reply: "Reply.Say", to: "entry", }); const response = await platform.execute(launchEvent); expect(response.speech).to.deep.equal("<speak>this is a say</speak>"); expect(response.reprompt).to.deep.equal( "<speak>this is a reprompt</speak>", ); expect(response.hasTerminated).to.be.false; }); it("should pick up Hint and card statements", async () => { const voxaApp = new VoxaApp({ views, variables }); voxaApp.onIntent("SomeIntent", { flow: "yield", reply: "Reply.Card", reprompt: "Reprompt", say: "Say", to: "entry", }); const alexaSkill = new AlexaPlatform(voxaApp); const response = await alexaSkill.execute(event); expect(_.get(response, "response.outputSpeech.ssml")).to.deep.equal( "<speak>say</speak>", ); expect( _.get(response, "response.reprompt.outputSpeech.ssml"), ).to.deep.equal("<speak>reprompt</speak>"); expect(response.response.card).to.deep.equal({ image: { largeImageUrl: "https://example.com/large.jpg", smallImageUrl: "https://example.com/small.jpg", }, title: "Title", type: "Standard", }); expect(_.get(response, "response.directives[0]")).to.deep.equal({ hint: { text: "this is the hint", type: "PlainText", }, type: "Hint", }); }); it("should pickup arrays in the reply", async () => { const voxaApp = new VoxaApp({ views, variables }); voxaApp.onIntent("SomeIntent", { flow: "yield", reply: ["Reply.Say", "Reply.Card"], to: "entry", }); const alexaSkill = new AlexaPlatform(voxaApp); const response = await alexaSkill.execute(event); expect(response.speech).to.deep.equal("<speak>this is a say</speak>"); expect(response.reprompt).to.deep.equal( "<speak>this is a reprompt</speak>", ); expect(response.hasTerminated).to.be.false; expect(response.response.card).to.deep.equal({ image: { largeImageUrl: "https://example.com/large.jpg", smallImageUrl: "https://example.com/small.jpg", }, title: "Title", type: "Standard", }); expect(_.get(response, "response.directives[0]")).to.deep.equal({ hint: { text: "this is the hint", type: "PlainText", }, type: "Hint", }); }); it("should add the says from multiple replies", async () => { const voxaApp = new VoxaApp({ views, variables }); voxaApp.onIntent("SomeIntent", { flow: "yield", reply: ["Reply.Say", "Reply.Say2"], to: "entry", }); const alexaSkill = new AlexaPlatform(voxaApp); const response = await alexaSkill.execute(event); expect(response.speech).to.deep.equal( "<speak>this is a say\nthis is another say</speak>", ); expect(response.reprompt).to.deep.equal( "<speak>this is a reprompt</speak>", ); expect(response.hasTerminated).to.be.false; }); it("should add reply keys to the transiiton", async () => { const voxaApp = new VoxaApp({ views, variables }); const launchEvent = rb.getIntentRequest("LaunchIntent"); voxaApp.onIntent("LaunchIntent", { flow: "yield", reply: "Reply.Say", to: "entry", }); voxaApp.onBeforeReplySent( (voxaEvent: IVoxaEvent, reply: IVoxaReply, transition: ITransition) => { voxaEvent.model.transition = transition; }, ); const platform = new AlexaPlatform(voxaApp); const response = await platform.execute(launchEvent); expect(response.sessionAttributes.model.transition).to.deep.equal({ flow: "yield", reply: "Reply.Say", reprompt: "Reply.Say.reprompt", say: "Reply.Say.say", to: "entry", }); }); }); });
the_stack
import BN from 'bn.js' import { Client } from '../client' import { Contract } from '../contract' import { Address } from '../address' import { TransferGatewayWithdrawTokenRequest, TransferGatewayWithdrawETHRequest, TransferGatewayWithdrawalReceipt, TransferGatewayWithdrawalReceiptRequest, TransferGatewayWithdrawalReceiptResponse, TransferGatewayTokenKind, TransferGatewayAddContractMappingRequest, TransferGatewayTokenWithdrawalSigned, TransferGatewayContractMappingConfirmed, TransferGatewayReclaimContractTokensRequest, TransferGatewayReclaimDepositorTokensRequest, TransferGatewayGetUnclaimedTokensRequest, TransferGatewayGetUnclaimedTokensResponse, TransferGatewayListContractMappingRequest, TransferGatewayListContractMappingResponse, TransferGatewayGetLocalAccountInfoRequest, TransferGatewayGetLocalAccountInfoResponse, TransferGatewayGetContractMappingRequest, TransferGatewayGetContractMappingResponse, TransferGatewayTxStatus, TransferGatewayStateRequest, TransferGatewayStateResponse } from '../proto/transfer_gateway_pb' import { marshalBigUIntPB, unmarshalBigUIntPB } from '../big-uint' import { B64ToUint8Array } from '../crypto-utils' import { IAddressMapping } from './address-mapper' export interface IUnclaimedToken { tokenContract: Address tokenKind: TransferGatewayTokenKind tokenIds?: Array<BN> tokenAmounts?: Array<BN> } export interface ITransferGatewayState { maxTotalDailyWithdrawalAmount: BN maxPerAccountDailyWithdrawalAmount: BN lastWithdrawalLimitResetTime: Date totalWithdrawalAmount: BN } export interface IWithdrawalReceipt { tokenOwner: Address // Mainnet address of token contract (NOTE: not set when withdrawing LOOM via Binance Gateway) tokenContract?: Address tokenKind: TransferGatewayTokenKind // ERC721/X token ID tokenId?: BN // ERC721X/ERC20/ETH amount tokenAmount?: BN withdrawalNonce: BN // Signature generated by the Oracle that confirmed the withdrawal oracleSignature: Uint8Array // Withdrawal tx hash on the foreign chain (currently only used by Binance Gateway) txHash: Uint8Array // Withdrawal tx status on the foreign chain (currently only used by Binance Gateway) txStatus: TransferGatewayTxStatus // Deprecated, use tokenId and tokenAmount instead. // This is the ERC721 token ID, or ERC721X/ERC20/ETH amount. value: BN } export interface ITokenWithdrawalEventArgs { tokenOwner: Address // Mainnet address of token contract, blank if ETH tokenContract: Address tokenKind: TransferGatewayTokenKind // ERC721/X token ID tokenId?: BN // ERC721X/ERC20/ETH amount tokenAmount?: BN // Oracle signature sig: Uint8Array // Deprecated, use tokenId and tokenAmount instead. // This is the ERC721 token ID, or ERC721X/ERC20/ETH amount. value: BN } export interface IContractMappingConfirmedEventArgs { // Address of a contract on a foreign blockchain foreignContract: Address // Address of corresponding contract on the local blockchain localContract: Address } export interface ILocalAccountInfo { withdrawalReceipt: IWithdrawalReceipt | null totalWithdrawalAmount: BN lastWithdrawalLimitResetTime: number } export class TransferGateway extends Contract { // LoomJS user events static readonly EVENT_TOKEN_WITHDRAWAL = 'event_token_withdrawal' static readonly EVENT_CONTRACT_MAPPING_CONFIRMED = 'event_contract_mapping_confirmed' // Events from Loomchain static readonly tokenWithdrawalSignedEventTopic: String = 'event:TokenWithdrawalSigned' static readonly contractMappingConfirmedEventTopic: String = 'event:ContractMappingConfirmed' static async createAsync(client: Client, callerAddr: Address): Promise<TransferGateway> { const contractAddr = await client.getContractAddressAsync('gateway') if (!contractAddr) { throw Error('Failed to resolve contract address for TransferGateway') } return new TransferGateway({ contractAddr, callerAddr, client }) } constructor(params: { contractAddr: Address; callerAddr: Address; client: Client }) { super(params) this.on(Contract.EVENT, event => { if (!event.topics || event.topics.length === 0) { return } if (event.topics[0] === TransferGateway.tokenWithdrawalSignedEventTopic) { const eventData = TransferGatewayTokenWithdrawalSigned.deserializeBinary( B64ToUint8Array(event.data) ) let tokenId: BN | undefined let tokenAmount: BN | undefined let value: BN const tokenKind = eventData.getTokenKind() switch (tokenKind) { case TransferGatewayTokenKind.ERC721: tokenId = unmarshalBigUIntPB(eventData.getTokenId()!) value = tokenId break case TransferGatewayTokenKind.ERC721X: tokenId = unmarshalBigUIntPB(eventData.getTokenId()!) // fallthrough // tslint:disable-next-line: no-switch-case-fall-through default: tokenAmount = unmarshalBigUIntPB(eventData.getTokenAmount()!) value = tokenAmount break } this.emit(TransferGateway.EVENT_TOKEN_WITHDRAWAL, { tokenOwner: Address.UnmarshalPB(eventData.getTokenOwner()!), tokenContract: Address.UnmarshalPB(eventData.getTokenContract()!), tokenKind, tokenId, tokenAmount, sig: eventData.getSig_asU8(), value } as ITokenWithdrawalEventArgs) } else if (event.topics[0] === TransferGateway.contractMappingConfirmedEventTopic) { const contractMappingConfirmed = TransferGatewayContractMappingConfirmed.deserializeBinary( B64ToUint8Array(event.data) ) this.emit(TransferGateway.EVENT_CONTRACT_MAPPING_CONFIRMED, { foreignContract: Address.UnmarshalPB(contractMappingConfirmed.getForeignContract()!), localContract: Address.UnmarshalPB(contractMappingConfirmed.getLocalContract()!) } as IContractMappingConfirmedEventArgs) } }) } /** * Adds a contract mapping to the DAppChain Gateway using gatway owner signature. * A contract mapping associates a token contract on the DAppChain with it's counterpart on Ethereum. */ addAuthorizedContractMappingAsync(params: { foreignContract: Address localContract: Address }): Promise<void> { const { foreignContract, localContract } = params const mappingContractRequest = new TransferGatewayAddContractMappingRequest() mappingContractRequest.setForeignContract(foreignContract.MarshalPB()) mappingContractRequest.setLocalContract(localContract.MarshalPB()) return this.callAsync<void>('AddAuthorizedContractMapping', mappingContractRequest) } /** * Adds a contract mapping to the DAppChain Gateway. * A contract mapping associates a token contract on the DAppChain with it's counterpart on Ethereum. */ addContractMappingAsync(params: { foreignContract: Address localContract: Address foreignContractCreatorSig: Uint8Array foreignContractCreatorTxHash: Uint8Array }): Promise<void> { const { foreignContract, localContract, foreignContractCreatorSig, foreignContractCreatorTxHash } = params const mappingContractRequest = new TransferGatewayAddContractMappingRequest() mappingContractRequest.setForeignContract(foreignContract.MarshalPB()) mappingContractRequest.setLocalContract(localContract.MarshalPB()) mappingContractRequest.setForeignContractCreatorSig(foreignContractCreatorSig) mappingContractRequest.setForeignContractTxHash(foreignContractCreatorTxHash) return this.callAsync<void>('AddContractMapping', mappingContractRequest) } /** * Fetches contract mappings from the DAppChain Gateway. * * @returns An object containing both confirmed & pending contract mappings. */ async listContractMappingsAsync(): Promise<{ confirmed: IAddressMapping[] pending: IAddressMapping[] }> { const response = await this.staticCallAsync<TransferGatewayListContractMappingResponse>( 'ListContractMapping', new TransferGatewayListContractMappingRequest(), new TransferGatewayListContractMappingResponse() ) const confirmed = response.getConfimedMappingsList().map(mapping => ({ from: Address.UnmarshalPB(mapping.getFrom()!), to: Address.UnmarshalPB(mapping.getTo()!) })) const pending = response.getConfimedMappingsList().map(mapping => ({ from: Address.UnmarshalPB(mapping.getFrom()!), to: Address.UnmarshalPB(mapping.getTo()!) })) return { confirmed, pending } } /** * Sends a request to the DAppChain Gateway to begin withdrawal of an ERC721 token from the * current DAppChain account to an Ethereum account. * @param tokenId ERC721 token ID. * @param tokenContract DAppChain address of ERC721 contract. * @param recipient Ethereum address of the account the token should be withdrawn to, if this is * omitted the Gateway will attempt to use the Address Mapper to retrieve the * address of the Ethereum account mapped to the current DAppChain account. * @returns A promise that will be resolved when the DAppChain Gateway has accepted the withdrawal * request. */ withdrawERC721Async(tokenId: BN, tokenContract: Address, recipient?: Address): Promise<void> { const req = new TransferGatewayWithdrawTokenRequest() req.setTokenKind(TransferGatewayTokenKind.ERC721) req.setTokenId(marshalBigUIntPB(tokenId)) req.setTokenContract(tokenContract.MarshalPB()) if (recipient) { req.setRecipient(recipient.MarshalPB()) } return this.callAsync<void>('WithdrawToken', req) } /** * Sends a request to the DAppChain Gateway to begin withdrawal of ERC721X tokens from the current * DAppChain account to an Ethereum account. * @param tokenId ERC721X token ID. * @param amount Amount of tokenId to withdraw. * @param tokenContract DAppChain address of ERC721X contract. * @param recipient Ethereum address of the account the token should be withdrawn to, if this is * omitted the Gateway will attempt to use the Address Mapper to retrieve the * address of the Ethereum account mapped to the current DAppChain account. * @returns A promise that will be resolved when the DAppChain Gateway has accepted the withdrawal * request. */ withdrawERC721XAsync( tokenId: BN, amount: BN, tokenContract: Address, recipient?: Address ): Promise<void> { const req = new TransferGatewayWithdrawTokenRequest() req.setTokenKind(TransferGatewayTokenKind.ERC721X) req.setTokenId(marshalBigUIntPB(tokenId)) req.setTokenAmount(marshalBigUIntPB(amount)) req.setTokenContract(tokenContract.MarshalPB()) if (recipient) { req.setRecipient(recipient.MarshalPB()) } return this.callAsync<void>('WithdrawToken', req) } /** * Sends a request to the DAppChain Gateway to begin withdrawal ERC20 tokens from the current * DAppChain account to an Ethereum account. * @param amount Amount to withdraw. * @param tokenContract DAppChain address of ERC20 contract. * @param recipient Ethereum address of the account the token should be withdrawn to, if this is * omitted the Gateway will attempt to use the Address Mapper to retrieve the * address of the Ethereum account mapped to the current DAppChain account. * @returns A promise that will be resolved when the DAppChain Gateway has accepted the withdrawal * request. */ withdrawERC20Async(amount: BN, tokenContract: Address, recipient?: Address): Promise<void> { const req = new TransferGatewayWithdrawTokenRequest() req.setTokenKind(TransferGatewayTokenKind.ERC20) req.setTokenAmount(marshalBigUIntPB(amount)) req.setTokenContract(tokenContract.MarshalPB()) if (recipient) { req.setRecipient(recipient.MarshalPB()) } return this.callAsync<void>('WithdrawToken', req) } /** * Sends a request to the DAppChain Gateway to begin withdrawal of ETH from the current * DAppChain account to an Ethereum account. * @param amount Amount to withdraw. * @param ethereumGateway Ethereum address of Ethereum Gateway. * @param recipient Ethereum address of the account the token should be withdrawn to, if this is * omitted the Gateway will attempt to use the Address Mapper to retrieve the * address of the Ethereum account mapped to the current DAppChain account. * @returns A promise that will be resolved when the DAppChain Gateway has accepted the withdrawal * request. */ withdrawETHAsync(amount: BN, ethereumGateway: Address, recipient?: Address): Promise<void> { const req = new TransferGatewayWithdrawETHRequest() req.setAmount(marshalBigUIntPB(amount)) req.setMainnetGateway(ethereumGateway.MarshalPB()) if (recipient) { req.setRecipient(recipient.MarshalPB()) } return this.callAsync<void>('WithdrawETH', req) } /** * Sends a request to the DAppChain Gateway to begin withdrawal TRX tokens from the current * DAppChain account to an Tron account. * @param amount Amount to withdraw. * @param tokenContract DAppChain address of Tron coin contract. * @param recipient Tron address of the account in hex string where the token should be withdrawn to, if this is * omitted the Gateway will attempt to use the Address Mapper to retrieve the * address of the Tron account mapped to the current DAppChain account. * @returns A promise that will be resolved when the DAppChain Gateway has accepted the withdrawal * request. */ withdrawTRXAsync(amount: BN, tokenContract: Address, recipient?: Address): Promise<void> { const req = new TransferGatewayWithdrawTokenRequest() req.setTokenKind(TransferGatewayTokenKind.TRX) req.setTokenAmount(marshalBigUIntPB(amount)) req.setTokenContract(tokenContract.MarshalPB()) if (recipient) { req.setRecipient(recipient.MarshalPB()) } return this.callAsync<void>('WithdrawToken', req) } /** * Sends a request to the DAppChain Gateway to begin withdrawal TRC20 tokens from the current * DAppChain account to an Tron account. * @param amount Amount to withdraw. * @param tokenContract DAppChain address of Tron TRC20 contract. * @param recipient Tron address of the account in hex string where the token should be withdrawn to, if this is * omitted the Gateway will attempt to use the Address Mapper to retrieve the * address of the Tron account mapped to the current DAppChain account. * @returns A promise that will be resolved when the DAppChain Gateway has accepted the withdrawal * request. */ withdrawTRC20Async(amount: BN, tokenContract: Address, recipient?: Address): Promise<void> { const req = new TransferGatewayWithdrawTokenRequest() req.setTokenKind(TransferGatewayTokenKind.TRC20) req.setTokenAmount(marshalBigUIntPB(amount)) req.setTokenContract(tokenContract.MarshalPB()) if (recipient) { req.setRecipient(recipient.MarshalPB()) } return this.callAsync<void>('WithdrawToken', req) } /** * Retrieves the current withdrawal receipt (if any) for the given DAppChain account. * Withdrawal receipts are created by calling one of the withdraw methods. * @param owner DAppChain address of a user account. * @returns A promise that will be resolved with the withdrawal receipt, or null if no withdrawal * receipt exists (this indicates there's no withdrawal from the specified account * currently in progress). */ async withdrawalReceiptAsync(owner: Address): Promise<IWithdrawalReceipt | null> { const tgWithdrawReceiptReq = new TransferGatewayWithdrawalReceiptRequest() tgWithdrawReceiptReq.setOwner(owner.MarshalPB()) const result = await this.staticCallAsync( 'WithdrawalReceipt', tgWithdrawReceiptReq, new TransferGatewayWithdrawalReceiptResponse() ) const receipt = result.getReceipt() return receipt ? unmarshalWithdrawalReceipt(receipt) : null } /** * Attempt to transfer tokens that originated from the specified Ethereum contract, and that have * been deposited to the Ethereum Gateway, but haven't yet been received by the depositors on the * DAppChain because of a missing identity or contract mapping. This method can only be called by * the creator of the specified token contract, or the Gateway owner. * * @param tokenContract token contract to reclaim the tokens */ async reclaimContractTokensAsync(tokenContract: Address): Promise<void> { const req = new TransferGatewayReclaimContractTokensRequest() req.setTokenContract(tokenContract.MarshalPB()) return this.callAsync<void>('ReclaimContractTokens', req) } async getUnclaimedTokensAsync(owner: Address): Promise<Array<IUnclaimedToken>> { const req = new TransferGatewayGetUnclaimedTokensRequest() req.setOwner(owner.MarshalPB()) const result = await this.staticCallAsync( 'GetUnclaimedTokens', req, new TransferGatewayGetUnclaimedTokensResponse() ) const unclaimedTokens = result.getUnclaimedTokensList() let tokens: Array<IUnclaimedToken> = [] for (let token of unclaimedTokens) { const tokenKind = token.getTokenKind() let tokenIds: Array<BN> = [] let tokenAmounts: Array<BN> = [] if (tokenKind === TransferGatewayTokenKind.ERC721) { // Set only the tokenId for ERC721 for (let amt of token.getAmountsList()) { tokenIds.push(unmarshalBigUIntPB(amt.getTokenId()!)) } } else if (tokenKind === TransferGatewayTokenKind.ERC721X) { // Set both the tokenId and the tokenAmounts for ERC721x for (let amt of token.getAmountsList()) { tokenIds.push(unmarshalBigUIntPB(amt.getTokenId()!)) tokenAmounts.push(unmarshalBigUIntPB(amt.getTokenAmount()!)) } } else { // Set only amount for all other cases for (let amt of token.getAmountsList()) { tokenAmounts.push(unmarshalBigUIntPB(amt.getTokenAmount()!)) } } tokens.push({ tokenContract: Address.UnmarshalPB(token.getTokenContract()!), tokenKind: tokenKind, tokenAmounts: tokenAmounts, tokenIds: tokenIds }) } return tokens } /** * Attempt to transfer any tokens that the caller may have deposited into the Ethereum Gateway * but hasn't yet received from the DAppChain Gateway because of a missing identity or contract * mapping. * * @param depositors Optional list of DAppChain accounts to reclaim tokens for, when set tokens * will be reclaimed for the specified accounts instead of the caller's account. * NOTE: Only the Gateway owner is authorized to provide a list of accounts. */ async reclaimDepositorTokensAsync(depositors?: Array<Address>): Promise<void> { const req = new TransferGatewayReclaimDepositorTokensRequest() if (depositors && depositors.length > 0) { req.setDepositorsList(depositors.map((address: Address) => address.MarshalPB())) } return this.callAsync<void>('ReclaimDepositorTokens', req) } /** * Retrieves the information stored by the Gateway for the given DAppChain account. * @param owner DAppChain address of a user account. * @returns A promise that will be resolved with the local account info. */ async getLocalAccountInfoAsync(owner: Address): Promise<ILocalAccountInfo> { const req = new TransferGatewayGetLocalAccountInfoRequest() req.setOwner(owner.MarshalPB()) const resp = await this.staticCallAsync( 'GetLocalAccountInfo', req, new TransferGatewayGetLocalAccountInfoResponse() ) const receipt = resp.getWithdrawalReceipt() const amount = resp.getTotalWithdrawalAmount() return { withdrawalReceipt: receipt ? unmarshalWithdrawalReceipt(receipt) : null, totalWithdrawalAmount: amount ? unmarshalBigUIntPB(amount) : new BN(0), lastWithdrawalLimitResetTime: resp.getLastWithdrawalLimitResetTime() } } /** * Looks up the contract mapping for the given contract address. * @param from Contract address. * @returns null if no mapping was found for the given contract, otherwise an object that contains * the address of the contract the `from` contract is mapped to, and the current status of * the mapping (pending or confirmed). */ async getContractMappingAsync(from: Address): Promise<{ to: Address; pending: boolean } | null> { const request = new TransferGatewayGetContractMappingRequest() request.setFrom(from.MarshalPB()) const response = await this.staticCallAsync<TransferGatewayGetContractMappingResponse>( 'GetContractMapping', request, new TransferGatewayGetContractMappingResponse() ) if (!response.getFound()) { return null } return { to: Address.UnmarshalPB(response.getMappedAddress()!), pending: response.getIsPending() } } /** * Retrieves the current transfer gateway state. * @returns A promise that will be resolved with the state info. */ async getStateAsync(): Promise<ITransferGatewayState> { const response = await this.staticCallAsync<TransferGatewayStateResponse>( 'GetState', new TransferGatewayStateRequest(), new TransferGatewayStateResponse() ) const state = response.getState() if (!state) { return { maxTotalDailyWithdrawalAmount: new BN(0), maxPerAccountDailyWithdrawalAmount: new BN(0), lastWithdrawalLimitResetTime: new Date(0), totalWithdrawalAmount: new BN(0) } } const maxTotalDailyWithdrawalAmount = state.getMaxTotalDailyWithdrawalAmount() const maxPerAccountDailyWithdrawalAmount = state.getMaxPerAccountDailyWithdrawalAmount() const lastWithdrawalLimitResetTime = state.getLastWithdrawalLimitResetTime() const totalWithdrawalAmount = state.getTotalWithdrawalAmount() return { maxTotalDailyWithdrawalAmount: maxTotalDailyWithdrawalAmount ? unmarshalBigUIntPB(maxTotalDailyWithdrawalAmount) : new BN(0), maxPerAccountDailyWithdrawalAmount: maxPerAccountDailyWithdrawalAmount ? unmarshalBigUIntPB(maxPerAccountDailyWithdrawalAmount) : new BN(0), lastWithdrawalLimitResetTime: lastWithdrawalLimitResetTime ? new Date(lastWithdrawalLimitResetTime * 1000) : new Date(0), totalWithdrawalAmount: totalWithdrawalAmount ? unmarshalBigUIntPB(totalWithdrawalAmount) : new BN(0) } } } function unmarshalWithdrawalReceipt( receipt: TransferGatewayWithdrawalReceipt ): IWithdrawalReceipt { let tokenId: BN | undefined let tokenAmount: BN | undefined let value: BN const tokenKind = receipt.getTokenKind() switch (tokenKind) { case TransferGatewayTokenKind.ERC721: tokenId = unmarshalBigUIntPB(receipt.getTokenId()!) value = tokenId break case TransferGatewayTokenKind.ERC721X: tokenId = unmarshalBigUIntPB(receipt.getTokenId()!) // fallthrough // tslint:disable-next-line: no-switch-case-fall-through default: tokenAmount = unmarshalBigUIntPB(receipt.getTokenAmount()!) value = tokenAmount break } return { tokenOwner: Address.UnmarshalPB(receipt.getTokenOwner()!), tokenContract: receipt.getTokenContract() ? Address.UnmarshalPB(receipt.getTokenContract()!) : undefined, tokenKind, tokenId, tokenAmount, withdrawalNonce: new BN(receipt.getWithdrawalNonce()!), oracleSignature: receipt.getOracleSignature_asU8(), txHash: receipt.getTxHash_asU8(), txStatus: receipt.getTxStatus(), value } }
the_stack
import archy from "archy"; import * as path from "path"; import * as semver from "semver"; import { SemVer } from "semver"; import * as debug from "../util/debug"; import * as packageUtils from "../util/package"; import resolve from "../util/resolve"; import { SimpleCache } from "../util/SimpleCache"; import { URI } from "../util/URI"; import EyeglassModule, { ModuleSpecifier, DiscoverOptions, isModuleReference } from "./EyeglassModule"; import merge from "lodash.merge"; import * as packageJson from "package-json"; import { IEyeglass } from "../IEyeglass"; import { SassImplementation } from "../util/SassImplementation"; import { Dict, isPresent } from "../util/typescriptUtils"; import { EyeglassConfig } from ".."; import { Config } from "../util/Options"; import heimdall = require("heimdalljs"); import { realpathSync } from "../util/perf"; import eyeglassVersion from "../util/version"; type PackageJson = packageJson.FullVersion; const EYEGLASS_VERSION = eyeglassVersion.semver export const ROOT_NAME = ":root"; const BOUNDARY_VERSIONS = [ new SemVer("1.6.0"), new SemVer(EYEGLASS_VERSION), new SemVer("2.9.9"), new SemVer("3.0.0"), new SemVer("3.9.9"), new SemVer("4.0.0") ]; type ModuleCollection = Dict<Set<EyeglassModule>>; type ModuleMap = Dict<EyeglassModule>; type Dependencies = Exclude<PackageJson["dependencies"], undefined>; const globalModuleCache = new SimpleCache<EyeglassModule>(); const globalModulePackageCache = new SimpleCache<string>(); export function resetGlobalCaches() { globalModuleCache.purge(); globalModulePackageCache.purge(); } interface DependencyVersionIssue { name: string; requested: { module: EyeglassModule; version: string; } resolved: { module: EyeglassModule; version: string; } } interface ModuleBranch { name: string; version: string | undefined; path: string; dependencies: Dict<ModuleBranch> | undefined; } /** * Discovers all of the modules for a given directory * * @constructor * @param {String} dir - the directory to discover modules in * @param {Array} modules - the explicit modules to include * @param {Boolean} useGlobalModuleCache - whether or not to use the global module cache */ export default class EyeglassModules { issues: { dependencies: { versions: Array<DependencyVersionIssue>; missing: Array<string>; }; engine: { missing: Array<EyeglassModule>; incompatible: Array<EyeglassModule>; }; }; cache: { access: SimpleCache<boolean>; compatibility: SimpleCache<boolean>; modules: SimpleCache<EyeglassModule | undefined>; modulePackage: SimpleCache<string | undefined>; }; collection: ModuleMap; list: Array<EyeglassModule>; tree: ModuleBranch; projectName: string; eyeglass: EyeglassModule; config: Config; private _modulePathMap: Dict<EyeglassModule> | undefined; constructor(dir: string, config: EyeglassConfig, modules?: Array<ModuleSpecifier>) { let timer = heimdall.start("eyeglass:modules"); try { this.config = config; let useGlobalModuleCache = config.eyeglass.useGlobalModuleCache; this.issues = { dependencies: { versions: [], missing: [] }, engine: { missing: [], incompatible: [] } }; this.cache = { access: new SimpleCache(), compatibility: new SimpleCache(), modules: useGlobalModuleCache ? globalModuleCache : new SimpleCache<EyeglassModule>(), modulePackage: useGlobalModuleCache ? globalModulePackageCache : new SimpleCache<string>(), }; // find the nearest package.json for the given directory dir = packageUtils.findNearestPackage(path.resolve(dir)); // resolve the current location into a module tree let moduleTree = this.resolveModule(dir, true)!; // if any modules were passed in, add them to the module tree if (modules && modules.length) { let discoverTimer = heimdall.start("eyeglass:modules:discovery"); try { for (let mod of modules) { if (isModuleReference(mod)) { if (moduleTree.hasModulePath(mod.path)) { // If we already have this module in the module tree, skip it. debug.modules(`Eyeglass module ${mod.path} is already in the module tree. Skipping...`); continue; } } let resolvedMod = new EyeglassModule(merge(mod, { isEyeglassModule: true }), this.discoverModules.bind(this)); // If we already have a direct dependency on a module with this name, skip it. if (!moduleTree.dependencies[resolvedMod.name]) { moduleTree.dependencies[resolvedMod.name] = resolvedMod; } else { debug.modules(`Eyeglass module ${resolvedMod.name} is already a dependency. Skipping...`); } } } finally { discoverTimer.stop(); } } let resolutionTimer = heimdall.start("eyeglass:modules:resolution"); try { debug.modules && debug.modules("discovered modules\n\t" + this.getGraph(moduleTree).replace(/\n/g, "\n\t")); // convert the tree into a flat collection of deduped modules let collection = this.dedupeModules(flattenModules(moduleTree)); // expose the collection this.collection = collection; // convert the collection object into a simple array for easy iteration this.list = Object.keys(collection).map((name) => collection[name]!); // prune and expose the tree this.tree = this.pruneModuleTree(moduleTree); // set the current projects name this.projectName = moduleTree.name; // expose a convenience reference to the eyeglass module itself this.eyeglass = this.find("eyeglass")!; // check for any issues we may have encountered this.checkForIssues(); } catch (e) { // typescript needs this catch & throw to convince it that the instance properties are initialized. throw e; } finally { resolutionTimer.stop(); } /* istanbul ignore next - don't test debug */ debug.modules && debug.modules("resolved modules\n\t" + this.getGraph(this.tree).replace(/\n/g, "\n\t")); } catch (e) { // typescript needs this catch & throw to convince it that the instance properties are initialized. throw e; } finally { timer.stop(); } } /** * initializes all of the modules with the given engines * * @param {Eyeglass} eyeglass - the eyeglass instance * @param {Function} sass - the sass engine */ init(eyeglass: IEyeglass, sass: SassImplementation): void { this.list.forEach((mod) => mod.init(eyeglass, sass)); } /** * Checks whether or not a given location has access to a given module * * @param {String} name - the module name to find * @param {String} origin - the location of the originating request * @returns {Object} the module reference if access is granted, null if access is prohibited */ access(name: string, origin: string): EyeglassModule | null { let mod = this.find(name); // if the module exists and we can access the module from the origin if (mod && this.canAccessModule(name, origin)) { return mod; } else { // if not, return null return null; } } /** * Finds a module reference by the module name * * @param {String} name - the module name to find * @returns {Object} the module reference */ find(name: string): EyeglassModule | undefined { return this.getFinalModule(name); } /** * Creates, caches and returns a mapping of filesystem locations to eyeglass * modules. */ get modulePathMap(): Dict<EyeglassModule> { if (this._modulePathMap) { return this._modulePathMap; } else { let names = Object.keys(this.collection); let modulePathMap: Dict<EyeglassModule> = {}; for (let name of names) { let mod = this.collection[name]!; modulePathMap[mod.path] = mod; } this._modulePathMap = modulePathMap; return this._modulePathMap; } } /** * Finds the most specific eyeglass module that contains the given filesystem * location. It does this by walking up the directory structure and looking * to see if it finds the main directory of an eyeglass module. */ findByPath(location: string): EyeglassModule | null { let pathMap = this.modulePathMap; // This is the only filesystem operation: we have to make sure // we're working with real path locations because the module directories // are also only real paths. This means that sass files that are sym-linked // into a subdirectory of an eyeglass module will not resolve against that // module. (Sym-linking an eyeglass module itself is supported.) let parentLocation = realpathSync(location); do { location = parentLocation; let mod = pathMap[location]; if (mod) { return mod; } parentLocation = path.dirname(location); } while (parentLocation != location) return null; } /** * Returns a formatted string of the module hierarchy * * @returns {String} the module hierarchy */ getGraph(tree?: ModuleBranch): string { if (!tree) { tree = this.tree; } let hierarchy = getHierarchy(tree); hierarchy.label = this.getDecoratedRootName(); return archy(hierarchy); } /** * resolves the module and it's dependencies * * @param {String} pkgPath - the path to the modules package.json location * @param {Boolean} isRoot - whether or not it's the root of the project * @returns {Object} the resolved module definition */ private resolveModule(pkgPath: string, isRoot: boolean = false): EyeglassModule | undefined { let cacheKey = `resolveModule~${pkgPath}!${!!isRoot}`; return this.cache.modules.getOrElse(cacheKey, () => { let pkg = packageUtils.getPackage(pkgPath); let isEyeglassMod = EyeglassModule.isEyeglassModule(pkg.data); // if the module is an eyeglass module OR it's the root project if (isEyeglassMod || (pkg.data && isRoot)) { // return a module reference return new EyeglassModule({ isEyeglassModule: isEyeglassMod, path: path.dirname(pkg.path) }, this.discoverModules.bind(this), isRoot); } else { return; } }); } /** * dedupes a collection of modules to a single version * * @this {EyeglassModules} * * @param {Object} module - the collection of modules * @returns {Object} the deduped module collection */ private dedupeModules(modules: ModuleCollection): ModuleMap { let deduped: ModuleMap = {}; for (let name of Object.keys(modules)) { let otherVersions = new Array<EyeglassModule>(); let secondNewestModule: EyeglassModule | undefined; let newestModule: EyeglassModule | undefined; for (let m of modules[name]!) { if (!newestModule) { newestModule = m } else { if (semver.compare(m.semver, newestModule.semver) > 0) { if (secondNewestModule) { otherVersions.push(secondNewestModule); } secondNewestModule = newestModule; newestModule = m; } else { if (secondNewestModule && semver.compare(m.semver, secondNewestModule.semver) > 0) { otherVersions.push(secondNewestModule); secondNewestModule = m; } else if (secondNewestModule) { otherVersions.push(m); } else { secondNewestModule = m; } } } } // In case the app and a dependency have the same name, we discard the app // Because they're not the same thing. if (secondNewestModule && newestModule!.isRoot) { newestModule = secondNewestModule; } else if (secondNewestModule) { otherVersions.push(secondNewestModule); } deduped[name] = newestModule; // check for any version issues this.issues.dependencies.versions.push.apply( this.issues.dependencies.versions, getDependencyVersionIssues(otherVersions, deduped[name]!) ); } return deduped; } /** * checks for any issues in the modules we've discovered * * @this {EyeglassModules} * */ private checkForIssues(): void { this.list.forEach((mod: EyeglassModule) => { // We don't check the app root for issues unless it declares itself to be // an eyeglass module. (because the app doesn't have to be a well-formed // eyeglass module.) if (mod.isRoot && !mod.isEyeglassModule) { return; } // check engine compatibility if (!mod.eyeglass || !mod.eyeglass.needs) { // if `eyeglass.needs` is not present... // add the module to the missing engines list this.issues.engine.missing.push(mod); } else if (!this.isCompatibleWithThisEyeglass(mod.eyeglass.needs)) { // if the current version of eyeglass does not satisfy the need... // add the module to the incompatible engines list this.issues.engine.incompatible.push(mod); } }); } private isCompatibleWithThisEyeglass(needs: string): boolean { let cacheKey = needs; return this.cache.compatibility.getOrElse(cacheKey, () => { let assertCompatSpec = this.config.eyeglass.assertEyeglassCompatibility; // If we don't have a forced compat version just check against the module if (!assertCompatSpec) { return semver.satisfies(EYEGLASS_VERSION, needs); } // We only use the forced compat version if it is functionally higher than // the module's needed version let minModule = semver.minSatisfying(BOUNDARY_VERSIONS, needs); let minCompat = semver.minSatisfying(BOUNDARY_VERSIONS, assertCompatSpec); if (minModule === null || minCompat === null || semver.gt(minModule, minCompat)) { return semver.satisfies(EYEGLASS_VERSION, needs) } else { return semver.satisfies(EYEGLASS_VERSION, `${assertCompatSpec} || ${needs}`) } }); } /** * rewrites the module tree to reflect the deduped modules * * @this {EyeglassModules} * * @param {Object} moduleTree - the tree to prune * @returns {Object} the pruned tree */ private pruneModuleTree(moduleTree: EyeglassModule): ModuleBranch { let finalModule = moduleTree.isEyeglassModule && this.find(moduleTree.name); // normalize the branch let branch: ModuleBranch = { name: finalModule && finalModule.name || moduleTree.name, version: (finalModule && finalModule.version || moduleTree.version), path: finalModule && finalModule.path || moduleTree.path, dependencies: undefined }; // if the tree has dependencies let dependencies = moduleTree.dependencies; if (dependencies) { // copy them into the branch after recursively pruning branch.dependencies = {}; for (let name of Object.keys(dependencies)) { branch.dependencies[name] = this.pruneModuleTree(dependencies[name]!); } } return branch; } /** * resolves the eyeglass module itself * * @returns {Object} the resolved eyeglass module definition */ private getEyeglassSelf(): EyeglassModule { let eyeglassDir = path.resolve(__dirname, "..", ".."); let eyeglassPkg = packageUtils.getPackage(eyeglassDir); let resolvedPkg = resolve(eyeglassPkg.path, eyeglassPkg.path, eyeglassDir); return this.resolveModule(resolvedPkg, false)!; } /** * discovers all the modules for a given set of options * * @param {Object} options - the options to use * @returns {Object} the discovered modules */ private discoverModules(options: DiscoverOptions): Dict<EyeglassModule> | null { let pkg = options.pkg || packageUtils.getPackage(options.dir); let dependencies: Dependencies = {}; if (!(options.isRoot || EyeglassModule.isEyeglassModule(pkg.data))) { return null; } // if there's package.json contents... /* istanbul ignore else - defensive conditional, don't care about else-case */ if (pkg.data) { merge( dependencies, // always include the `dependencies` and `peerDependencies` pkg.data.dependencies, pkg.data.peerDependencies, // only include the `devDependencies` if isRoot options.isRoot && pkg.data.devDependencies ); } // for each dependency... let dependentModules: Dict<EyeglassModule> = Object.keys(dependencies).reduce((modules: Dict<EyeglassModule>, dependency) => { // resolve the package.json let resolvedPkg = this.resolveModulePackage( packageUtils.getPackagePath(dependency), pkg.path, URI.system(options.dir) ); if (!resolvedPkg) { // if it didn't resolve, they likely didn't `npm install` it correctly this.issues.dependencies.missing.push(dependency); } else { // otherwise, set it onto our collection let resolvedModule = this.resolveModule(resolvedPkg); if (resolvedModule) { modules[resolvedModule.name] = resolvedModule; } } return modules; }, {}); // if it's the root... if (options.isRoot) { // ensure eyeglass itself is a direct dependency dependentModules["eyeglass"] = dependentModules["eyeglass"] || this.getEyeglassSelf(); } return Object.keys(dependentModules).length ? dependentModules : null; } /** * resolves the package for a given module * * @see resolve() */ private resolveModulePackage(id: string, parent: string, parentDir: string): string | undefined { let cacheKey = "resolveModulePackage~" + id + "!" + parent + "!" + parentDir; return this.cache.modulePackage.getOrElse(cacheKey, function () { try { return resolve(id, parent, parentDir); } catch (e) { /* istanbul ignore next - don't test debug */ debug.modules && debug.modules( 'failed to resolve module package %s', e ) return; } }); } /** * gets the final module from the collection * * @this {EyeglassModules} * * @param {String} name - the module name to find * @returns {Object} the module reference */ private getFinalModule(name: string): EyeglassModule | undefined { return this.collection[name]; } /** * gets the root name and decorates it * * @this {EyeglassModules} * * @returns {String} the decorated name */ private getDecoratedRootName(): string { return ROOT_NAME + ((this.projectName) ? "(" + this.projectName + ")" : ""); } /** * whether or not a module can be accessed by the origin request * * @this {EyeglassModules} * * @param {String} name - the module name to find * @param {String} origin - the location of the originating request * @returns {Boolean} whether or not access is permitted */ private canAccessModule(name: string, origin: string): boolean { // eyeglass can be imported by anyone, regardless of the dependency tree if (name === "eyeglass") { return true; } let canAccessFrom = (origin: string): boolean => { // find the nearest package for the origin let mod = this.findByPath(origin); if (!mod) { if (this.config.eyeglass.disableStrictDependencyCheck) { return true; } else { throw new Error(`No module found containing '${origin}'.`) } } let modulePath = mod.path; let cacheKey = modulePath + "!" + origin; return this.cache.access.getOrElse(cacheKey, () => { // find all the branches that match the origin let branches = findBranchesByPath(this.tree, modulePath); let canAccess = branches.some(function(branch) { // if the reference is to itself (branch.name) // OR it's an immediate dependency (branch.dependencies[name]) if (branch.name === name || branch.dependencies && branch.dependencies[name]) { return true; } else { return false; } }); // If strict dependency checks are disabled, just return the true. if (!canAccess && this.config.eyeglass.disableStrictDependencyCheck) { debug.warning( "Overriding strict dependency check for %s from %s", name, origin ); return true; } else { /* istanbul ignore next - don't test debug */ debug.importer( "%s can%s be imported from %s", name, (canAccess ? "" : "not"), origin ); return canAccess; } }); }; // check if we can access from the origin... let canAccess = canAccessFrom(origin); // if not... if (!canAccess) { // check for a symlink... let realOrigin = realpathSync(origin); /* istanbul ignore if */ if (realOrigin !== origin) { /* istanbul ignore next */ canAccess = canAccessFrom(realOrigin); } } return canAccess; } } /** * given a set of dependencies, gets the hierarchy nodes * * @param {Object} dependencies - the dependencies * @returns {Object} the corresponding hierarchy nodes (for use in archy) */ function getHierarchyNodes(dependencies: ModuleBranch["dependencies"]): Array<archy.Data> | undefined { if (dependencies) { // for each dependency, recurse and get it's hierarchy return Object.keys(dependencies).map((name) => getHierarchy(dependencies[name]!)); } else { return; } } /** * gets the archy hierarchy for a given branch * * @param {Object} branch - the branch to traverse * @returns {Object} the corresponding archy hierarchy */ function getHierarchy(branch: ModuleBranch): archy.Data { // return an object the confirms to the archy expectations return { // if the branch has a version on it, append it to the label label: branch.name + (branch.version ? "@" + branch.version : ""), nodes: getHierarchyNodes(branch.dependencies) }; } /** * find a branches in a tree with a given path * * @param {Object} tree - the module tree to traverse * @param {String} dir - the path to search for * @returns {Object} the branches of the tree that contain the path */ function findBranchesByPath(mod: ModuleBranch | undefined, dir: string, branches = new Array<ModuleBranch>()): Array<ModuleBranch> { // iterate over the tree if (!mod) { return branches; } if (mod.path === dir) { branches.push(mod); } if (mod.dependencies) { let subModNames = Object.keys(mod.dependencies); for (let subModName of subModNames) { findBranchesByPath(mod.dependencies[subModName], dir, branches); } } return branches; } /** * given a branch of modules, flattens them into a collection * * @param {Object} branch - the module branch * @param {Object} collection - the incoming collection * @returns {Object} the resulting collection */ function flattenModules(branch: EyeglassModule, collection: ModuleCollection = {}): ModuleCollection { // We capture the app root to a special name so we can always find it easily // and so it remains in the collection in case de-duplication against a // dependency would trigger its removal. if (branch.isRoot) { collection[":root"] = new Set([branch]); } // if the branch itself is a module, add it... if (branch.isEyeglassModule || branch.isRoot) { collection[branch.name] = collection[branch.name] || new Set<EyeglassModule>(); collection[branch.name]!.add(branch); } let dependencies = branch.dependencies; if (dependencies) { for (let name of Object.keys(dependencies)) { flattenModules(dependencies[name]!, collection); } } return collection; } /** * given a set of versions, checks if there are any compat issues * * @param {Array<Object>} modules - the various modules to check * @param {String} finalModule - the final module to check against * @returns {Array<Object>} the array of any issues found */ function getDependencyVersionIssues(modules: Array<EyeglassModule>, finalModule: EyeglassModule): Array<DependencyVersionIssue> { return modules.map(function(mod) { let satisfied = semver.satisfies(finalModule.semver.version, "^" + mod.semver); // if the versions are not identical, log it if (mod.version !== finalModule.version) { /* istanbul ignore next - don't test debug */ debug.modules && debug.modules( "asked for %s@%s but using %s@%s which %s a conflict", mod.name, mod.version, finalModule.name, finalModule.version, satisfied ? "is not" : "is", ); } // check that the current module version is satisfied by the finalModule version // if not, push an error object onto the results if (!satisfied) { return { name: mod.name, requested: { module: mod, version: mod.semver.toString(), }, resolved: { module: finalModule, version: finalModule.semver.toString(), } }; } else { return; } }).filter<DependencyVersionIssue>(isPresent); }
the_stack
import { exec as execAsync, execSync } from 'child_process'; import { promisify } from 'util'; // eslint-disable-next-line import/no-extraneous-dependencies import { SecretsManager } from 'aws-sdk'; import { LambdaContext } from '../lib/aws-lambda'; import { CfnRequestEvent, SimpleCustomResource } from '../lib/custom-resource'; import { writeAsciiFile, } from '../lib/filesystem'; import { readCertificateData, Secret, } from '../lib/secrets-manager'; import { IConnectionOptions, IMongoDbConfigureResource, implementsIMongoDbConfigureResource, IX509AuthenticatedUser, } from './types'; const exec = promisify(execAsync); export class MongoDbConfigure extends SimpleCustomResource { protected readonly secretsManagerClient: SecretsManager; constructor(secretsManagerClient: SecretsManager) { super(); this.secretsManagerClient = secretsManagerClient; } /** * @inheritdoc */ /* istanbul ignore next */ // @ts-ignore public validateInput(data: object): boolean { return implementsIMongoDbConfigureResource(data); } /** * @inheritdoc */ // @ts-ignore -- we do not use the physicalId public async doCreate(physicalId: string, resourceProperties: IMongoDbConfigureResource): Promise<object|undefined> { const mongoDbDriver = this.installMongoDbDriver(); const mongoClient = await this.mongoLogin(mongoDbDriver, resourceProperties.Connection); try { if (resourceProperties.PasswordAuthUsers) { const adminDb = mongoClient.db('admin'); for (const userArn of resourceProperties.PasswordAuthUsers) { if (!await this.createPasswordAuthUser(adminDb, userArn)) { // Note: Intentionally not including the data as part of this message. It may contain secrets, and including it will leak those secrets. console.log(`User in '${userArn}' already exists in the MongoDB. No action performed for this user.`); } } } if (resourceProperties.X509AuthUsers) { const externalDb = mongoClient.db('$external'); for (const x509User of resourceProperties.X509AuthUsers) { if (!await this.createX509AuthUser(externalDb, x509User)) { // Note: Intentionally not including the data as part of this message. It may contain secrets, and including it will leak those secrets. console.log(`User in '${x509User.Certificate}' already exists in the MongoDB. No action performed for this user.`); } } } } finally { console.log('Closing Mongo connection'); await mongoClient.close(); } return undefined; } /** * @inheritdoc */ /* istanbul ignore next */ // @ts-ignore public async doDelete(physicalId: string, resourceProperties: IMongoDbConfigureResource): Promise<void> { // Nothing to do -- we don't modify any existing DB contents. return; } /** * Installs the official NodeJS MongoDB driver into /tmp, and returns the module object for it. */ /* istanbul ignore next */ protected installMongoDbDriver(): any { console.log('Installing latest MongoDB Driver for NodeJS from npmjs.org'); // Both HOME and --prefix are needed here because /tmp is the only writable location execSync('HOME=/tmp npm install mongodb@3 --production --no-package-lock --no-save --prefix /tmp'); // eslint-disable-next-line @typescript-eslint/no-require-imports return require('/tmp/node_modules/mongodb'); } /** * Login to MongoDB and return the MongoClient connection object. * @param mongoDbDriver * @param options */ protected async mongoLogin(mongoDbDriver: any, options: IConnectionOptions): Promise<any> { // Get the CA cert. const caData = await this.readCertificateData(options.CaCertificate); await writeAsciiFile('/tmp/ca.crt', caData); // Next, the login credentials const credentials = await this.readLoginCredentials(options.Credentials); // Login to MongoDB const mongoUri = `mongodb://${options.Hostname}:${options.Port}`; console.log(`Connecting to: ${mongoUri}`); // Reference: http://mongodb.github.io/node-mongodb-native/3.5/api/MongoClient.html#.connect return await mongoDbDriver.MongoClient.connect(mongoUri, { tls: true, // Require TLS tlsInsecure: false, // Require server identity validation tlsCAFile: '/tmp/ca.crt', auth: { user: credentials.username, password: credentials.password, }, useUnifiedTopology: true, // We error on connect if not passing this. }); } /** * Retrieve CA certificate data from the Secret with the given ARN. * @param certificateArn */ protected async readCertificateData(certificateArn: string): Promise<string> { return await readCertificateData(certificateArn, this.secretsManagerClient); } /** * Use openssl to retrieve the subject, in RFC2253 format, of the given certificate. * @param certificateData */ protected async retrieveRfc2253Subject(certificateData: string): Promise<string> { await writeAsciiFile('/tmp/client.crt', certificateData); const subject = await exec('openssl x509 -in /tmp/client.crt -noout -subject -nameopt RFC2253'); return subject.stdout.replace(/subject= /, '').trim(); } /** * Retrieve the credentials of the user that we're to login to the DB with. * @param credentialsArn */ protected async readLoginCredentials(credentialsArn: string): Promise<{ [key: string]: string}> { const data = await Secret.fromArn(credentialsArn, this.secretsManagerClient).getValue(); if (Buffer.isBuffer(data) || !data) { throw new Error(`Login credentials, in Secret ${credentialsArn}, for MongoDB must be a JSON encoded string`); } let credentials: { [key: string]: string }; try { credentials = JSON.parse(data); } catch (e) { // Note: Intentionally not including the data as part of this error message. It may contain secrets, and including it will leak those secrets. throw new Error(`Failed to parse JSON in MongoDB login credentials Secret (${credentialsArn}). Please ensure that the Secret contains properly formatted JSON.`); } for (const key of ['username', 'password']) { if (!(key in credentials)) { throw new Error(`Login credentials Secret (${credentialsArn}) is missing: ${key}`); } } return credentials; } /** * Read, from the given Secret, the information for a password-authenticated user to be created * in the DB. * @param userArn */ protected async readPasswordAuthUserInfo(userArn: string): Promise<{[key: string]: string}> { const data = await Secret.fromArn(userArn, this.secretsManagerClient).getValue(); if (Buffer.isBuffer(data) || !data) { throw new Error(`Password-auth user credentials, in Secret ${userArn}, for MongoDB must be a JSON encoded string`); } let userCreds: { [key: string]: string }; try { userCreds = JSON.parse(data); } catch (e) { // Note: Intentionally not including the data as part of this error message. It may contain secrets, and including it will leak those secrets. throw new Error(`Failed to parse JSON for password-auth user Secret (${userArn}). Please ensure that the Secret contains properly formatted JSON.`); } for (const key of ['username', 'password', 'roles']) { if (!(key in userCreds)) { // Note: Intentionally not including the data as part of this error message. It may contain secrets, and including it will leak those secrets. throw new Error(`User credentials Secret '${userArn}' is missing: ${key}`); } } return userCreds; } /** * Query the given DB to determine whether or not there is a user with the given username. * @param db * @param username */ protected async userExists(db: any, username: string): Promise<boolean> { const result = await db.command({ usersInfo: username }); if (result.ok !== 1) { throw new Error(`MongoDB error checking whether user exists \'${username}\' -- ${JSON.stringify(result)}`); } return result.users.length > 0; } /** * Add a user to the database. This must only be called if you know that the user does not * already exist. * @param db * @param credentials */ protected async createUser(db: any, credentials: { [key: string]: any }): Promise<void> { console.log(`Creating user: ${credentials.username}`); const request: { [key: string]: any } = { createUser: credentials.username, roles: credentials.roles, }; // It is an error to include a pwd field with undefined value, and our password // will be absent/undefined for x.509 authenticated users in the $external DB. if (credentials.password) { request.pwd = credentials.password; } const result = await db.command(request); if (result.ok !== 1) { throw new Error(`MongoDB error when adding user \'${credentials.username}\' -- ${JSON.stringify(result)}`); } } /** * Create a user in the admin DB if it does not already exist. If it does exist, then do nothing. * @param db * @param userArn */ protected async createPasswordAuthUser(db: any, userArn: string): Promise<boolean> { const credentials = await this.readPasswordAuthUserInfo(userArn); if (await this.userExists(db, credentials.username)) { return false; } await this.createUser(db, credentials); return true; } /** * Create a user in the $external DB if it does not already exist. If it does exist, then do nothing. * @param db * @param user */ protected async createX509AuthUser(db: any, user: IX509AuthenticatedUser): Promise<boolean> { const userCertData = await this.readCertificateData(user.Certificate); const username = await this.retrieveRfc2253Subject(userCertData); if (await this.userExists(db, username)) { return false; } const credentials: { [key: string]: any } = { username, // Note: No need to check for parse-errors. It's already been vetted twice. Once by the typescript code, and once by the // input verifier of this handler. roles: JSON.parse(user.Roles), }; await this.createUser(db, credentials); return true; } } /** * The lambda handler that is used to log in to MongoDB and perform some configuration actions. */ /* istanbul ignore next */ export async function configureMongo(event: CfnRequestEvent, context: LambdaContext): Promise<string> { const handler = new MongoDbConfigure(new SecretsManager()); return await handler.handler(event, context); }
the_stack
* @fileoverview Configuration options for the TexParser. * * @author v.sorge@mathjax.org (Volker Sorge) */ import {HandlerConfig, FallbackConfig} from './MapHandler.js'; import {StackItemClass} from './StackItem.js'; import {TagsClass} from './Tags.js'; import {userOptions, defaultOptions, OptionList} from '../../util/Options.js'; import {SubHandlers} from './MapHandler.js'; import {FunctionList} from '../../util/FunctionList.js'; import {TeX} from '../tex.js'; import {PrioritizedList} from '../../util/PrioritizedList.js'; import {TagsFactory} from './Tags.js'; export type StackItemConfig = {[kind: string]: StackItemClass}; export type TagsConfig = {[kind: string]: TagsClass}; export type Processor<T> = [T, number]; export type ProtoProcessor<T> = Processor<T> | T; export type ProcessorList = Processor<Function>[]; export type ConfigMethod = (c: ParserConfiguration, j: TeX<any, any, any>) => void; export type InitMethod = (c: ParserConfiguration) => void; export class Configuration { /** * Creates a function priority pair. * @param {ProtoProcessor<T>} func The function or processor. * @param {number} priority The default priority. * @return {Processor} The processor pair. * @template T */ private static makeProcessor<T>(func: ProtoProcessor<T>, priority: number): Processor<T> { return Array.isArray(func) ? func : [func, priority]; } /** * Creates a configuration for a package. * @param {string} name The package name or empty string. * @param {Object} config See `create` method. * @return {Configuration} The newly generated configuration. */ private static _create(name: string, config: {handler?: HandlerConfig, fallback?: FallbackConfig, items?: StackItemConfig, tags?: TagsConfig, options?: OptionList, nodes?: {[key: string]: any}, preprocessors?: ProtoProcessor<Function>[], postprocessors?: ProtoProcessor<Function>[], init?: ProtoProcessor<InitMethod>, config?: ProtoProcessor<ConfigMethod>, priority?: number, parser?: string, } = {}): Configuration { let priority = config.priority || PrioritizedList.DEFAULTPRIORITY; let init = config.init ? this.makeProcessor(config.init, priority) : null; let conf = config.config ? this.makeProcessor(config.config, priority) : null; let preprocessors = (config.preprocessors || []).map( pre => this.makeProcessor(pre, priority)); let postprocessors = (config.postprocessors || []).map( post => this.makeProcessor(post, priority)); let parser = config.parser || 'tex'; return new Configuration( name, config.handler || {}, config.fallback || {}, config.items || {}, config.tags || {}, config.options || {}, config.nodes || {}, preprocessors, postprocessors, init, conf, priority, parser ); } /** * Creator pattern for creating a named package configuration. This will be * administered in the configuration handler and can be retrieved again. * @param {string} name The package name. * @param {Object} config The configuration parameters: * Configuration for the TexParser consist of the following: * * _handler_ configuration mapping handler types to lists of symbol mappings. * * _fallback_ configuration mapping handler types to fallback methods. * * _items_ for the StackItem factory. * * _tags_ mapping tagging configurations to tagging objects. * * _options_ parse options for the packages. * * _nodes_ for the Node factory. * * _preprocessors_ list of functions for preprocessing the LaTeX * string wrt. to given parse options. Can contain a priority. * * _postprocessors_ list of functions for postprocessing the MmlNode * wrt. to given parse options. Can contain a priority. * * _init_ init method and optionally its priority. * * _config_ config method and optionally its priority. * * _priority_ default priority of the configuration. * * _parser_ the name of the parser that this configuration targets. * @return {Configuration} The newly generated configuration. */ public static create(name: string, config: {handler?: HandlerConfig, fallback?: FallbackConfig, items?: StackItemConfig, tags?: TagsConfig, options?: OptionList, nodes?: {[key: string]: any}, preprocessors?: ProtoProcessor<Function>[], postprocessors?: ProtoProcessor<Function>[], init?: ProtoProcessor<InitMethod>, config?: ProtoProcessor<ConfigMethod>, priority?: number, parser?: string, } = {}): Configuration { let configuration = Configuration._create(name, config); ConfigurationHandler.set(name, configuration); return configuration; } /** * Creates an unnamed, ephemeral package configuration. It will not added to * the configuration handler. * @param {Object} config See `create` method. * @return {Configuration} The ephemeral package configuration. */ public static local(config: {handler?: HandlerConfig, fallback?: FallbackConfig, items?: StackItemConfig, tags?: TagsConfig, options?: OptionList, nodes?: {[key: string]: any}, preprocessors?: ProtoProcessor<Function>[], postprocessors?: ProtoProcessor<Function>[], init?: ProtoProcessor<InitMethod>, config?: ProtoProcessor<ConfigMethod>, priority?: number, parser?: string, } = {}): Configuration { return Configuration._create('', config); } /** * @constructor */ private constructor(readonly name: string, readonly handler: HandlerConfig = {}, readonly fallback: FallbackConfig = {}, readonly items: StackItemConfig = {}, readonly tags: TagsConfig = {}, readonly options: OptionList = {}, readonly nodes: {[key: string]: any} = {}, readonly preprocessors: ProcessorList = [], readonly postprocessors: ProcessorList = [], readonly initMethod: Processor<InitMethod> = null, readonly configMethod: Processor<ConfigMethod> = null, public priority: number, readonly parser: string ) { this.handler = Object.assign( {character: [], delimiter: [], macro: [], environment: []}, handler); } /** * The init method. * @type {Function} */ public get init(): InitMethod { return this.initMethod ? this.initMethod[0] : null; } /** * The config method to call once jax is ready. * @type {FunctionList} */ public get config(): ConfigMethod { return this.configMethod ? this.configMethod[0] : null; } } export namespace ConfigurationHandler { let maps: Map<string, Configuration> = new Map(); /** * Adds a new configuration to the handler overwriting old ones. * * @param {string} name The name of the configuration. * @param {Configuration} map The configuration mapping. */ export let set = function(name: string, map: Configuration): void { maps.set(name, map); }; /** * Looks up a configuration. * * @param {string} name The name of the configuration. * @return {Configuration} The configuration with the given name or null. */ export let get = function(name: string): Configuration { return maps.get(name); }; /** * @return {string[]} All configurations in the handler. */ export let keys = function(): IterableIterator<string> { return maps.keys(); }; } /** * Parser configuration combines the configurations of the currently selected * packages. * @constructor */ export class ParserConfiguration { /** * Priority list of init methods. * @type {FunctionList} */ protected initMethod: FunctionList = new FunctionList(); /** * Priority list of init methods to call once jax is ready. * @type {FunctionList} */ protected configMethod: FunctionList = new FunctionList(); /** * An ordered list of cofigurations. * @type {PrioritizedList<Configuration>} */ protected configurations: PrioritizedList<Configuration> = new PrioritizedList(); /** * The list of parsers this configuration targets */ protected parsers: string[] = []; /** * The subhandlers for this configuration. * @type {SubHandlers} */ public handlers: SubHandlers = new SubHandlers(); /** * The collated stack items. * @type {StackItemConfig} */ public items: StackItemConfig = {}; /** * The collated tag configurations. * @type {TagsConfig} */ public tags: TagsConfig = {}; /** * The collated options. * @type {OptionList} */ public options: OptionList = {}; /** * The collated node creators. * @type {{[key: string]: any}} */ public nodes: {[key: string]: any} = {}; /** * @constructor * @param {(string|[string,number])[]} packages A list of packages with * optional priorities. * @parm {string[]} parsers The names of the parsers this package targets */ constructor(packages: (string | [string, number])[], parsers: string[] = ['tex']) { this.parsers = parsers; for (const pkg of packages.slice().reverse()) { this.addPackage(pkg); } for (let {item: config, priority: priority} of this.configurations) { this.append(config, priority); } } /** * Init method for the configuration; */ public init() { this.initMethod.execute(this); } /** * Init method for when the jax is ready * @param {TeX} jax The TeX jax for this configuration */ public config(jax: TeX<any, any, any>) { this.configMethod.execute(this, jax); for (const config of this.configurations) { this.addFilters(jax, config.item); } } /** * Retrieves and adds configuration for a package with priority. * @param {(string | [string, number]} pkg Package with priority. */ public addPackage(pkg: (string | [string, number])) { const name = typeof pkg === 'string' ? pkg : pkg[0]; const conf = this.getPackage(name); conf && this.configurations.add(conf, typeof pkg === 'string' ? conf.priority : pkg[1]); } /** * Adds a configuration after the input jax is created. (Used by \require.) * Sets items, nodes and runs configuration method explicitly. * * @param {string} name The name of the package to add * @param {TeX} jax The TeX jax where it is being registered * @param {OptionList=} options The options for the configuration. */ public add(name: string, jax: TeX<any, any, any>, options: OptionList = {}) { const config = this.getPackage(name); this.append(config); this.configurations.add(config, config.priority); this.init(); const parser = jax.parseOptions; parser.nodeFactory.setCreators(config.nodes); for (const kind of Object.keys(config.items)) { parser.itemFactory.setNodeClass(kind, config.items[kind]); } TagsFactory.addTags(config.tags); defaultOptions(parser.options, config.options); userOptions(parser.options, options); this.addFilters(jax, config); if (config.config) { config.config(this, jax); } } /** * Find a package and check that it is for the targeted parser * * @param {string} name The name of the package to check * @return {Configuration} The configuration for the package */ protected getPackage(name: string): Configuration { const config = ConfigurationHandler.get(name); if (config && this.parsers.indexOf(config.parser) < 0) { throw Error(`Package ${name} doesn't target the proper parser`); } return config; } /** * Appends a configuration to the overall configuration object. * @param {Configuration} config A configuration. * @param {number} priority The configurations optional priority. */ public append(config: Configuration, priority?: number) { priority = priority || config.priority; if (config.initMethod) { this.initMethod.add(config.initMethod[0], config.initMethod[1]); } if (config.configMethod) { this.configMethod.add(config.configMethod[0], config.configMethod[1]); } this.handlers.add(config.handler, config.fallback, priority); Object.assign(this.items, config.items); Object.assign(this.tags, config.tags); defaultOptions(this.options, config.options); Object.assign(this.nodes, config.nodes); } /** * Adds pre- and postprocessor as filters to the jax. * @param {TeX<any} jax The TeX Jax. * @param {Configuration} config The configuration whose processors are added. */ private addFilters(jax: TeX<any, any, any>, config: Configuration) { for (const [pre, priority] of config.preprocessors) { jax.preFilters.add(pre, priority); } for (const [post, priority] of config.postprocessors) { jax.postFilters.add(post, priority); } } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { class UserEntityInstanceDataApi { /** * DynamicsCrm.DevKit UserEntityInstanceDataApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Common end date */ CommonEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Common start date */ CommonStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Due Date */ DueDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Flag due by */ FlagDueBy_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Flag request */ FlagRequest: DevKit.WebApi.StringValue; /** Flag status. */ FlagStatus: DevKit.WebApi.IntegerValue; /** Unique identifier of the source record. */ objectid_account: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_activityfileattachment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_activitymimeattachment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_activityparty: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_annotation: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_appelement: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_applicationuser: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_appmodulecomponentedge: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_appmodulecomponentnode: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_appnotification: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_appointment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_appsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_appusersetting: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_asyncoperation: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_attachment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_attributeimageconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_attributemap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_audit: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_bot: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_botcomponent: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_bulkdeletefailure: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_bulkdeleteoperation: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_businessunitmap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_businessunitnewsarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_calendar: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_calendarrule: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_canvasappextendedmetadata: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_catalog: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_catalogassignment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ channelaccessprofile_userentityinstancedatas: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ channelaccessprofileruleid: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_clientupdate: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_columnmapping: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_connection: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_connectionreference: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_connectionrole: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_connectionroleassociation: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_connectionroleobjecttypecode: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_connector: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_contact: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_conversationtranscript: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_convertrule: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_customapi: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_customapirequestparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_customapiresponseproperty: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_customeraddress: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_customerrelationship: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_datalakefolder: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_datalakefolderpermission: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_datalakeworkspace: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_datalakeworkspacepermission: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_dependency: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_dependencynode: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_devkit_bpfaccount: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_displaystring: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_displaystringmap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_documentindex: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_duplicaterecord: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_duplicaterule: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_duplicaterulecondition: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_email: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_emailhash: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_emailsearch: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_entityanalyticsconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_entityimageconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_entitymap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_environmentvariabledefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_environmentvariablevalue: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_exportsolutionupload: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ externalparty_userentityinstancedatas: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_fax: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_featurecontrolsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_fieldpermission: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_fieldsecurityprofile: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_fileattachment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_filtertemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_flowmachine: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_flowmachinegroup: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_flowsession: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_goal: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_goalrollupquery: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_holidaywrapper: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_import: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_importdata: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_importentitymapping: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_importfile: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_importjob: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_importlog: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_importmap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_internaladdress: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_internalcatalogassignment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_invaliddependency: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_isvconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_kbarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_kbarticlecomment: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_kbarticletemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_keyvaultreference: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_knowledgearticle: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_knowledgebaserecord: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_letter: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_license: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_lookupmapping: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_mailbox: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_mailmergetemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_managedidentity: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_metric: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdynce_botcontent: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aibdataset: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aibfile: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aiconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aimodel: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aiodimage: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aiodlabel: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_aitemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_dataflow: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_federatedarticle: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_helppage: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_kmpersonalizationsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_pminferredtask: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_pmrecording: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_richtextfile: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_slakpi: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_msdyn_tour: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_notification: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_organization: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_organizationdatasyncsubscription: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_organizationsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_organizationstatistic: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_ownermapping: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_package: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_pdfsetting: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_phonecall: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_picklistmapping: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_pluginassembly: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_pluginpackage: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_plugintype: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_plugintypestatistic: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_principalattributeaccessmap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_principalentitymap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_principalobjectaccess: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_principalobjectattributeaccess: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_privilege: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_processsession: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_processstageparameter: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_provisionlanguageforuser: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_publisher: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_publisheraddress: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_queue: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_queueitem: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_recurringappointmentmaster: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_relationshipattribute: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_relationshiprole: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_relationshiprolemap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_report: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_reportcategory: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_reportentity: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_reportlink: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_reportvisibility: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_ribboncommand: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_ribboncontextgroup: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_ribboncustomization: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_ribbondiff: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_ribbonrule: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_ribbontabtocommandmap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_role: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_roletemplate: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_rollupfield: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_routingrule: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_routingruleitem: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_savedquery: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_savedqueryvisualization: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sdkmessage: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sdkmessagefilter: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sdkmessagepair: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sdkmessageprocessingstep: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sdkmessageprocessingstepimage: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sdkmessageprocessingstepsecureconfig: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sdkmessagerequest: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sdkmessagerequestfield: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sdkmessageresponse: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sdkmessageresponsefield: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_serviceendpoint: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_serviceplan: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_serviceplanmapping: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_settingdefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sharepointdocumentlocation: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sharepointsite: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sitemap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_sla: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_socialactivity: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_solution: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_solutioncomponent: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_solutioncomponentbatchconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_solutioncomponentconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_stagesolutionupload: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_statusmap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_stringmap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_subject: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_subscription: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_subscriptionmanuallytrackedobject: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_subscriptionsyncinfo: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_systemuser: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_systemuserauthorizationchangetracker: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_systemuserbusinessunitentitymap: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_task: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_team: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_teammembership: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_teammobileofflineprofilemembership: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_template: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_territory: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_theme: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_timezonedefinition: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_timezonelocalizedname: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_timezonerule: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_transactioncurrency: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_transformationmapping: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_transformationparametermapping: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_unresolvedaddress: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_userentityuisettings: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_userfiscalcalendar: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_userform: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_usermapping: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_usermobileofflineprofilemembership: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_userquery: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_userqueryvisualization: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_virtualentitymetadata: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_webresource: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_webwizard: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_wizardaccessprivilege: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_wizardpage: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_workflow: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_workflowbinary: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_workflowdependency: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_workflowlog: DevKit.WebApi.LookupValue; /** Unique identifier of the source record. */ objectid_workflowwaitsubscription: DevKit.WebApi.LookupValue; /** Object Type Code */ ObjectTypeCode: DevKit.WebApi.IntegerValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns this. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team who owns this object. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns this object. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Personal categories */ PersonalCategories: DevKit.WebApi.StringValue; /** Indicates whether a reminder is set on this object. */ ReminderSet: DevKit.WebApi.BooleanValue; /** Reminder time */ ReminderTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Start Time */ StartTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** To Do item flags. */ ToDoItemFlags: DevKit.WebApi.IntegerValue; /** For internal use only. */ ToDoOrdinalDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** For internal use only. */ ToDoSubOrdinal: DevKit.WebApi.StringValue; /** For internal use only. */ ToDoTitle: DevKit.WebApi.StringValue; /** Unique identifier user entity */ UserEntityInstanceDataId: DevKit.WebApi.GuidValue; VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace UserEntityInstanceData { enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { module, test } from 'qunit'; import { setupApplicationTest } from 'ember-qunit'; import { click, currentURL, settled, visit, waitFor, } from '@ember/test-helpers'; import percySnapshot from '@percy/ember'; import Layer2TestWeb3Strategy from '@cardstack/web-client/utils/web3-strategies/test-layer2'; import { currentNetworkDisplayInfo as c } from '@cardstack/web-client/utils/web3-strategies/network-display-info'; import { setupHubAuthenticationToken } from '../helpers/setup'; import WorkflowPersistence from '@cardstack/web-client/services/workflow-persistence'; import { createDepotSafe, createSafeToken, } from '@cardstack/web-client/utils/test-factories'; function postableSel(milestoneIndex: number, postableIndex: number): string { return `[data-test-milestone="${milestoneIndex}"][data-test-postable="${postableIndex}"]`; } function milestoneCompletedSel(milestoneIndex: number): string { return `[data-test-milestone-completed][data-test-milestone="${milestoneIndex}"]`; } function epiloguePostableSel(postableIndex: number): string { return `[data-test-epilogue][data-test-postable="${postableIndex}"]`; } module('Acceptance | create card space', function (hooks) { setupApplicationTest(hooks); let layer2Service: Layer2TestWeb3Strategy; let layer2AccountAddress = '0x182619c6Ea074C053eF3f1e1eF81Ec8De6Eb6E44'; test('initiating workflow without wallet connections', async function (assert) { let subdomain = ''; // TODO: replace this when other parts of the form are filled out await visit('/card-space'); await click('[data-test-workflow-button="create-space"]'); assert .dom('[data-test-boxel-thread-header]') .containsText('Card Space Creation'); // // Milestone 1 assert.dom(`${postableSel(0, 0)} img`).exists(); assert.dom(postableSel(0, 0)).containsText(`Hello, welcome to Card Space`); // // L2 wallet connection assert .dom(postableSel(0, 1)) .containsText(`connect your ${c.layer2.fullName} wallet`); assert .dom(postableSel(0, 2)) .containsText(`Once you have installed the app`); layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; layer2Service.test__simulateWalletConnectUri(); await waitFor('[data-test-wallet-connect-qr-code]'); layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ createDepotSafe({ owners: [layer2AccountAddress], tokens: [createSafeToken('DAI.CPXD', '0')], }), ]); await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); await settled(); assert .dom('[data-test-layer-2-wallet-summary] [data-test-address-field]') .containsText(layer2AccountAddress); await waitFor(milestoneCompletedSel(0)); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); // // Milestone 2 // // Hub auth assert.dom(postableSel(1, 0)).containsText(`you need to authenticate`); await click(`[data-test-authentication-button]`); layer2Service.test__simulateHubAuthentication('abc123--def456--ghi789'); // // Username step await waitFor(postableSel(1, 3)); assert.dom(postableSel(1, 2)).containsText(`Please pick a username`); assert.dom(postableSel(1, 3)).containsText(`Pick a username`); await click('[data-test-card-space-username-save-button]'); assert.dom('[data-test-card-space-username-is-complete]').exists(); await waitFor(milestoneCompletedSel(1)); assert.dom(milestoneCompletedSel(1)).containsText(`Username picked`); // // Milestone 3 // // Details step await waitFor(postableSel(2, 2)); assert .dom(postableSel(2, 1)) .containsText(`Now it’s time to set up your space.`); assert .dom(postableSel(2, 2)) .containsText(`Fill out the Card Space details`); await click('[data-test-card-space-details-start-button]'); await click('[data-test-card-space-edit-details-save-button]'); assert.dom('[data-test-card-space-details-is-complete]').exists(); await waitFor(milestoneCompletedSel(2)); assert .dom(milestoneCompletedSel(2)) .containsText(`Card Space details saved`); // // Milestone 4 await waitFor(postableSel(3, 1)); assert .dom(postableSel(3, 0)) .containsText(`We have sent your URL reservation badge`); // // Badge assert.dom(postableSel(3, 1)).containsText(`URL reservation`); assert .dom(`${postableSel(3, 1)} [data-test-full-card-space-domain]`) .containsText(`${subdomain}.card.space`); // // Confirm step await waitFor(postableSel(3, 3)); assert .dom(postableSel(3, 2)) .containsText(`You need to pay a small protocol fee`); assert.dom(postableSel(3, 3)).containsText(`Select a payment method`); await click('[data-test-card-space-creation-button]'); assert.dom('[data-test-card-space-creation-is-complete]').exists(); await waitFor(milestoneCompletedSel(3)); assert.dom(postableSel(3, 4)).containsText(`Thank you for your payment`); assert.dom(milestoneCompletedSel(3)).containsText(`Card Space created`); assert .dom( '[data-test-milestone] [data-test-boxel-action-chin] button[data-test-boxel-button]:not([disabled])' ) .doesNotExist(); // // Epilogue await waitFor(epiloguePostableSel(0)); assert .dom(epiloguePostableSel(0)) .containsText(`This is the remaining balance on your prepaid card`); await waitFor(epiloguePostableSel(1)); assert .dom(epiloguePostableSel(1)) .containsText(`Congrats, you have created your Card Space!`); await waitFor(epiloguePostableSel(2)); await percySnapshot(assert); // TODO // await click('[data-test-card-space-next-step="visit-space"]'); }); module('tests with layer 2 already connected', function (hooks) { setupHubAuthenticationToken(hooks); hooks.beforeEach(async function () { layer2Service = this.owner.lookup('service:layer2-network') .strategy as Layer2TestWeb3Strategy; layer2Service.test__simulateRemoteAccountSafes(layer2AccountAddress, [ createDepotSafe({ owners: [layer2AccountAddress], tokens: [createSafeToken('DAI.CPXD', '0')], }), ]); await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]); }); test('initiating workflow with L2 wallet already connected', async function (assert) { await visit('/card-space?flow=create-space'); const flowId = new URL( 'http://domain.test/' + currentURL() ).searchParams.get('flow-id'); assert.equal( currentURL(), `/card-space?flow=create-space&flow-id=${flowId}` ); assert .dom(postableSel(0, 1)) .containsText( `Looks like you’ve already connected your ${c.layer2.fullName} wallet` ); assert .dom( '[data-test-layer-2-wallet-card] [data-test-layer-2-wallet-connected-status]' ) .containsText('Connected'); assert .dom( '[data-test-layer-2-wallet-card] [data-test-wallet-connect-qr-code]' ) .doesNotExist(); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); await waitFor(postableSel(1, 1)); assert.dom(postableSel(1, 0)).containsText(`Please pick a username`); assert.dom(postableSel(1, 1)).containsText(`Pick a username`); let workflowPersistenceService = this.owner.lookup( 'service:workflow-persistence' ) as WorkflowPersistence; let workflowPersistenceId = new URL( 'http://domain.test/' + currentURL() ).searchParams.get('flow-id')!; let persistedData = workflowPersistenceService.getPersistedData( workflowPersistenceId ); assert.ok( persistedData.state.layer2WalletAddress.includes(layer2AccountAddress), 'expected the layer 2 address to have been persisted when the wallet was already connected' ); }); test('disconnecting L2 should cancel the workflow', async function (assert) { await visit('/card-space'); await click('[data-test-workflow-button="create-space"]'); assert .dom('[data-test-layer-2-wallet-card] [data-test-address-field]') .containsText(layer2AccountAddress) .isVisible(); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); layer2Service.test__simulateDisconnectFromWallet(); await settled(); assert .dom('[data-test-postable="0"][data-test-cancelation]') .containsText( `It looks like your ${c.layer2.fullName} wallet got disconnected. If you still want to create a Card Space, please start again by connecting your wallet.` ); assert .dom('[data-test-workflow-default-cancelation-cta="create-space"]') .containsText('Workflow canceled'); // restart workflow await click( '[data-test-workflow-default-cancelation-restart="create-space"]' ); layer2Service.test__simulateWalletConnectUri(); await waitFor('[data-test-wallet-connect-qr-code]'); assert .dom( '[data-test-layer-2-wallet-card] [data-test-wallet-connect-qr-code]' ) .exists(); assert .dom('[data-test-workflow-default-cancelation-cta="create-space"]') .doesNotExist(); }); test('changing L2 account should cancel the workflow', async function (assert) { let differentL2Address = '0x5416C61193C3393B46C2774ac4717C252031c0bE'; await visit('/card-space'); await click('[data-test-workflow-button="create-space"]'); assert .dom('[data-test-layer-2-wallet-card] [data-test-address-field]') .containsText(layer2AccountAddress) .isVisible(); assert .dom(milestoneCompletedSel(0)) .containsText(`${c.layer2.fullName} wallet connected`); await layer2Service.test__simulateAccountsChanged([differentL2Address]); await settled(); assert .dom('[data-test-postable="0"][data-test-cancelation]') .containsText( 'It looks like you changed accounts in the middle of this workflow. If you still want to create a Card Space, please restart the workflow.' ); assert .dom('[data-test-workflow-default-cancelation-cta="create-space"]') .containsText('Workflow canceled'); // restart workflow await click( '[data-test-workflow-default-cancelation-restart="create-space"]' ); assert .dom(postableSel(0, 1)) .containsText( `Looks like you’ve already connected your ${c.layer2.fullName} wallet` ); assert .dom('[data-test-layer-2-wallet-card] [data-test-address-field]') .containsText(differentL2Address) .isVisible(); assert .dom('[data-test-workflow-default-cancelation-cta="create-space"]') .doesNotExist(); }); }); });
the_stack
import DataFrame from '../../src/dataset/data-frame'; import Series from '../../src/dataset/series'; import * as analyzer from '../../src/analyzer'; describe('new DataFrame', () => { test('1D: basic type', () => { const df = new DataFrame(1); expect(df.data).toStrictEqual([1]); expect(df.colData).toStrictEqual([1]); expect(df.axes).toStrictEqual([[0], [0]]); }); test('1D: basic type with extra index and columns', () => { const df = new DataFrame(1, { index: ['kk', 'bb'], columns: [5, 6] }); expect(df.data).toStrictEqual([ [1, 1], [1, 1], ]); expect(df.colData).toStrictEqual([ [1, 1], [1, 1], ]); expect(df.axes).toStrictEqual([ ['kk', 'bb'], [5, 6], ]); }); test('1D: basic type with error extra', () => { expect(() => new DataFrame(1, { columns: [5, 6] })).toThrow('When the length of extra?.columns is larger than 1, extra?.index is required.'); }); test('1D: array', () => { const df = new DataFrame([1, 2, 3]); expect(df.data).toStrictEqual([1, 2, 3]); expect(df.colData).toStrictEqual([1, 2, 3]); expect(df.axes).toStrictEqual([[0, 1, 2], [0]]); }); test('1D: array with extra index and columns', () => { const df = new DataFrame([1, 2, 3], { index: ['b', 'c', 'a'], columns: ['col'] }); expect(df.data).toStrictEqual([1, 2, 3]); expect(df.colData).toStrictEqual([1, 2, 3]); expect(df.axes).toStrictEqual([['b', 'c', 'a'], ['col']]); }); test('1D: object', () => { const df = new DataFrame({ a: 1, b: 2, c: 3 }); expect(df.data).toStrictEqual([1, 2, 3]); expect(df.colData).toStrictEqual([1, 2, 3]); expect(df.axes).toStrictEqual([[0], ['a', 'b', 'c']]); }); test('1D: object with extra index and columns', () => { const df = new DataFrame({ a: 1, b: 2, c: 3 }, { index: ['idx1'], columns: ['c', 'b'] }); expect(df.data).toStrictEqual([3, 2]); expect(df.colData).toStrictEqual([3, 2]); expect(df.axes).toStrictEqual([['idx1'], ['c', 'b']]); }); test('2D: array', () => { const df = new DataFrame([ [1, 4], [2, 5], [3, 6], ]); expect(df.data).toStrictEqual([ [1, 4], [2, 5], [3, 6], ]); expect(df.colData).toStrictEqual([ [1, 2, 3], [4, 5, 6], ]); expect(df.axes).toStrictEqual([ [0, 1, 2], [0, 1], ]); }); test('2D: array with extra index and columns', () => { const df = new DataFrame( [ [1, 4], [2, 5], [3, 6], ], { index: ['a', 'b', 'c'], columns: ['col1', 'col2'], } ); expect(df.data).toStrictEqual([ [1, 4], [2, 5], [3, 6], ]); expect(df.colData).toStrictEqual([ [1, 2, 3], [4, 5, 6], ]); expect(df.axes).toStrictEqual([ ['a', 'b', 'c'], ['col1', 'col2'], ]); }); test('2D: object array', () => { const df = new DataFrame([ { a: 1, b: 4 }, { a: 2, b: 5 }, { a: 3, b: 6 }, ]); expect(df.data).toStrictEqual([ [1, 4], [2, 5], [3, 6], ]); expect(df.colData).toStrictEqual([ [1, 2, 3], [4, 5, 6], ]); expect(df.axes).toStrictEqual([ [0, 1, 2], ['a', 'b'], ]); }); test('2D: object array with extra index and columns', () => { const df = new DataFrame( [ { a: 1, b: 4, c: 7 }, { a: 2, b: 5, c: 8 }, { a: 3, b: 6, c: 9 }, ], { index: ['k', 'm', 'n'], columns: ['c', 'a'] } ); expect(df.data).toStrictEqual([ [7, 1], [8, 2], [9, 3], ]); expect(df.colData).toStrictEqual([ [7, 8, 9], [1, 2, 3], ]); expect(df.axes).toStrictEqual([ ['k', 'm', 'n'], ['c', 'a'], ]); }); test('2D: array object', () => { const df = new DataFrame({ a: [1, 2, 3], b: [4, 5, 6], }); expect(df.data).toStrictEqual([ [1, 4], [2, 5], [3, 6], ]); expect(df.colData).toStrictEqual([ [1, 2, 3], [4, 5, 6], ]); expect(df.axes).toStrictEqual([ [0, 1, 2], ['a', 'b'], ]); }); test('2D: array object with extra index and columns', () => { const df = new DataFrame( { a: [1, 2, 3], b: [4, 5, 6], }, { index: ['p', 'q', 'r'], columns: ['b', 'a'], } ); expect(df.data).toStrictEqual([ [4, 1], [5, 2], [6, 3], ]); expect(df.colData).toStrictEqual([ [4, 5, 6], [1, 2, 3], ]); expect(df.axes).toStrictEqual([ ['p', 'q', 'r'], ['b', 'a'], ]); }); }); describe('DataFrame getter', () => { test('shape', () => { const df = new DataFrame({ a: [1, 2, 3], b: [4, 5, 6], }); expect(df.shape).toStrictEqual([3, 2]); }); }); describe('DataFrame get value functions', () => { const df = new DataFrame([ { a: 1, b: 4, c: 7 }, { a: 2, b: 5, c: 8 }, { a: 3, b: 6, c: 9 }, ]); test('get', () => { /** only rowLoc */ // rowLoc is Axis const rowLocNum = df.get(0); expect(rowLocNum).toStrictEqual( new Series([1, 4, 7], { index: ['a', 'b', 'c'], }) ); // rowLoc is Axis[] const rowLocNumArr = df.get([0, 2]); // DataFrame contains private functions, we can't compare it by serializing to the same string expect(rowLocNumArr.data).toStrictEqual([ [1, 4, 7], [3, 6, 9], ]); expect(rowLocNumArr.axes).toStrictEqual([ [0, 2], ['a', 'b', 'c'], ]); // rowLoc is slice const rowLocStrSlice = df.get('0:2'); expect(rowLocStrSlice.data).toStrictEqual([ [1, 4, 7], [2, 5, 8], ]); expect(rowLocStrSlice.axes).toStrictEqual([ [0, 1], ['a', 'b', 'c'], ]); /** rowLoc and colLoc */ // rowLoc is axis, colLoc is axis const rowLocNumColLocNum = df.get(1, 'c'); expect(rowLocNumColLocNum.data).toStrictEqual([[8]]); expect(rowLocNumColLocNum.axes).toStrictEqual([[1], ['c']]); // rowLoc is axis, colLoc is axis[] const rowLocNumColLocNumArr = df.get(1, ['a', 'c']); expect(rowLocNumColLocNumArr.data).toStrictEqual([[2, 8]]); expect(rowLocNumColLocNumArr.axes).toStrictEqual([[1], ['a', 'c']]); // rowLoc is axis, colLoc is slice const rowLocNumColLocSlice = df.get(1, 'a:c'); expect(rowLocNumColLocSlice.data).toStrictEqual([[2, 5]]); expect(rowLocNumColLocSlice.axes).toStrictEqual([[1], ['a', 'b']]); // rowLoc is axis[], colLoc is axis const rowLocNumArrColLocNum = df.get([1, 2], 'a'); expect(rowLocNumArrColLocNum.data).toStrictEqual([[2], [3]]); expect(rowLocNumArrColLocNum.axes).toStrictEqual([[1, 2], ['a']]); // rowLoc is axis[], colLoc is axis[] const rowLocNumArrColLocNumArr = df.get([1, 2], ['a', 'b']); expect(rowLocNumArrColLocNumArr.data).toStrictEqual([ [2, 5], [3, 6], ]); expect(rowLocNumArrColLocNumArr.axes).toStrictEqual([ [1, 2], ['a', 'b'], ]); // rowLoc is axis[], colLoc is slice const rowLocNumArrColLocSlice = df.get([1, 2], 'b:c'); expect(rowLocNumArrColLocSlice.data).toStrictEqual([[5], [6]]); expect(rowLocNumArrColLocSlice.axes).toStrictEqual([[1, 2], ['b']]); // rowLoc is slice, colLoc is axis const rowLocSliceColLocNum = df.get('0:2', 'b'); expect(rowLocSliceColLocNum.data).toStrictEqual([[4], [5]]); expect(rowLocSliceColLocNum.axes).toStrictEqual([[0, 1], ['b']]); // rowLoc is slice, colLoc is axis[] const rowLocSliceColLocNumArr = df.get('0:2', ['b', 'c']); expect(rowLocSliceColLocNumArr.data).toStrictEqual([ [4, 7], [5, 8], ]); expect(rowLocSliceColLocNumArr.axes).toStrictEqual([ [0, 1], ['b', 'c'], ]); // rowLoc is slice, colLoc is slice const rowLocSliceColLocSlice = df.get('0:2', 'b:c'); expect(rowLocSliceColLocSlice.data).toStrictEqual([[4], [5]]); expect(rowLocSliceColLocSlice.axes).toStrictEqual([[0, 1], ['b']]); }); test('getByIntegerIndex', () => { /** only rowLoc */ // rowLoc is int const rowLocInt = df.getByIntegerIndex(0); expect(rowLocInt).toStrictEqual( new Series([1, 4, 7], { index: ['a', 'b', 'c'], }) ); // rowLoc is int[] const rowLocIntArr = df.getByIntegerIndex([0, 2]); // DataFrame contains private functions, we can't compare it by serializing to the same string expect(rowLocIntArr.data).toStrictEqual([ [1, 4, 7], [3, 6, 9], ]); expect(rowLocIntArr.axes).toStrictEqual([ [0, 2], ['a', 'b', 'c'], ]); // rowLoc is slice const rowLocStrSlice = df.getByIntegerIndex('0:2'); expect(rowLocStrSlice.data).toStrictEqual([ [1, 4, 7], [2, 5, 8], ]); expect(rowLocStrSlice.axes).toStrictEqual([ [0, 1], ['a', 'b', 'c'], ]); /** rowLoc and colLoc */ // rowLoc is int, colLoc is int const rowLocIntColLocInt = df.getByIntegerIndex(1, 2); expect(rowLocIntColLocInt.data).toStrictEqual([[8]]); expect(rowLocIntColLocInt.axes).toStrictEqual([[1], ['c']]); // rowLoc is int, colLoc is int[] const rowLocIntColLocIntArr = df.getByIntegerIndex(1, [0, 2]); expect(rowLocIntColLocIntArr.data).toStrictEqual([[2, 8]]); expect(rowLocIntColLocIntArr.axes).toStrictEqual([[1], ['a', 'c']]); // rowLoc is int, colLoc is slice const rowLocIntColLocSlice = df.getByIntegerIndex(1, '0:2'); expect(rowLocIntColLocSlice.data).toStrictEqual([[2, 5]]); expect(rowLocIntColLocSlice.axes).toStrictEqual([[1], ['a', 'b']]); // rowLoc is int[], colLoc is int const rowLocIntArrColLocInt = df.getByIntegerIndex([1, 2], 0); expect(rowLocIntArrColLocInt.data).toStrictEqual([[2], [3]]); expect(rowLocIntArrColLocInt.axes).toStrictEqual([[1, 2], ['a']]); // rowLoc is int[], colLoc is int[] const rowLocIntArrColLocIntArr = df.getByIntegerIndex([1, 2], [0, 1]); expect(rowLocIntArrColLocIntArr.data).toStrictEqual([ [2, 5], [3, 6], ]); expect(rowLocIntArrColLocIntArr.axes).toStrictEqual([ [1, 2], ['a', 'b'], ]); // rowLoc is int[], colLoc is slice const rowLocIntArrColLocSlice = df.getByIntegerIndex([1, 2], '1:2'); expect(rowLocIntArrColLocSlice.data).toStrictEqual([[5], [6]]); expect(rowLocIntArrColLocSlice.axes).toStrictEqual([[1, 2], ['b']]); // rowLoc is slice, colLoc is int const rowLocSliceColLocInt = df.getByIntegerIndex('0:2', 1); expect(rowLocSliceColLocInt.data).toStrictEqual([[4], [5]]); expect(rowLocSliceColLocInt.axes).toStrictEqual([[0, 1], ['b']]); // rowLoc is slice, colLoc is int[] const rowLocSliceColLocIntArr = df.getByIntegerIndex('0:2', [1, 2]); expect(rowLocSliceColLocIntArr.data).toStrictEqual([ [4, 7], [5, 8], ]); expect(rowLocSliceColLocIntArr.axes).toStrictEqual([ [0, 1], ['b', 'c'], ]); // rowLoc is slice, colLoc is slice const rowLocSliceColLocSlice = df.getByIntegerIndex('0:2', '1:2'); expect(rowLocSliceColLocSlice.data).toStrictEqual([[4], [5]]); expect(rowLocSliceColLocSlice.axes).toStrictEqual([[0, 1], ['b']]); }); test('getByColumn', () => { const getA = df.getByColumn('a'); expect(getA).toStrictEqual(new Series([1, 2, 3], { index: [0, 1, 2] })); }); }); describe('DataFrame info', () => { test('2D: object array', () => { const df = new DataFrame( [ { a: 1, b: 4, c: 7 }, { a: 2, b: 5, c: 8 }, { a: 3, b: 6, c: 9 }, ], { columns: ['a', 'c'] } ); const infos = df.info(); const info = infos[0] as analyzer.NumberFieldInfo & { name: String }; expect(info.count).toBe(3); expect(info.distinct).toBe(3); expect(info.type).toBe('integer'); expect(info.recommendation).toBe('integer'); expect(info.missing).toBe(0); expect(info.samples).toStrictEqual([1, 2, 3]); expect(info.valueMap).toStrictEqual({ '1': 1, '2': 1, '3': 1 }); expect(info.minimum).toBe(1); expect(info.maximum).toBe(3); expect(info.mean).toBe(2); expect(info.percentile5).toBe(1); expect(info.percentile25).toBe(1); expect(info.percentile50).toBe(2); expect(info.percentile75).toBe(3); expect(info.percentile95).toBe(3); expect(info.sum).toBe(6); expect(info.variance).toBe(0.6666666666666666); expect(info.standardDeviation).toBe(0.816496580927726); expect(info.zeros).toBe(0); expect(info.levelOfMeasurements).toStrictEqual(['Interval', 'Discrete']); expect(info.name).toBe('a'); }); });
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { DiagramElement } from '../../../src/diagram/core/elements/diagram-element'; import { Container } from '../../../src/diagram/core/containers/container'; import { DiagramModel } from '../../../src/diagram/index'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; describe('Diagram Control', () => { describe('Simple canvas panel without children', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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; } ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let container: Container = new Container(); container.pivot = { x: 0, y: 0 }; container.offsetX = 200; container.offsetY = 100; container.width = 200; container.height = 200; container.style = { fill: 'red' }; diagram = new Diagram({ width: 1000, height: 600, basicElements: [container] } as DiagramModel); diagram.appendTo('#diagram'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking container without chidlren', (done: Function) => { expect(diagram.basicElements[0].actualSize.width == 200 && diagram.basicElements[0].actualSize.height == 200).toBe(true); done(); }); }); describe('Simple container with two child', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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; } ele = createElement('div', { id: 'diagram1' }); document.body.appendChild(ele); let container: Container = new Container(); container.style = { fill: 'transparent' }; let element: DiagramElement = new DiagramElement(); element.width = 100; element.height = 100; element.offsetX = 200; element.offsetY = 100; element.style.strokeWidth = 1; element.style = { fill: 'red' }; let element1: DiagramElement = new DiagramElement(); element1.width = 100; element1.height = 100; element1.offsetX = 400; element1.offsetY = 100; element1.style = { fill: 'yellow' }; container.children = [element, element1]; diagram = new Diagram({ width: 600, height: 300, basicElements: [container] } as DiagramModel); diagram.appendTo('#diagram1'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking before, after, Simple container with two child', (done: Function) => { let failure: boolean = false; let container: Container = new Container(); for (let i: number = 0; i < diagram.basicElements.length; i++) { let container: DiagramElement; container = diagram.basicElements[i]; if (container instanceof Container) { if (container.actualSize.width === 300 && container.actualSize.height === 100) { failure = true; } if (container.offsetX === 300 && container.offsetY === 100) { failure = true; } if (container.hasChildren()) { for (let child of container.children) { if (child.rotateAngle === container.parentTransform) { failure = true; } else { failure = false; } } } } } expect(failure).toBe(true); done(); }); }); describe('Simple container with two child and one rotated child', () => { let diagram: Diagram; let ele: HTMLElement; let container: Container; let element: DiagramElement; let element1: DiagramElement; beforeAll((): void => { 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; } ele = createElement('div', { id: 'diagram2' }); document.body.appendChild(ele); let container: Container = new Container(); container.style = { fill: 'transparent' }; element = new DiagramElement(); element.width = 100; element.height = 200; element.offsetX = 200; element.offsetY = 100; element.style.strokeWidth = 1; element.rotateAngle = 120; element.style = { fill: 'red' }; let element1: DiagramElement = new DiagramElement(); element1.width = 100; element1.height = 100; element1.offsetX = 400; element1.offsetY = 100; element1.style = { fill: 'orange' }; container.children = [element, element1]; diagram = new Diagram({ width: 600, height: 300, basicElements: [container] } as DiagramModel); diagram.appendTo('#diagram2'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking before, after, Simple container with two child and one rotated child', (done: Function) => { let failure: boolean = false; let container: Container; let element: DiagramElement; for (let i: number = 0; i < diagram.basicElements.length; i++) { let container: DiagramElement; container = diagram.basicElements[i]; if (container instanceof Container) { if (container.actualSize.width === 361.605 && container.actualSize.height === 186.60000000000002) { failure = true; } if (container.offsetX === 269.1975 && container.offsetY === 100.00000000000001) { failure = true; } if (container.hasChildren()) { for (let child of container.children) { if (child.rotateAngle === container.parentTransform) { failure = true; } else { failure = false; } } } } } expect(failure).toBe(true); done(); }); }); describe('Simple container with rotateangle', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll((): void => { 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; } ele = createElement('div', { id: 'diagram3' }); document.body.appendChild(ele); let container: Container = new Container(); container.style = { fill: 'transparent' }; container.rotateAngle = 120; let element: DiagramElement = new DiagramElement(); element.width = 100; element.height = 200; element.offsetX = 400; element.offsetY = 200; element.style.strokeWidth = 1; element.style = { fill: 'red' }; let element1: DiagramElement = new DiagramElement(); element1.width = 100; element1.height = 100; element1.offsetX = 700; element1.offsetY = 500; element1.style = { fill: 'yellow' }; container.children = [element, element1]; diagram = new Diagram({ width: 1000, height: 700, basicElements: [container] } as DiagramModel); diagram.appendTo('#diagram3'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking before, after, Simple container with rotation and rotated child', (done: Function) => { let failure: boolean = false; let container: Container; let element: DiagramElement; for (let i: number = 0; i < diagram.basicElements.length; i++) { let container: DiagramElement; container = diagram.basicElements[i]; if (container instanceof Container) { if (container.actualSize.width === 400 && container.actualSize.height === 450) { failure = true; } if (container.offsetX === 550 && container.offsetY === 325) { failure = true; } if (container.hasChildren()) { for (let child of container.children) { if (container.parentTransform === child.rotateAngle) { failure = true; } else { failure = false; } } } } } expect(failure).toBe(true); done(); }); }); describe('Simple container with rotateangle and rotatedchild', () => { let diagram: Diagram; let ele: HTMLElement; let container: Container; beforeAll((): void => { 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; } ele = createElement('div', { id: 'diagram4' }); document.body.appendChild(ele); let container: Container = new Container(); container.style = { fill: 'transparent' }; container.rotateAngle = 120; let element: DiagramElement = new DiagramElement(); element.width = 100; element.height = 300; element.offsetX = 200; element.offsetY = 250; element.rotateAngle = 120; element.style.strokeWidth = 1; element.style = { fill: 'orange' }; let element1: DiagramElement = new DiagramElement(); element1.width = 100; element1.height = 100; element1.offsetX = 400; element1.offsetY = 250; element1.rotateAngle = 220; element1.style = { fill: 'yellow' }; container.children = [element, element1]; diagram = new Diagram({ width: '600px', height: '500px', basicElements: [container] } as DiagramModel); diagram.appendTo('#diagram4'); }); afterAll((): void => { diagram.destroy(); ele.remove(); }); it('Checking before, after, Simple container with rotation and rotated child', (done: Function) => { let failure: boolean = false; let container: Container; let element: DiagramElement; for (let i: number = 0; i < diagram.basicElements.length; i++) { let container: DiagramElement; container = diagram.basicElements[i]; if (container instanceof Container) { if (container.actualSize.width === 425.345 && container.actualSize.height === 236.59999999999997 ) { failure = true; } if (container.offsetX === 257.76750000000004 && container.offsetY === 249.99999999999997) { failure = true; } if (container.hasChildren()) { for (let child of container.children) { if (container.parentTransform === child.rotateAngle) { failure = true; } else { failure = false; } } } } } if (failure) { done(); } else { //workaround done(); } }); 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 { AfterViewInit, ApplicationRef, ChangeDetectorRef, Component, ComponentFactoryResolver, ComponentRef, Directive, EventEmitter, Inject, Injector, Input, OnChanges, OnDestroy, Output, SimpleChanges, TemplateRef, Type, ViewChild, ViewContainerRef } from '@angular/core'; import { ComponentPortal, DomPortalHost, PortalHost } from '@angular/cdk/portal'; import { WindowComponent } from '../window/window.component'; import { WindowRegistry } from '../window/window-state'; import { RenderComponentDirective } from '../core/render-component.directive'; import { ELECTRON_WINDOW, IN_DIALOG } from '../app/token'; import { Subscription } from 'rxjs'; import { DOCUMENT } from '@angular/common'; import { DuiDialog } from '../dialog/dialog'; import { Electron } from '../../core/utils'; import { detectChangesNextFrame } from '../app'; function PopupCenter(url: string, title: string, w: number, h: number): Window { let top = window.screenTop + (window.outerHeight / 2) - w / 2; top = top > 0 ? top : 0; let left = window.screenLeft + (window.outerWidth / 2) - w / 2; left = left > 0 ? left : 0; const newWindow: Window = window.open(url, title, 'width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)!; return newWindow; } @Component({ template: ` <ng-container *ngIf="component" #renderComponentDirective [renderComponent]="component" [renderComponentInputs]="componentInputs" > </ng-container> <ng-container *ngIf="content" [ngTemplateOutlet]="content"></ng-container> <ng-container *ngIf="container"> <ng-container [ngTemplateOutlet]="container"></ng-container> </ng-container> <ng-container *ngIf="!container"> <ng-content></ng-content> </ng-container> `, host: { '[attr.tabindex]': '1' } }) export class ExternalDialogWrapperComponent { @Input() component?: Type<any>; @Input() componentInputs: { [name: string]: any } = {}; actions?: TemplateRef<any> | undefined; container?: TemplateRef<any> | undefined; content?: TemplateRef<any> | undefined; @ViewChild(RenderComponentDirective, { static: false }) renderComponentDirective?: RenderComponentDirective; constructor( protected cd: ChangeDetectorRef, public injector: Injector, @Inject(ELECTRON_WINDOW) electron: any, ) { } public setDialogContainer(container: TemplateRef<any> | undefined) { this.container = container; this.cd.detectChanges(); } } @Component({ selector: 'dui-external-dialog', template: ` <ng-template #template> <ng-content></ng-content> </ng-template> `, }) export class ExternalWindowComponent implements AfterViewInit, OnDestroy, OnChanges { private portalHost?: PortalHost; @Input() alwaysRaised: boolean = false; @Input() visible: boolean = true; @Output() visibleChange = new EventEmitter<boolean>(); @Output() closed = new EventEmitter<void>(); @Input() component?: Type<any>; @Input() componentInputs: { [name: string]: any } = {}; public wrapperComponentRef?: ComponentRef<ExternalDialogWrapperComponent>; @ViewChild('template', { static: false }) template?: TemplateRef<any>; externalWindow?: Window; container?: TemplateRef<any> | undefined; observerStyles?: MutationObserver; observerClass?: MutationObserver; parentFocusSub?: Subscription; electronWindow?: any; parentWindow?: WindowComponent; constructor( protected componentFactoryResolver: ComponentFactoryResolver, protected applicationRef: ApplicationRef, protected injector: Injector, protected dialog: DuiDialog, protected registry: WindowRegistry, protected cd: ChangeDetectorRef, protected viewContainerRef: ViewContainerRef, ) { } ngOnChanges(changes: SimpleChanges): void { if (this.visible) { this.show(); } else { this.close(); } } public setDialogContainer(container: TemplateRef<any> | undefined) { this.container = container; if (this.wrapperComponentRef) { this.wrapperComponentRef.instance.setDialogContainer(container); } } public show() { if (this.externalWindow) { this.electronWindow.focus(); return; } this.externalWindow = PopupCenter('', '', 300, 300); if (!this.externalWindow) { this.dialog.alert('Error', 'Could not open window.'); return; } this.externalWindow.onunload = () => { this.close(); }; const cloned = new Map<Node, Node>(); for (let i = 0; i < window.document.styleSheets.length; i++) { const style = window.document.styleSheets[i]; if (!style.ownerNode) continue; const clone: Node = style.ownerNode.cloneNode(true); cloned.set(style.ownerNode, clone); this.externalWindow!.document.head!.appendChild(clone); } this.observerStyles = new MutationObserver((mutations: MutationRecord[]) => { for (const mutation of mutations) { for (let i = 0; i < mutation.addedNodes.length; i++) { const node = mutation.addedNodes[i]; if (!cloned.has(node)) { const clone: Node = node.cloneNode(true); cloned.set(node, clone); this.externalWindow!.document.head!.appendChild(clone); } } for (let i = 0; i < mutation.removedNodes.length; i++) { const node = mutation.removedNodes[i]; if (cloned.has(node)) { const clone = cloned.get(node)!; clone.parentNode!.removeChild(clone); cloned.delete(node); } } } }); this.observerStyles.observe(window.document.head!, { childList: true, }); const copyBodyClass = () => { if (this.externalWindow) { this.externalWindow.document.body.className = window.document.body.className; } }; this.observerClass = new MutationObserver((mutations: MutationRecord[]) => { copyBodyClass(); }); this.observerClass.observe(window.document.body, { attributeFilter: ['class'] }); const document = this.externalWindow!.document; copyBodyClass(); this.electronWindow = Electron.isAvailable() ? Electron.getRemote().BrowserWindow.getAllWindows()[0] : undefined; this.parentWindow = this.registry.getOuterActiveWindow(); if (this.parentWindow && this.alwaysRaised) { this.parentWindow.windowState.disableInputs.next(true); if (this.parentWindow.electronWindow) { this.electronWindow.setParentWindow(this.parentWindow.electronWindow); } } window.addEventListener('beforeunload', () => { this.beforeUnload(); }); this.portalHost = new DomPortalHost( document.body, this.componentFactoryResolver, this.applicationRef, this.injector ); document.addEventListener('click', () => detectChangesNextFrame()); document.addEventListener('focus', () => detectChangesNextFrame()); document.addEventListener('blur', () => detectChangesNextFrame()); document.addEventListener('keydown', () => detectChangesNextFrame()); document.addEventListener('keyup', () => detectChangesNextFrame()); document.addEventListener('keypress', () => detectChangesNextFrame()); document.addEventListener('mousedown', () => detectChangesNextFrame()); //todo, add beforeclose event and call beforeUnload() to make sure all dialogs are closed when page is reloaded const injector = Injector.create({ parent: this.injector, providers: [ { provide: ExternalWindowComponent, useValue: this }, { provide: ELECTRON_WINDOW, useValue: this.electronWindow }, { provide: IN_DIALOG, useValue: false }, { provide: DOCUMENT, useValue: this.externalWindow!.document }, ], }); const portal = new ComponentPortal(ExternalDialogWrapperComponent, this.viewContainerRef, injector); this.wrapperComponentRef = this.portalHost.attach(portal); this.wrapperComponentRef!.instance.component = this.component!; this.wrapperComponentRef!.instance.componentInputs = this.componentInputs; this.wrapperComponentRef!.instance.content = this.template!; if (this.container) { this.wrapperComponentRef!.instance.setDialogContainer(this.container); } this.visible = true; this.visibleChange.emit(true); this.wrapperComponentRef!.changeDetectorRef.detectChanges(); this.wrapperComponentRef!.location.nativeElement.focus(); this.cd.detectChanges(); } beforeUnload() { if (this.externalWindow) { if (this.portalHost) { this.portalHost.detach(); this.portalHost.dispose(); delete this.portalHost; } this.closed.emit(); if (this.parentFocusSub) this.parentFocusSub.unsubscribe(); if (this.parentWindow && this.alwaysRaised) { this.parentWindow.windowState.disableInputs.next(false); } if (this.externalWindow) { this.externalWindow!.close(); } delete this.externalWindow; this.observerStyles!.disconnect(); this.observerClass!.disconnect(); } } ngAfterViewInit() { } public close() { this.visible = false; this.visibleChange.emit(false); this.beforeUnload(); requestAnimationFrame(() => { this.applicationRef.tick(); }); } ngOnDestroy(): void { this.beforeUnload(); } } /** * This directive is necessary if you want to load and render the dialog content * only when opening the dialog. Without it it is immediately render, which can cause * performance and injection issues. */ @Directive({ 'selector': '[externalDialogContainer]', }) export class ExternalDialogDirective { constructor(protected dialog: ExternalWindowComponent, public template: TemplateRef<any>) { this.dialog.setDialogContainer(this.template); } }
the_stack
import * as bSemver from 'balena-semver'; import once = require('lodash/once'); import { isNotFoundResponse, onlyIf, treatAsMissingApplication, mergePineOptionsTyped, } from '../util'; import type { BalenaRequestStreamResult } from 'balena-request'; import type { Dictionary, ResolvableReturnType } from '../../typings/utils'; import type { ResourceTagBase, ApplicationTag, Release } from '../types/models'; import type { InjectedDependenciesParam, InjectedOptionsParam, PineOptions, } from '..'; import { getAuthDependentMemoize } from '../util/cache'; import { toWritable } from '../util/types'; const RELEASE_POLICY_TAG_NAME = 'release-policy'; const ESR_NEXT_TAG_NAME = 'esr-next'; const ESR_CURRENT_TAG_NAME = 'esr-current'; const ESR_SUNSET_TAG_NAME = 'esr-sunset'; const VARIANT_TAG_NAME = 'variant'; const VERSION_TAG_NAME = 'version'; const BASED_ON_VERSION_TAG_NAME = 'meta-balena-base'; export enum OsTypes { DEFAULT = 'default', ESR = 'esr', } // Do not change the enum key names b/c they need to // match with the release_tag values. export enum OsVariant { production = 'prod', development = 'dev', } export type OsLines = 'next' | 'current' | 'sunset' | 'outdated' | undefined; const releaseSelectedFields = toWritable([ 'id', 'known_issue_list', 'raw_version', ] as const); export interface OsVersion extends Pick<Release, typeof releaseSelectedFields[number]> { /** @deprecated use OsVersion.raw_version. */ rawVersion: string; strippedVersion: string; basedOnVersion?: string; osType: string; line?: OsLines; variant?: string; /** @deprecated */ formattedVersion: string; /** @deprecated */ isRecommended?: boolean; } export interface OsVersionsByDeviceType { [deviceTypeSlug: string]: OsVersion[]; } export interface ImgConfigOptions { network?: 'ethernet' | 'wifi'; appUpdatePollInterval?: number; provisioningKeyName?: string; provisioningKeyExpiryDate?: string; wifiKey?: string; wifiSsid?: string; ip?: string; gateway?: string; netmask?: string; deviceType?: string; version: string; developmentMode?: boolean; } export interface OsUpdateVersions { versions: string[]; recommended: string | undefined; current: string | undefined; } const sortVersions = (a: OsVersion, b: OsVersion) => { return bSemver.rcompare(a.raw_version, b.raw_version); }; /** * device/os architectures that show in the keys are also able to * run app containers compiled for the architectures in the values * @private */ const archCompatibilityMap: Partial<Dictionary<string[]>> = { aarch64: ['armv7hf', 'rpi'], armv7hf: ['rpi'], }; const getOsModel = function ( deps: InjectedDependenciesParam, opts: InjectedOptionsParam, ) { const { pine, request, pubsub } = deps; const { apiUrl, isBrowser } = opts; const applicationModel = once(() => (require('./application') as typeof import('./application')).default( deps, opts, ), ); const deviceTypeModel = once(() => (require('./device-type') as typeof import('./device-type')).default(deps), ); const hupActionHelper = once( () => ( require('../util/device-actions/os-update/utils') as typeof import('../util/device-actions/os-update/utils') ).hupActionHelper, ); const authDependentMemoizer = getAuthDependentMemoize(pubsub); const tagsToDictionary = ( tags: Array<Pick<ResourceTagBase, 'tag_key' | 'value'>>, ): Dictionary<string> => { const result: Dictionary<string> = {}; for (const { tag_key, value } of tags) { result[tag_key] = value; } return result; }; type HostAppTagSet = ReturnType<typeof getOsAppTags>; const getOsAppTags = ( applicationTags: Array<Pick<ApplicationTag, 'tag_key' | 'value'>>, ) => { const tagMap = tagsToDictionary(applicationTags); return { osType: tagMap[RELEASE_POLICY_TAG_NAME] ?? OsTypes.DEFAULT, nextLineVersionRange: tagMap[ESR_NEXT_TAG_NAME] ?? '', currentLineVersionRange: tagMap[ESR_CURRENT_TAG_NAME] ?? '', sunsetLineVersionRange: tagMap[ESR_SUNSET_TAG_NAME] ?? '', }; }; const getOsVersionReleaseLine = (version: string, appTags: HostAppTagSet) => { // All patches belong to the same line. if (bSemver.satisfies(version, `^${appTags.nextLineVersionRange}`)) { return 'next'; } if (bSemver.satisfies(version, `^${appTags.currentLineVersionRange}`)) { return 'current'; } if (bSemver.satisfies(version, `^${appTags.sunsetLineVersionRange}`)) { return 'sunset'; } if (appTags.osType?.toLowerCase() === OsTypes.ESR) { return 'outdated'; } }; type HostAppInfo = ResolvableReturnType<typeof _getOsVersions>[number]; const _getOsVersions = async ( deviceTypes: string[], options?: PineOptions<Release>, ) => { return await pine.get({ resource: 'application', options: { $select: 'is_for__device_type', $expand: { application_tag: { $select: ['tag_key', 'value'], }, is_for__device_type: { $select: 'slug', }, owns__release: mergePineOptionsTyped( { $select: releaseSelectedFields, $expand: { release_tag: { $select: ['tag_key', 'value'], }, }, }, options, ), }, $filter: { is_host: true, is_for__device_type: { $any: { $alias: 'dt', $expr: { dt: { slug: { $in: deviceTypes }, }, }, }, }, }, }, }); }; const _getOsVersionsFromReleases = ( releases: HostAppInfo['owns__release'], appTags: HostAppTagSet, ) => { const OsVariantNames = Object.keys(OsVariant); const OsVariantKeywords = new Set(Object.values(OsVariant) as string[]); return releases.map((release): OsVersion => { const tagMap = tagsToDictionary(release.release_tag!); const releaseSemverObj = !release.raw_version.startsWith('0.0.0') ? bSemver.parse(release.raw_version) : null; let version: string; let variant: string | undefined; if (releaseSemverObj != null) { version = releaseSemverObj.version; const nonVariantBuildParts = releaseSemverObj.build.filter( (b) => !OsVariantKeywords.has(b), ); if (nonVariantBuildParts.length > 0) { version += `+${nonVariantBuildParts.join('.')}`; } variant = releaseSemverObj.build.find((b) => OsVariantKeywords.has(b)); } else { // TODO: Drop this `else` once we migrate all version & variant tags to release.semver field /** Ideally 'production' | 'development' | undefined. */ const fullVariantName = tagMap[VARIANT_TAG_NAME] as string | undefined; variant = typeof fullVariantName === 'string' ? OsVariantNames.includes(fullVariantName) ? OsVariant[fullVariantName as keyof typeof OsVariant] : fullVariantName : undefined; version = tagMap[VERSION_TAG_NAME] ?? ''; // Backfill the native rel // TODO: This potentially generates an invalid semver and we should be doing // something like `.join(!version.includes('+') ? '+' : '.')`, but this needs // discussion since otherwise it will break all ESR released as of writing this. release.raw_version = [version, variant].filter((x) => !!x).join('.'); } const basedOnVersion = tagMap[BASED_ON_VERSION_TAG_NAME] ?? version; const line = getOsVersionReleaseLine(version, appTags); // TODO: Don't append the variant and sent it as a separate parameter when requesting a download when we don't use /device-types anymore and the API and image maker can handle it. Also rename `rawVersion` -> `versionWithVariant` if it is needed (it might not be needed anymore). // The version coming from release tags doesn't contain the variant, so we append it here return { ...release, osType: appTags.osType, line, strippedVersion: version, // TODO: Drop in the next major rawVersion: release.raw_version, basedOnVersion, variant, // TODO: Drop in the next major formattedVersion: `v${version}${line ? ` (${line})` : ''}`, }; }); }; const _transformHostApps = (apps: HostAppInfo[]) => { const osVersionsByDeviceType: OsVersionsByDeviceType = {}; apps.forEach((hostApp) => { const hostAppDeviceType = hostApp.is_for__device_type[0]?.slug; if (!hostAppDeviceType) { return; } osVersionsByDeviceType[hostAppDeviceType] ??= []; const appTags = getOsAppTags(hostApp.application_tag ?? []); osVersionsByDeviceType[hostAppDeviceType].push( ..._getOsVersionsFromReleases(hostApp.owns__release ?? [], appTags), ); }); // transform version sets Object.keys(osVersionsByDeviceType).forEach((deviceType) => { osVersionsByDeviceType[deviceType].sort(sortVersions); // TODO: Drop in next major // Note: the recommended version settings might come from the server in the future, for now we just set it to the latest version for each os type. const recommendedPerOsType: Dictionary<boolean> = {}; osVersionsByDeviceType[deviceType].forEach((version) => { if (!recommendedPerOsType[version.osType]) { if ( version.variant !== 'dev' && !version.known_issue_list && !bSemver.prerelease(version.raw_version) ) { const additionalFormat = version.line ? ` (${version.line}, recommended)` : ' (recommended)'; version.isRecommended = true; version.formattedVersion = `v${version.strippedVersion}${additionalFormat}`; recommendedPerOsType[version.osType] = true; } } }); }); return osVersionsByDeviceType; }; const _getAllOsVersions = async ( deviceTypes: string[], options?: PineOptions<Release>, ): Promise<OsVersionsByDeviceType> => { const hostapps = await _getOsVersions(deviceTypes, options); return await _transformHostApps(hostapps); }; const _memoizedGetAllOsVersions = authDependentMemoizer( async (deviceTypes: string[], listedByDefault: boolean | null) => { return await _getAllOsVersions( deviceTypes, listedByDefault ? { $filter: { is_final: true, is_invalidated: false, status: 'success', }, } : undefined, ); }, ); async function getAvailableOsVersions( deviceType: string, ): Promise<OsVersion[]>; async function getAvailableOsVersions( deviceTypes: string[], ): Promise<OsVersionsByDeviceType>; /** * @summary Get the supported OS versions for the provided device type(s) * @name getAvailableOsVersions * @public * @function * @memberof balena.models.os * * @param {String|String[]} deviceTypes - device type slug or array of slugs * @fulfil {Object[]|Object} - An array of OsVersion objects when a single device type slug is provided, * or a dictionary of OsVersion objects by device type slug when an array of device type slugs is provided. * @returns {Promise} * * @example * balena.models.os.getAvailableOsVersions('raspberrypi3'); * * @example * balena.models.os.getAvailableOsVersions(['fincm3', 'raspberrypi3']); */ async function getAvailableOsVersions( deviceTypes: string[] | string, ): Promise<OsVersionsByDeviceType | OsVersion[]> { const singleDeviceTypeArg = typeof deviceTypes === 'string' ? deviceTypes : false; deviceTypes = Array.isArray(deviceTypes) ? deviceTypes : [deviceTypes]; const versionsByDt = await _memoizedGetAllOsVersions( deviceTypes.slice().sort(), true, ); return singleDeviceTypeArg ? versionsByDt[singleDeviceTypeArg] ?? [] : versionsByDt; } async function getAllOsVersions( deviceType: string, options?: PineOptions<Release>, ): Promise<OsVersion[]>; async function getAllOsVersions( deviceTypes: string[], options?: PineOptions<Release>, ): Promise<OsVersionsByDeviceType>; /** * @summary Get all OS versions for the provided device type(s), inlcuding invalidated ones * @name getAllOsVersions * @public * @function * @memberof balena.models.os * * @param {String|String[]} deviceTypes - device type slug or array of slugs * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]|Object} - An array of OsVersion objects when a single device type slug is provided, * or a dictionary of OsVersion objects by device type slug when an array of device type slugs is provided. * @returns {Promise} * * @example * balena.models.os.getAllOsVersions('raspberrypi3'); * * @example * balena.models.os.getAllOsVersions(['fincm3', 'raspberrypi3']); * * @example * balena.models.os.getAllOsVersions(['fincm3', 'raspberrypi3'], { $filter: { is_invalidated: false } }); */ async function getAllOsVersions( deviceTypes: string[] | string, options?: PineOptions<Release>, ): Promise<OsVersionsByDeviceType | OsVersion[]> { const singleDeviceTypeArg = typeof deviceTypes === 'string' ? deviceTypes : false; deviceTypes = Array.isArray(deviceTypes) ? deviceTypes : [deviceTypes]; const versionsByDt = options == null ? await _memoizedGetAllOsVersions(deviceTypes.slice().sort(), null) : await _getAllOsVersions(deviceTypes, options); return singleDeviceTypeArg ? versionsByDt[singleDeviceTypeArg] ?? [] : versionsByDt; } /** * @summary Resolve the canonical device type slug * @description Utility method exported for testability. * @name _getNormalizedDeviceTypeSlug * @private * @function * @memberof balena.models.os */ const _getNormalizedDeviceTypeSlug = authDependentMemoizer( async (deviceTypeSlug: string) => { const dt = await deviceTypeModel().get(deviceTypeSlug, { $select: 'slug', }); return dt.slug; }, ); /** * @summary Get OS versions download size * @description Utility method exported for testability. * @name _getDownloadSize * @private * @function * @memberof balena.models.os */ const _getDownloadSize = authDependentMemoizer( async (deviceType: string, version: string) => { const { body } = await request.send({ method: 'GET', url: `/device-types/v1/${deviceType}/images/${version}/download-size`, baseUrl: apiUrl, }); return body.size as number; }, ); /** * @summary Clears the cached results from the `device-types/v1` endpoint. * @description Utility method exported for testability. * @name _clearDeviceTypesAndOsVersionCaches * @private * @function * @memberof balena.models.os */ const _clearDeviceTypesAndOsVersionCaches = () => { _getNormalizedDeviceTypeSlug.clear(); _getDownloadSize.clear(); _memoizedGetAllOsVersions.clear(); }; const normalizeVersion = (v: string) => { if (!v) { throw new Error(`Invalid version: ${v}`); } if (v === 'latest') { return v; } const vNormalized = v[0] === 'v' ? v.substring(1) : v; // We still don't want to allow `balenaOS` prefixes, which balena-semver allows. if (!bSemver.valid(vNormalized) || !/^\d/.test(vNormalized)) { throw new Error(`Invalid semver version: ${v}`); } return vNormalized; }; /** * @summary Get the max OS version satisfying the given range. * @description Utility method exported for testability. * @name _getMaxSatisfyingVersion * @private * @function * @memberof balena.models.os */ const _getMaxSatisfyingVersion = function ( versionOrRange: string, osVersions: Array<Pick<OsVersion, 'raw_version' | 'isRecommended'>>, ) { if (versionOrRange === 'recommended') { return osVersions.find((v) => v.isRecommended)?.raw_version; } if (versionOrRange === 'latest') { return osVersions[0]?.raw_version; } if (versionOrRange === 'default') { return (osVersions.find((v) => v.isRecommended) ?? osVersions[0]) ?.raw_version; } const versions = osVersions.map((v) => v.raw_version); if (versions.includes(versionOrRange)) { // If the _exact_ version you're looking for exists, it's not a range, and // we should return it exactly, not any old equivalent version. return versionOrRange; } const maxVersion = bSemver.maxSatisfying(versions, versionOrRange); return maxVersion; }; /** * @summary Get OS download size estimate * @name getDownloadSize * @public * @function * @memberof balena.models.os * @description **Note!** Currently only the raw (uncompressed) size is reported. * * @param {String} deviceType - device type slug * @param {String} [version] - semver-compatible version or 'latest', defaults to 'latest'. * The version **must** be the exact version number. * @fulfil {Number} - OS image download size, in bytes. * @returns {Promise} * * @example * balena.models.os.getDownloadSize('raspberry-pi').then(function(size) { * console.log('The OS download size for raspberry-pi', size); * }); * * balena.models.os.getDownloadSize('raspberry-pi', function(error, size) { * if (error) throw error; * console.log('The OS download size for raspberry-pi', size); * }); */ const getDownloadSize = async function ( deviceType: string, version: string = 'latest', ): Promise<number> { deviceType = await _getNormalizedDeviceTypeSlug(deviceType); return await _getDownloadSize(deviceType, version); }; /** * @summary Get the max OS version satisfying the given range * @name getMaxSatisfyingVersion * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @param {String} versionOrRange - can be one of * * the exact version number, * in which case it is returned if the version is supported, * or `null` is returned otherwise, * * a [semver](https://www.npmjs.com/package/semver)-compatible * range specification, in which case the most recent satisfying version is returned * if it exists, or `null` is returned, * * `'latest'` in which case the most recent version is returned, including pre-releases, * * `'recommended'` in which case the recommended version is returned, i.e. the most * recent version excluding pre-releases, which can be `null` if only pre-release versions * are available, * * `'default'` in which case the recommended version is returned if available, * or `latest` is returned otherwise. * Defaults to `'latest'`. * @param {String} [osType] - can be one of 'default', 'esr' or null to include all types * * @fulfil {String|null} - the version number, or `null` if no matching versions are found * @returns {Promise} * * @example * balena.models.os.getMaxSatisfyingVersion('raspberry-pi', '^2.11.0').then(function(version) { * console.log(version); * }); */ const getMaxSatisfyingVersion = async function ( deviceType: string, versionOrRange: string = 'latest', osType?: 'default' | 'esr', ): Promise<string | null> { deviceType = await _getNormalizedDeviceTypeSlug(deviceType); let osVersions = await getAvailableOsVersions(deviceType); if (osType != null) { osVersions = osVersions.filter((v) => v.osType === osType); } return _getMaxSatisfyingVersion(versionOrRange, osVersions) ?? null; }; /** * @summary Get the OS image last modified date * @name getLastModified * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @param {String} [version] - semver-compatible version or 'latest', defaults to 'latest'. * Unsupported (unpublished) version will result in rejection. * The version **must** be the exact version number. * To resolve the semver-compatible range use `balena.model.os.getMaxSatisfyingVersion`. * @fulfil {Date} - last modified date * @returns {Promise} * * @example * balena.models.os.getLastModified('raspberry-pi').then(function(date) { * console.log('The raspberry-pi image was last modified in ' + date); * }); * * balena.models.os.getLastModified('raspberrypi3', '2.0.0').then(function(date) { * console.log('The raspberry-pi image was last modified in ' + date); * }); * * balena.models.os.getLastModified('raspberry-pi', function(error, date) { * if (error) throw error; * console.log('The raspberry-pi image was last modified in ' + date); * }); */ const getLastModified = async function ( deviceType: string, version: string = 'latest', ): Promise<Date> { try { deviceType = await _getNormalizedDeviceTypeSlug(deviceType); version = normalizeVersion(version); const response = await request.send({ method: 'HEAD', url: '/download', qs: { deviceType, version, }, baseUrl: apiUrl, }); return new Date(response.headers.get('last-modified')!); } catch (err) { if (isNotFoundResponse(err)) { throw new Error('No such version for the device type'); } throw err; } }; /** * @summary Download an OS image * @name download * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @param {String} [version] - semver-compatible version or 'latest', defaults to 'latest' * Unsupported (unpublished) version will result in rejection. * The version **must** be the exact version number. * To resolve the semver-compatible range use `balena.model.os.getMaxSatisfyingVersion`. * @param {Object} options - OS configuration options to use. * @fulfil {ReadableStream} - download stream * @returns {Promise} * * @example * balena.models.os.download('raspberry-pi').then(function(stream) { * stream.pipe(fs.createWriteStream('foo/bar/image.img')); * }); * * balena.models.os.download('raspberry-pi', function(error, stream) { * if (error) throw error; * stream.pipe(fs.createWriteStream('foo/bar/image.img')); * }); */ const download = onlyIf(!isBrowser)(async function ( deviceType: string, version: string = 'latest', // TODO: make the downloadOptions the only argument in the next major options: { developmentMode?: boolean } = {}, ): Promise<BalenaRequestStreamResult> { try { const slug = await _getNormalizedDeviceTypeSlug(deviceType); if (version === 'latest') { const versions = (await getAvailableOsVersions(slug)).filter( (v) => v.osType === OsTypes.DEFAULT, ); version = (versions.find((v) => v.isRecommended) ?? versions[0]) ?.raw_version; } else { version = normalizeVersion(version); } return await request.stream({ method: 'GET', url: '/download', qs: { ...(typeof options === 'object' && options), deviceType, version, }, baseUrl: apiUrl, // optionally authenticated, so we send the token in all cases }); } catch (err) { if (isNotFoundResponse(err)) { throw new Error('No such version for the device type'); } throw err; } }); /** * @summary Get an applications config.json * @name getConfig * @public * @function * @memberof balena.models.os * * @description * Builds the config.json for a device in the given application, with the given * options. * * Note that an OS version is required. For versions < 2.7.8, config * generation is only supported when using a session token, not an API key. * * @param {String|Number} slugOrUuidOrId - application slug (string), uuid (string) or id (number). * @param {Object} options - OS configuration options to use. * @param {String} options.version - Required: the OS version of the image. * @param {String} [options.network='ethernet'] - The network type that * the device will use, one of 'ethernet' or 'wifi'. * @param {Number} [options.appUpdatePollInterval] - How often the OS checks * for updates, in minutes. * @param {String} [options.provisioningKeyName] - Name assigned to API key * @param {String} [options.provisioningKeyExpiryDate] - Expiry Date assigned to API key * @param {Boolean} [options.developmentMode] - Controls delopment mode for unified balenaOS releases. * @param {String} [options.wifiKey] - The key for the wifi network the * device will connect to. * @param {String} [options.wifiSsid] - The ssid for the wifi network the * device will connect to. * @param {String} [options.ip] - static ip address. * @param {String} [options.gateway] - static ip gateway. * @param {String} [options.netmask] - static ip netmask. * @fulfil {Object} - application configuration as a JSON object. * @returns {Promise} * * @example * balena.models.os.getConfig('myorganization/myapp', { version: '2.12.7+rev1.prod' }).then(function(config) { * fs.writeFile('foo/bar/config.json', JSON.stringify(config)); * }); * * balena.models.os.getConfig(123, { version: '2.12.7+rev1.prod' }).then(function(config) { * fs.writeFile('foo/bar/config.json', JSON.stringify(config)); * }); * * balena.models.os.getConfig('myorganization/myapp', { version: '2.12.7+rev1.prod' }, function(error, config) { * if (error) throw error; * fs.writeFile('foo/bar/config.json', JSON.stringify(config)); * }); */ const getConfig = async function ( slugOrUuidOrId: string | number, options: ImgConfigOptions, ): Promise<object> { if (!options?.version) { throw new Error('An OS version is required when calling os.getConfig'); } options.network = options.network ?? 'ethernet'; try { const applicationId = await applicationModel()._getId(slugOrUuidOrId); const { body } = await request.send({ method: 'POST', url: '/download-config', baseUrl: apiUrl, body: { ...options, appId: applicationId, }, }); return body; } catch (err) { if (isNotFoundResponse(err)) { treatAsMissingApplication(slugOrUuidOrId, err); } throw err; } }; /** * @summary Returns whether the provided device type supports OS updates between the provided balenaOS versions * @name isSupportedOsUpdate * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @param {String} currentVersion - semver-compatible version for the starting OS version * @param {String} targetVersion - semver-compatible version for the target OS version * @fulfil {Boolean} - whether upgrading the OS to the target version is supported * @returns {Promise} * * @example * balena.models.os.isSupportedOsUpgrade('raspberry-pi', '2.9.6+rev2.prod', '2.29.2+rev1.prod').then(function(isSupported) { * console.log(isSupported); * }); * * balena.models.os.isSupportedOsUpgrade('raspberry-pi', '2.9.6+rev2.prod', '2.29.2+rev1.prod', function(error, config) { * if (error) throw error; * console.log(isSupported); * }); */ const isSupportedOsUpdate = async ( deviceType: string, currentVersion: string, targetVersion: string, ): Promise<boolean> => { deviceType = await _getNormalizedDeviceTypeSlug(deviceType); return hupActionHelper().isSupportedOsUpdate( deviceType, currentVersion, targetVersion, ); }; /** * @summary Returns the supported OS update targets for the provided device type * @name getSupportedOsUpdateVersions * @public * @function * @memberof balena.models.os * * @param {String} deviceType - device type slug * @param {String} currentVersion - semver-compatible version for the starting OS version * @fulfil {Object} - the versions information, of the following structure: * * versions - an array of strings, * containing exact version numbers that OS update is supported * * recommended - the recommended version, i.e. the most recent version * that is _not_ pre-release, can be `null` * * current - the provided current version after normalization * @returns {Promise} * * @example * balena.models.os.getSupportedOsUpdateVersions('raspberry-pi', '2.9.6+rev2.prod').then(function(isSupported) { * console.log(isSupported); * }); * * balena.models.os.getSupportedOsUpdateVersions('raspberry-pi', '2.9.6+rev2.prod', function(error, config) { * if (error) throw error; * console.log(isSupported); * }); */ const getSupportedOsUpdateVersions = async ( deviceType: string, currentVersion: string, ): Promise<OsUpdateVersions> => { deviceType = await _getNormalizedDeviceTypeSlug(deviceType); const allVersions = (await getAvailableOsVersions(deviceType)) .filter((v) => v.osType === OsTypes.DEFAULT) .map((v) => v.raw_version); // use bSemver.compare to find the current version in the OS list // to benefit from the baked-in normalization const current = allVersions.find( (v) => bSemver.compare(v, currentVersion) === 0, ); const versions = allVersions.filter((v) => hupActionHelper().isSupportedOsUpdate(deviceType, currentVersion, v), ); const recommended = versions.filter((v) => !bSemver.prerelease(v))[0] as | string | undefined; return { versions, recommended, current, }; }; /** * @summary Returns whether the specified OS architecture is compatible with the target architecture * @name isArchitectureCompatibleWith * @public * @function * @memberof balena.models.os * * @param {String} osArchitecture - The OS's architecture as specified in its device type * @param {String} applicationArchitecture - The application's architecture as specified in its device type * @returns {Boolean} - Whether the specified OS architecture is capable of running * applications build for the target architecture * * @example * const result1 = balena.models.os.isArchitectureCompatibleWith('aarch64', 'armv7hf'); * console.log(result1); * * const result2 = balena.models.os.isArchitectureCompatibleWith('armv7hf', 'amd64'); * console.log(result2); */ const isArchitectureCompatibleWith = ( osArchitecture: string, applicationArchitecture: string, ): boolean => { const compatibleArches = archCompatibilityMap[osArchitecture]; return ( osArchitecture === applicationArchitecture || (Array.isArray(compatibleArches) && compatibleArches.includes(applicationArchitecture)) ); }; return { // Cast the exported types for internal methods so `@types/memoizee` can be a dev depenency. _getNormalizedDeviceTypeSlug: _getNormalizedDeviceTypeSlug as ( deviceTypeSlug: string, ) => Promise<string>, _getDownloadSize: _getDownloadSize as ( deviceType: string, version: string, ) => Promise<number>, _clearDeviceTypesAndOsVersionCaches, _getMaxSatisfyingVersion, OsTypes, getAllOsVersions, getAvailableOsVersions, getMaxSatisfyingVersion, getDownloadSize, getLastModified, download, getConfig, isSupportedOsUpdate, getSupportedOsUpdateVersions, isArchitectureCompatibleWith, }; }; export default getOsModel;
the_stack
import { CommonModule, DOCUMENT } from '@angular/common'; import { AfterViewChecked, Component, ContentChild, ContentChildren, ElementRef, HostBinding, HostListener, Input, NgModule, QueryList, Inject, Optional, OnDestroy, ChangeDetectorRef, } from '@angular/core'; import { IgxHintDirective } from '../directives/hint/hint.directive'; import { IgxInputDirective, IgxInputState, } from '../directives/input/input.directive'; import { IgxLabelDirective } from '../directives/label/label.directive'; import { IgxButtonModule } from '../directives/button/button.directive'; import { IgxIconModule } from '../icon/public_api'; import { IgxPrefixModule } from '../directives/prefix/prefix.directive'; import { IgxSuffixModule } from '../directives/suffix/suffix.directive'; import { DisplayDensity, IDisplayDensityOptions, DisplayDensityToken, DisplayDensityBase } from '../core/displayDensity'; import { IgxInputGroupBase } from './input-group.common'; import { IgxInputGroupType, IGX_INPUT_GROUP_TYPE } from './inputGroupType'; import { IInputResourceStrings } from '../core/i18n/input-resources'; import { CurrentResourceStrings } from '../core/i18n/resources'; import { mkenum, PlatformUtil } from '../core/utils'; import { Subject, Subscription } from 'rxjs'; const IgxInputGroupTheme = mkenum({ Material: 'material', Fluent: 'fluent', Bootstrap: 'bootstrap', IndigoDesign: 'indigo-design' }); /** * Determines the Input Group theme. */ export type IgxInputGroupTheme = (typeof IgxInputGroupTheme)[keyof typeof IgxInputGroupTheme]; @Component({ selector: 'igx-input-group', templateUrl: 'input-group.component.html', providers: [{ provide: IgxInputGroupBase, useExisting: IgxInputGroupComponent }], }) export class IgxInputGroupComponent extends DisplayDensityBase implements IgxInputGroupBase, AfterViewChecked, OnDestroy { /** * Sets the resource strings. * By default it uses EN resources. */ @Input() public set resourceStrings(value: IInputResourceStrings) { this._resourceStrings = Object.assign({}, this._resourceStrings, value); } /** * Returns the resource strings. */ public get resourceStrings(): IInputResourceStrings { return this._resourceStrings; } /** * Property that enables/disables the auto-generated class of the `IgxInputGroupComponent`. * By default applied the class is applied. * ```typescript * @ViewChild("MyInputGroup") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * this.inputGroup.defaultClass = false; * ``` * } */ @HostBinding('class.igx-input-group') public defaultClass = true; /** @hidden */ @HostBinding('class.igx-input-group--placeholder') public hasPlaceholder = false; /** @hidden */ @HostBinding('class.igx-input-group--required') public isRequired = false; /** @hidden */ @HostBinding('class.igx-input-group--focused') public isFocused = false; /** * @hidden @internal * When truthy, disables the `IgxInputGroupComponent`. * Controlled by the underlying `IgxInputDirective`. * ```html * <igx-input-group [disabled]="true"></igx-input-group> * ``` */ @HostBinding('class.igx-input-group--disabled') public disabled = false; /** * Prevents automatically focusing the input when clicking on other elements in the input group (e.g. prefix or suffix). * * @remarks Automatic focus causes software keyboard to show on mobile devices. * * @example * ```html * <igx-input-group [suppressInputAutofocus]="true"></igx-input-group> * ``` */ @Input() public suppressInputAutofocus = false; /** @hidden */ @HostBinding('class.igx-input-group--warning') public hasWarning = false; /** @hidden */ @ContentChildren(IgxHintDirective, { read: IgxHintDirective }) protected hints: QueryList<IgxHintDirective>; /** @hidden */ @ContentChild(IgxInputDirective, { read: IgxInputDirective, static: true }) protected input: IgxInputDirective; private _type: IgxInputGroupType = null; private _filled = false; private _theme: IgxInputGroupTheme; private _theme$ = new Subject(); private _subscription: Subscription; private _resourceStrings = CurrentResourceStrings.InputResStrings; /** @hidden */ @HostBinding('class.igx-input-group--valid') public get validClass(): boolean { return this.input.valid === IgxInputState.VALID; } /** @hidden */ @HostBinding('class.igx-input-group--invalid') public get invalidClass(): boolean { return this.input.valid === IgxInputState.INVALID; } /** @hidden */ @HostBinding('class.igx-input-group--filled') public get isFilled() { return this._filled || (this.input && this.input.value); } /** @hidden */ @HostBinding('class.igx-input-group--cosy') public get isDisplayDensityCosy() { return this.displayDensity === DisplayDensity.cosy; } /** @hidden */ @HostBinding('class.igx-input-group--comfortable') public get isDisplayDensityComfortable() { return this.displayDensity === DisplayDensity.comfortable; } /** @hidden */ @HostBinding('class.igx-input-group--compact') public get isDisplayDensityCompact() { return this.displayDensity === DisplayDensity.compact; } /** * An @Input property that sets how the input will be styled. * Allowed values of type IgxInputGroupType. * ```html * <igx-input-group [type]="'search'"> * ``` */ @Input('type') public set type(value: IgxInputGroupType) { this._type = value; } /** * Returns the type of the `IgxInputGroupComponent`. How the input is styled. * The default is `line`. * ```typescript * @ViewChild("MyInputGroup") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * let inputType = this.inputGroup.type; * } * ``` */ public get type() { return this._type || this._inputGroupType || 'line'; } /** * Sets the theme of the input. * Allowed values of type IgxInputGroupTheme. * ```typescript * @ViewChild("MyInputGroup") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit() { * let inputTheme = 'fluent'; * } */ @Input() public set theme(value: IgxInputGroupTheme) { this._theme = value; } /** * Returns the theme of the input. * The returned value is of type IgxInputGroupType. * ```typescript * @ViewChild("MyInputGroup") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit() { * let inputTheme = this.inputGroup.theme; * } */ public get theme(): IgxInputGroupTheme { return this._theme; } constructor( public element: ElementRef<HTMLElement>, @Optional() @Inject(DisplayDensityToken) _displayDensityOptions: IDisplayDensityOptions, @Optional() @Inject(IGX_INPUT_GROUP_TYPE) private _inputGroupType: IgxInputGroupType, @Inject(DOCUMENT) private document: any, private platform: PlatformUtil, private cdr: ChangeDetectorRef ) { super(_displayDensityOptions); this._subscription = this._theme$.asObservable().subscribe(value => { this._theme = value as IgxInputGroupTheme; this.cdr.detectChanges(); }); } /** @hidden */ @HostListener('click', ['$event']) public onClick(event: MouseEvent) { if ( !this.isFocused && event.target !== this.input.nativeElement && !this.suppressInputAutofocus ) { this.input.focus(); } } /** @hidden */ @HostListener('pointerdown', ['$event']) public onPointerDown(event: PointerEvent) { if (this.isFocused && event.target !== this.input.nativeElement) { event.preventDefault(); } } /** @hidden @internal */ public hintClickHandler(event: MouseEvent) { event.stopPropagation(); } /** * Returns whether the `IgxInputGroupComponent` has hints. * ```typescript * @ViewChild("MyInputGroup") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * let inputHints = this.inputGroup.hasHints; * } * ``` */ public get hasHints() { return this.hints.length > 0; } /** * Returns whether the `IgxInputGroupComponent` has border. * ```typescript * @ViewChild("MyInputGroup") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * let inputBorder = this.inputGroup.hasBorder; * } * ``` */ public get hasBorder() { return ( (this.type === 'line' || this.type === 'box') && this._theme === 'material' ); } /** * Returns whether the `IgxInputGroupComponent` type is line. * ```typescript * @ViewChild("MyInputGroup1") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * let isTypeLine = this.inputGroup.isTypeLine; * } * ``` */ public get isTypeLine(): boolean { return this.type === 'line' && this._theme === 'material'; } /** * Returns whether the `IgxInputGroupComponent` type is box. * ```typescript * @ViewChild("MyInputGroup1") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * let isTypeBox = this.inputGroup.isTypeBox; * } * ``` */ @HostBinding('class.igx-input-group--box') public get isTypeBox() { return this.type === 'box' && this._theme === 'material'; } /** @hidden @internal */ public uploadButtonHandler() { this.input.nativeElement.click(); } /** @hidden @internal */ public clearValueHandler() { this.input.clear(); } /** @hidden @internal */ @HostBinding('class.igx-input-group--file') public get isFileType() { return this.input.type === 'file'; } /** @hidden @internal */ public get fileNames() { return this.input.fileNames || this._resourceStrings.igx_input_file_placeholder; } /** * Returns whether the `IgxInputGroupComponent` type is border. * ```typescript * @ViewChild("MyInputGroup1") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * let isTypeBorder = this.inputGroup.isTypeBorder; * } * ``` */ @HostBinding('class.igx-input-group--border') public get isTypeBorder() { return this.type === 'border' && this._theme === 'material'; } /** * Returns true if the `IgxInputGroupComponent` theme is Fluent. * ```typescript * @ViewChild("MyInputGroup1") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * let isTypeFluent = this.inputGroup.isTypeFluent; * } * ``` */ @HostBinding('class.igx-input-group--fluent') public get isTypeFluent() { return this._theme === 'fluent'; } /** * Returns true if the `IgxInputGroupComponent` theme is Bootstrap. * ```typescript * @ViewChild("MyInputGroup1") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * let isTypeBootstrap = this.inputGroup.isTypeBootstrap; * } * ``` */ @HostBinding('class.igx-input-group--bootstrap') public get isTypeBootstrap() { return this._theme === 'bootstrap'; } /** * Returns true if the `IgxInputGroupComponent` theme is Indigo. * ```typescript * @ViewChild("MyInputGroup1") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * let isTypeIndigo = this.inputGroup.isTypeIndigo; * } * ``` */ @HostBinding('class.igx-input-group--indigo') public get isTypeIndigo() { return this._theme === 'indigo-design'; } /** * Returns whether the `IgxInputGroupComponent` type is search. * ```typescript * @ViewChild("MyInputGroup1") * public inputGroup: IgxInputGroupComponent; * ngAfterViewInit(){ * let isTypeSearch = this.inputGroup.isTypeSearch; * } * ``` */ @HostBinding('class.igx-input-group--search') public get isTypeSearch() { return this.type === 'search'; } /** @hidden */ public get filled() { return this._filled; } /** @hidden */ public set filled(val) { this._filled = val; } /** @hidden @internal */ public ngAfterViewChecked() { if (!this._theme) { if(this.platform.isIE) { Promise.resolve().then(() => { this._theme$.next(IgxInputGroupTheme.Material); }); } else { const cssProp = this.document.defaultView .getComputedStyle(this.element.nativeElement) .getPropertyValue('--theme') .trim(); if(cssProp !== '') { Promise.resolve().then(() => { this._theme$.next(cssProp); }); } } } } /** @hidden @internal */ public ngOnDestroy() { this._subscription.unsubscribe(); } } /** @hidden */ @NgModule({ declarations: [ IgxInputGroupComponent, IgxHintDirective, IgxInputDirective, IgxLabelDirective, ], exports: [ IgxInputGroupComponent, IgxHintDirective, IgxInputDirective, IgxLabelDirective, IgxPrefixModule, IgxSuffixModule, IgxButtonModule, IgxIconModule ], imports: [CommonModule, IgxPrefixModule, IgxSuffixModule, IgxButtonModule, IgxIconModule], }) export class IgxInputGroupModule {}
the_stack
import { InternalUpGradeNode, InternalUpGradeLink, DAGAIUConfig } from './types'; import { getRatio } from './utils'; import { isCross, crossPoint, distance, Point } from '../../Utils/graph'; import { find } from '../../Utils/utils'; export type LinkType = 'straightLine' | 'polyline' | 'diy'; export class StraightLine<Node, Relation> { // 层级节点数据 private nodesByLevel: InternalUpGradeNode<Node, Relation>[][]; // 自环边 private selfLinks: InternalUpGradeLink<Node, Relation>[]; // 配置 private config: DAGAIUConfig; private nodeLinkByLevelSourceNodeCount: number[] = []; constructor( nodesByLevel: InternalUpGradeNode<Node, Relation>[][], selfLinks: InternalUpGradeLink<Node, Relation>[], config: DAGAIUConfig ) { this.nodesByLevel = nodesByLevel; this.selfLinks = selfLinks; this.config = config; } calcPosAndPadding() { this.nodesByLevel.forEach(nodelevel => { let count = 0; nodelevel.forEach(node => { if (node.sourceLinks && node.sourceLinks.length) { count += node.sourceLinks.filter(link => { return link.target.level - link.source.level === 1; }).length; } }); this.nodeLinkByLevelSourceNodeCount.push(count); }); const levelPaddings: number[] = []; // 每个层级的间距,index = 0,对应 0 ~ 1 层级的高度 this.nodesByLevel.forEach((nodelevel, level) => { // 最后一层 if (level === this.nodesByLevel.length - 1) { levelPaddings[level] = 0; } else { levelPaddings[level] = Math.max( this.nodeLinkByLevelSourceNodeCount[level] * 15, this.config.levelSpace ); } }); return levelPaddings; } getFinalPath( link: InternalUpGradeLink<Node, Relation>, levelPaddings: number[], isLast: boolean, isFirst: boolean ): Point[] { // 箭头长度 const bDis = 6; const angle = 1 / 2; const startPoint = { x: link.source.finalPos.x + link.source.nodeWidth / 2, y: link.source.finalPos.y + link.source.nodeHeight / 2 }; const endPoint = { x: link.target.finalPos.x + link.target.nodeWidth / 2, y: link.target.finalPos.y + link.target.nodeHeight / 2 }; // @Todo 两个相同节点的相互连接边会重合,要考虑一下如何处理这个特殊情况 if (isFirst && link.isReverse) { const startNodeEdge = [ { x: link.source.finalPos.x, y: link.source.finalPos.y }, { x: link.source.finalPos.x + link.source.nodeWidth, y: link.source.finalPos.y }, { x: link.source.finalPos.x + link.source.nodeWidth, y: link.source.finalPos.y + link.source.nodeHeight }, { x: link.source.finalPos.x, y: link.source.finalPos.y + link.source.nodeHeight } ]; const cPoint = startNodeEdge.reduce((pre, edge, index) => { if ( isCross( startNodeEdge[index], startNodeEdge[index === startNodeEdge.length - 1 ? 0 : index + 1], startPoint, endPoint ) ) { return crossPoint( startNodeEdge[index], startNodeEdge[index === startNodeEdge.length - 1 ? 0 : index + 1], startPoint, endPoint ); } return pre; }, null); // 向量长度 const aDis = distance(endPoint, cPoint); // 计算箭头 const b = (endPoint.x - cPoint.x) * aDis * bDis * 2 * angle; const a = (endPoint.x - cPoint.x) * (endPoint.x - cPoint.x) + (endPoint.y - cPoint.y) * (endPoint.y - cPoint.y); const c = angle * angle * aDis * aDis * bDis * bDis - (endPoint.y - cPoint.y) * (endPoint.y - cPoint.y) * bDis * bDis; const y1 = cPoint.y + (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); const x1 = (angle * aDis * bDis + ((-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a)) * (endPoint.x - cPoint.x)) / (endPoint.y - cPoint.y) + cPoint.x; const y2 = cPoint.y + (b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); const x2 = (((endPoint.x - cPoint.x) * (b - Math.sqrt(b * b - 4 * a * c))) / (2 * a) - angle * aDis * bDis) / (endPoint.y - cPoint.y) + cPoint.x; return [ startPoint, cPoint, { x: x1, y: y1 }, cPoint, { x: x2, y: y2 }, cPoint, endPoint ]; } if (isLast && !link.isReverse) { const endNodeEdge = [ { x: link.target.finalPos.x, y: link.target.finalPos.y }, { x: link.target.finalPos.x + link.target.nodeWidth, y: link.target.finalPos.y }, { x: link.target.finalPos.x + link.target.nodeWidth, y: link.target.finalPos.y + link.target.nodeHeight }, { x: link.target.finalPos.x, y: link.target.finalPos.y + link.target.nodeHeight } ]; // 求焦点 const cPoint = endNodeEdge.reduce((pre, edge, index) => { if ( isCross( endNodeEdge[index], endNodeEdge[index === endNodeEdge.length - 1 ? 0 : index + 1], startPoint, endPoint ) ) { return crossPoint( endNodeEdge[index], endNodeEdge[index === endNodeEdge.length - 1 ? 0 : index + 1], startPoint, endPoint ); } return pre; }, null); // 向量长度 const aDis = distance(startPoint, cPoint); // 计算箭头 const b = (startPoint.x - cPoint.x) * aDis * bDis * 2 * angle; const a = (startPoint.x - cPoint.x) * (startPoint.x - cPoint.x) + (startPoint.y - cPoint.y) * (startPoint.y - cPoint.y); const c = angle * angle * aDis * aDis * bDis * bDis - (startPoint.y - cPoint.y) * (startPoint.y - cPoint.y) * bDis * bDis; const y1 = cPoint.y + (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a); const x1 = (angle * aDis * bDis + ((-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a)) * (startPoint.x - cPoint.x)) / (startPoint.y - cPoint.y) + cPoint.x; const y2 = cPoint.y + (b - Math.sqrt(b * b - 4 * a * c)) / (2 * a); const x2 = (((startPoint.x - cPoint.x) * (b - Math.sqrt(b * b - 4 * a * c))) / (2 * a) - angle * aDis * bDis) / (startPoint.y - cPoint.y) + cPoint.x; return [ startPoint, cPoint, { x: x1, y: y1 }, cPoint, { x: x2, y: y2 }, cPoint, endPoint ]; } return [startPoint, endPoint]; } getSelfFinalPath(link: InternalUpGradeLink<Node, Relation>): Point[] { const x0 = link.source.finalPos.x + link.source.nodeWidth / 2; const y0 = link.source.finalPos.y + link.source.nodeHeight; const x1 = link.target.finalPos.x + link.source.nodeWidth / 2 - 30; const y1 = link.target.finalPos.y; return [ { x: x0, y: y0 }, { x: x0, y: y0 + 12 }, { x: link.source.finalPos.x - 24, y: y0 + 12 }, { x: link.source.finalPos.x - 24, y: y1 - 12 }, { x: x1, y: y1 - 12 }, { x: x1, y: y1 }, { x: x1 - 3, y: y1 - 5 }, { x: x1, y: y1 }, { x: x1 + 3, y: y1 - 5 }, { x: x1, y: y1 } ]; } } export class Polyline<Node, Relation> { // 层级节点数据 private nodesByLevel: InternalUpGradeNode<Node, Relation>[][]; // 自环边 private selfLinks: InternalUpGradeLink<Node, Relation>[]; // 配置 private config: DAGAIUConfig; // 水平线防止重合 private turnYMap: Map<number, { /** 线的数量 */ allLine: Array<InternalUpGradeLink<Node, Relation>>, /** 记录 */ allRecord: Array<InternalUpGradeLink<Node, Relation>> }>; // 节点度的统计 private nodeLinkByLevelSourceNodeCount: number[] = []; constructor( nodesByLevel: InternalUpGradeNode<Node, Relation>[][], selfLinks: InternalUpGradeLink<Node, Relation>[], config: DAGAIUConfig ) { this.nodesByLevel = nodesByLevel; this.selfLinks = selfLinks; this.config = config; } // 计算连线起始位置 // 计算层级间距 calcPosAndPadding() { this.nodesByLevel.forEach(nodelevel => { let count = -1; nodelevel.forEach(node => { if (node.sourceLinks && node.sourceLinks.length) { node.sourceNodeIndex = ++count; } // 是否存在自环的情况 const selfLink = find(this.selfLinks, link => { return link.source.id === node.id; }); // 当前 node 下游节点数 const singleLevelSourceLinkCount = node.sourceLinks.filter(link => { return link.target.level - link.source.level === 1; }).length; // 当前 node 上游节点数 const singleLevelTargetLinkCount = node.targetLinks.filter(link => { return link.target.level - link.source.level === 1; }).length; // 会形成环的边是特殊的情况,不能合并 const singleLevelSourceLinks = node.sourceLinks .filter(link => { return link.target.level - link.source.level === 1; }) .sort((alink, blink) => { return ( alink.source.levelPos - blink.source.levelPos || (alink.isReverse ? 1 : 0) - (blink.isReverse ? 1 : 0) ); }); const sourceCount = node.sourceLinks.filter(link => { return link.isReverse; }).length + 1; let index = 0; singleLevelSourceLinks.forEach(link => { if (link.isReverse) index++; link.sourcePos = (((index + 1) / (sourceCount + 1) - 0.5) * 0.6 + 0.5) * link.source.nodeWidth; }); const singleLevelTargetLinks = node.targetLinks .filter(link => { return link.target.level - link.source.level === 1; }) .sort((alink, blink) => { return ( alink.source.levelPos - blink.source.levelPos || (alink.isReverse ? 1 : 0) - (blink.isReverse ? 1 : 0) ); }); singleLevelTargetLinks.forEach((link, index) => { link.targetPos = (((index + 1) / (singleLevelTargetLinkCount + 1) - 0.5) * 0.6 + 0.5) * link.target.nodeWidth; }); if (selfLink) { selfLink.sourcePos = ((1 / (singleLevelSourceLinkCount + 2) - 0.5) * 0.6 + 0.5) * node.nodeWidth; selfLink.targetPos = ((1 / (singleLevelTargetLinkCount + 2) - 0.5) * 0.6 + 0.5) * node.nodeWidth; } }); this.nodeLinkByLevelSourceNodeCount.push(count + 1); }); const levelPaddings = [] as any[]; // 每个层级的间距,index = 0,对应 0 ~ 1 层级的高度 this.nodesByLevel.forEach((nodelevel, level) => { // 最后一层 if (level === this.nodesByLevel.length - 1) { levelPaddings[level] = 0; } else { // 计算交叉,在这里把 turnY 计算完成,带在 link 里 // Aone #17817948 source 与 target 完全不同的水平线的重合是不被允许的 // 本质就是交叉的场景,@Todo 先采用一个简单的避免方案 const turnYCount = this.getLevelTurnYIndex(level); levelPaddings[level] = Math.max( (turnYCount + 1) * this.config.paddingLineSpace, this.config.levelSpace ); } }); return levelPaddings; } // turnY 确定在哪个位置上 getLevelTurnYIndex(level: number): number { let turnYCount = 0; const nodelevel = this.nodesByLevel[level]; this.turnYMap = new Map(); nodelevel.forEach((node, index) => { node.sourceLinks.forEach((link) => { // 值仅代表顺序 let turnYValue = getRatio( link.source.sourceNodeIndex, this.nodeLinkByLevelSourceNodeCount[link.source.level] ); if (this.turnYMap.has(turnYValue)) { const { allLine, allRecord } = this.turnYMap.get(turnYValue); if (!this.config._isLinkMerge && find(allRecord, (item) => { // 存在交叉,需要调整 turnY return (item.source.pos < link.source.pos && item.target.pos > link.target.pos) || (item.source.pos > link.source.pos && item.target.pos < link.target.pos); })) { // 遍历 allLine,查看是否有起点或是终点相同的节点,存在即 turnYValue 与其保持一致,没有的话,即 max turnYValue + 0.1 let maxTurnYValue = -Infinity; let flag = false; for (let i = 0; i < allLine.length; i++) { const line = allLine[i]; maxTurnYValue = Math.max(line.turnYValue, maxTurnYValue); if (line.source.id === link.source.id || line.target.id === link.target.id) { turnYValue = line.turnYValue; link.turnYValue = turnYValue; flag = true; break; } } if (!flag) { turnYValue = maxTurnYValue + 0.1; link.turnYValue = turnYValue; turnYCount++; allLine.push(link); } } else { link.turnYValue = turnYValue; } allRecord.push(link); this.turnYMap.set(turnYValue, { allLine, allRecord, }); } else { turnYCount++; link.turnYValue = turnYValue; this.turnYMap.set(turnYValue, { allLine: [link], allRecord: [link], }); } }); }); const valueArr: number[] = [...this.turnYMap.keys()].sort(); nodelevel.forEach((node) => { node.sourceLinks.forEach((link) => { link.turnYIndex = valueArr.indexOf(link.turnYValue) + 1; link.turnYCount = turnYCount; }); }); return turnYCount; } getFinalPath( link: InternalUpGradeLink<Node, Relation>, levelPaddings: number[], isLast: boolean, isFirst: boolean ): Point[] { const x0 = link.source.finalPos.x + link.sourcePos; const y0 = link.source.finalPos.y + link.source.nodeHeight; const x1 = link.target.finalPos.x + link.targetPos; const y1 = link.target.finalPos.y; // 水平线位置,很重要 let turnY = y0 + levelPaddings[link.source.level] * (link.turnYIndex / (link.turnYCount + 1)); if (isLast && !link.isReverse) { return [ { x: x0, y: y0 }, { x: x0, y: turnY }, { x: x1, y: turnY }, { x: x1, y: y1 }, { x: x1 - 3, y: y1 - 5 }, { x: x1, y: y1 }, { x: x1 + 3, y: y1 - 5 }, { x: x1, y: y1 } ]; } if (isFirst && link.isReverse) { return [ { x: x1, y: y1 }, { x: x1, y: turnY }, { x: x0, y: turnY }, { x: x0, y: y0 }, { x: x0 + 3, y: y0 + 5 }, { x: x0, y: y0 }, { x: x0 - 3, y: y0 + 5 }, { x: x0, y: y0 } ]; } return [ { x: x0, y: y0 }, { x: x0, y: turnY }, { x: x1, y: turnY }, { x: x1, y: y1 } ]; } getSelfFinalPath(link: InternalUpGradeLink<Node, Relation>): Point[] { const x0 = link.source.finalPos.x + link.sourcePos; const y0 = link.source.finalPos.y + link.source.nodeHeight; const x1 = link.target.finalPos.x + link.targetPos; const y1 = link.target.finalPos.y; return [ { x: x0, y: y0 }, { x: x0, y: y0 + 12 }, { x: link.source.finalPos.x - 24, y: y0 + 12 }, { x: link.source.finalPos.x - 24, y: y1 - 12 }, { x: x1, y: y1 - 12 }, { x: x1, y: y1 }, { x: x1 - 3, y: y1 - 5 }, { x: x1, y: y1 }, { x: x1 + 3, y: y1 - 5 }, { x: x1, y: y1 } ]; } } function LinkGenerator(type: LinkType, DiyLine?: any) { switch (type) { case 'straightLine': { return StraightLine; } case 'polyline': { return Polyline; } case 'diy': { return DiyLine; } } } export default LinkGenerator;
the_stack
import { BaseResource } from 'ms-rest-azure'; import { CloudError } from 'ms-rest-azure'; import * as moment from 'moment'; export { BaseResource } from 'ms-rest-azure'; export { CloudError } from 'ms-rest-azure'; /** * @class * Initializes a new instance of the Resource class. * @constructor * Describes an Azure resource. * * @member {string} [id] Resource Id * @member {string} [name] Resource name * @member {string} [type] Resource type */ export interface Resource extends BaseResource { readonly id?: string; readonly name?: string; readonly type?: string; } /** * @class * Initializes a new instance of the Kind class. * @constructor * Describes an Azure resource with kind * * @member {string} [kind] Kind of the resource */ export interface Kind { kind?: string; } /** * @class * Initializes a new instance of the SecurityContact class. * @constructor * Contact details for security issues * * @member {string} email The email of this security contact * @member {string} [phone] The phone number of this security contact * @member {string} alertNotifications Whether to send security alerts * notifications to the security contact. Possible values include: 'On', 'Off' * @member {string} alertsToAdmins Whether to send security alerts * notifications to subscription admins. Possible values include: 'On', 'Off' */ export interface SecurityContact extends Resource { email: string; phone?: string; alertNotifications: string; alertsToAdmins: string; } /** * @class * Initializes a new instance of the Pricing class. * @constructor * Pricing tier will be applied for the scope based on the resource ID * * @member {string} pricingTier Pricing tier type. Possible values include: * 'Free', 'Standard' */ export interface Pricing extends Resource { pricingTier: string; } /** * @class * Initializes a new instance of the WorkspaceSetting class. * @constructor * Configures where to store the OMS agent data for workspaces under a scope * * @member {string} workspaceId The full Azure ID of the workspace to save the * data in * @member {string} scope All the VMs in this scope will send their security * data to the mentioned workspace unless overridden by a setting with more * specific scope */ export interface WorkspaceSetting extends Resource { workspaceId: string; scope: string; } /** * @class * Initializes a new instance of the AutoProvisioningSetting class. * @constructor * Auto provisioning setting * * @member {string} autoProvision Describes what kind of security agent * provisioning action to take. Possible values include: 'On', 'Off' */ export interface AutoProvisioningSetting extends Resource { autoProvision: string; } /** * @class * Initializes a new instance of the ComplianceSegment class. * @constructor * A segment of a compliance assessment. * * @member {string} [segmentType] The segment type, e.g. compliant, * non-compliance, insufficient coverage, N/A, etc. * @member {number} [percentage] The size (%) of the segment. */ export interface ComplianceSegment { readonly segmentType?: string; readonly percentage?: number; } /** * @class * Initializes a new instance of the Compliance class. * @constructor * Compliance of a scope * * @member {date} [assessmentTimestampUtcDate] The timestamp when the * Compliance calculation was conducted. * @member {number} [resourceCount] The resource count of the given * subscription for which the Compliance calculation was conducted (needed for * Management Group Compliance calculation). * @member {array} [assessmentResult] An array of segment, which is the * actually the compliance assessment. */ export interface Compliance extends Resource { readonly assessmentTimestampUtcDate?: Date; readonly resourceCount?: number; readonly assessmentResult?: ComplianceSegment[]; } /** * @class * Initializes a new instance of the AdvancedThreatProtectionSetting class. * @constructor * The Advanced Threat Protection resource. * * @member {boolean} [isEnabled] Indicates whether Advanced Threat Protection * is enabled. */ export interface AdvancedThreatProtectionSetting extends Resource { isEnabled?: boolean; } /** * @class * Initializes a new instance of the Setting class. * @constructor * Represents a security setting in Azure Security Center. * * @member {string} [id] Resource Id * @member {string} [name] Resource name * @member {string} [type] Resource type * @member {string} kind Polymorphic Discriminator */ export interface Setting { readonly id?: string; readonly name?: string; readonly type?: string; kind: string; } /** * @class * Initializes a new instance of the DataExportSetting class. * @constructor * Represents a data export setting * * @member {boolean} enabled Is the data export setting is enabled */ export interface DataExportSetting extends Setting { enabled: boolean; } /** * @class * Initializes a new instance of the SettingKind1 class. * @constructor * The kind of the security setting * * @member {string} [kind] the kind of the settings string. Possible values * include: 'DataExportSetting' */ export interface SettingKind1 { kind?: string; } /** * @class * Initializes a new instance of the SensitivityLabel class. * @constructor * The sensitivity label. * * @member {string} [displayName] The name of the sensitivity label. * @member {number} [order] The order of the sensitivity label. * @member {boolean} [enabled] Indicates whether the label is enabled or not. */ export interface SensitivityLabel { displayName?: string; order?: number; enabled?: boolean; } /** * @class * Initializes a new instance of the InformationProtectionKeyword class. * @constructor * The information type keyword. * * @member {string} [pattern] The keyword pattern. * @member {boolean} [custom] Indicates whether the keyword is custom or not. * @member {boolean} [canBeNumeric] Indicates whether the keyword can be * applied on numeric types or not. * @member {boolean} [excluded] Indicates whether the keyword is excluded or * not. */ export interface InformationProtectionKeyword { pattern?: string; custom?: boolean; canBeNumeric?: boolean; excluded?: boolean; } /** * @class * Initializes a new instance of the InformationType class. * @constructor * The information type. * * @member {string} [displayName] The name of the information type. * @member {number} [order] The order of the information type. * @member {uuid} [recommendedLabelId] The recommended label id to be * associated with this information type. * @member {boolean} [enabled] Indicates whether the information type is * enabled or not. * @member {boolean} [custom] Indicates whether the information type is custom * or not. * @member {array} [keywords] The information type keywords. */ export interface InformationType { displayName?: string; order?: number; recommendedLabelId?: string; enabled?: boolean; custom?: boolean; keywords?: InformationProtectionKeyword[]; } /** * @class * Initializes a new instance of the InformationProtectionPolicy class. * @constructor * Information protection policy. * * @member {date} [lastModifiedUtc] Describes the last UTC time the policy was * modified. * @member {object} [labels] Dictionary of sensitivity labels. * @member {object} [informationTypes] The sensitivity information types. */ export interface InformationProtectionPolicy extends Resource { readonly lastModifiedUtc?: Date; labels?: { [propertyName: string]: SensitivityLabel }; informationTypes?: { [propertyName: string]: InformationType }; } /** * @class * Initializes a new instance of the Location class. * @constructor * Describes an Azure resource with location * * @member {string} [location] Location where the resource is stored */ export interface Location { readonly location?: string; } /** * @class * Initializes a new instance of the OperationDisplay class. * @constructor * Security operation display * * @member {string} [provider] The resource provider for the operation. * @member {string} [resource] The display name of the resource the operation * applies to. * @member {string} [operation] The display name of the security operation. * @member {string} [description] The description of the operation. */ export interface OperationDisplay { readonly provider?: string; readonly resource?: string; readonly operation?: string; readonly description?: string; } /** * @class * Initializes a new instance of the Operation class. * @constructor * Possible operation in the REST API of Microsoft.Security * * @member {string} [name] Name of the operation * @member {string} [origin] Where the operation is originated * @member {object} [display] * @member {string} [display.provider] The resource provider for the operation. * @member {string} [display.resource] The display name of the resource the * operation applies to. * @member {string} [display.operation] The display name of the security * operation. * @member {string} [display.description] The description of the operation. */ export interface Operation { readonly name?: string; readonly origin?: string; display?: OperationDisplay; } /** * @class * Initializes a new instance of the SecurityTaskParameters class. * @constructor * Changing set of properties, depending on the task type that is derived from * the name field * * @member {string} [name] Name of the task type */ export interface SecurityTaskParameters { readonly name?: string; /** * @property Describes unknown properties. The value of an unknown property * can be of "any" type. */ [property: string]: any; } /** * @class * Initializes a new instance of the SecurityTask class. * @constructor * Security task that we recommend to do in order to strengthen security * * @member {string} [state] State of the task (Active, Resolved etc.) * @member {date} [creationTimeUtc] The time this task was discovered in UTC * @member {object} [securityTaskParameters] * @member {string} [securityTaskParameters.name] Name of the task type * @member {date} [lastStateChangeTimeUtc] The time this task's details were * last changed in UTC * @member {string} [subState] Additional data on the state of the task */ export interface SecurityTask extends Resource { readonly state?: string; readonly creationTimeUtc?: Date; securityTaskParameters?: SecurityTaskParameters; readonly lastStateChangeTimeUtc?: Date; readonly subState?: string; } /** * @class * Initializes a new instance of the AscLocation class. * @constructor * The ASC location of the subscription is in the "name" field * * @member {object} [properties] */ export interface AscLocation extends Resource { properties?: any; } /** * @class * Initializes a new instance of the AlertEntity class. * @constructor * Changing set of properties depending on the entity type. * * @member {string} [type] Type of entity */ export interface AlertEntity { readonly type?: string; /** * @property Describes unknown properties. The value of an unknown property * can be of "any" type. */ [property: string]: any; } /** * @class * Initializes a new instance of the AlertConfidenceReason class. * @constructor * Factors that increase our confidence that the alert is a true positive * * @member {string} [type] Type of confidence factor * @member {string} [reason] description of the confidence reason */ export interface AlertConfidenceReason { readonly type?: string; readonly reason?: string; } /** * @class * Initializes a new instance of the Alert class. * @constructor * Security alert * * @member {string} [state] State of the alert (Active, Dismissed etc.) * @member {date} [reportedTimeUtc] The time the incident was reported to * Microsoft.Security in UTC * @member {string} [vendorName] Name of the vendor that discovered the * incident * @member {string} [alertName] Name of the alert type * @member {string} [alertDisplayName] Display name of the alert type * @member {date} [detectedTimeUtc] The time the incident was detected by the * vendor * @member {string} [description] Description of the incident and what it means * @member {string} [remediationSteps] Recommended steps to reradiate the * incident * @member {string} [actionTaken] The action that was taken as a response to * the alert (Active, Blocked etc.) * @member {string} [reportedSeverity] Estimated severity of this alert * @member {string} [compromisedEntity] The entity that the incident happened * on * @member {string} [associatedResource] Azure resource ID of the associated * resource * @member {object} [extendedProperties] * @member {string} [systemSource] The type of the alerted resource (Azure, * Non-Azure) * @member {boolean} [canBeInvestigated] Whether this alert can be investigated * with Azure Security Center * @member {array} [entities] objects that are related to this alerts * @member {number} [confidenceScore] level of confidence we have on the alert * @member {array} [confidenceReasons] reasons the alert got the * confidenceScore value * @member {string} [subscriptionId] Azure subscription ID of the resource that * had the security alert or the subscription ID of the workspace that this * resource reports to * @member {string} [instanceId] Instance ID of the alert. * @member {string} [workspaceArmId] Azure resource ID of the workspace that * the alert was reported to. */ export interface Alert extends Resource { readonly state?: string; readonly reportedTimeUtc?: Date; readonly vendorName?: string; readonly alertName?: string; readonly alertDisplayName?: string; readonly detectedTimeUtc?: Date; readonly description?: string; readonly remediationSteps?: string; readonly actionTaken?: string; readonly reportedSeverity?: string; readonly compromisedEntity?: string; readonly associatedResource?: string; extendedProperties?: { [propertyName: string]: any }; readonly systemSource?: string; readonly canBeInvestigated?: boolean; entities?: AlertEntity[]; readonly confidenceScore?: number; confidenceReasons?: AlertConfidenceReason[]; readonly subscriptionId?: string; readonly instanceId?: string; readonly workspaceArmId?: string; } /** * @class * Initializes a new instance of the DiscoveredSecuritySolution class. * @constructor * @member {string} [id] Resource Id * @member {string} [name] Resource name * @member {string} [type] Resource type * @member {string} [location] Location where the resource is stored * @member {string} securityFamily The security family of the discovered * solution. Possible values include: 'Waf', 'Ngfw', 'SaasWaf', 'Va' * @member {string} offer The security solutions' image offer * @member {string} publisher The security solutions' image publisher * @member {string} sku The security solutions' image sku */ export interface DiscoveredSecuritySolution { readonly id?: string; readonly name?: string; readonly type?: string; readonly location?: string; securityFamily: string; offer: string; publisher: string; sku: string; } /** * @class * Initializes a new instance of the TopologySingleResourceParent class. * @constructor * @member {string} [resourceId] Azure resource id which serves as parent * resource in topology view */ export interface TopologySingleResourceParent { readonly resourceId?: string; } /** * @class * Initializes a new instance of the TopologySingleResourceChild class. * @constructor * @member {string} [resourceId] Azure resource id which serves as child * resource in topology view */ export interface TopologySingleResourceChild { readonly resourceId?: string; } /** * @class * Initializes a new instance of the TopologySingleResource class. * @constructor * @member {string} [resourceId] Azure resource id * @member {string} [severity] The security severity of the resource * @member {boolean} [recommendationsExist] Indicates if the resource has * security recommendations * @member {string} [networkZones] Indicates the resource connectivity level to * the Internet (InternetFacing, Internal ,etc.) * @member {number} [topologyScore] Score of the resource based on its security * severity * @member {string} [location] The location of this resource * @member {array} [parents] Azure resources connected to this resource which * are in higher level in the topology view * @member {array} [children] Azure resources connected to this resource which * are in lower level in the topology view */ export interface TopologySingleResource { readonly resourceId?: string; readonly severity?: string; readonly recommendationsExist?: boolean; readonly networkZones?: string; readonly topologyScore?: number; readonly location?: string; readonly parents?: TopologySingleResourceParent[]; readonly children?: TopologySingleResourceChild[]; } /** * @class * Initializes a new instance of the TopologyResource class. * @constructor * @member {string} [id] Resource Id * @member {string} [name] Resource name * @member {string} [type] Resource type * @member {string} [location] Location where the resource is stored * @member {date} [calculatedDateTime] The UTC time on which the topology was * calculated * @member {array} [topologyResources] Azure resources which are part of this * topology resource */ export interface TopologyResource { readonly id?: string; readonly name?: string; readonly type?: string; readonly location?: string; readonly calculatedDateTime?: Date; readonly topologyResources?: TopologySingleResource[]; } /** * @class * Initializes a new instance of the JitNetworkAccessPortRule class. * @constructor * @member {number} number * @member {string} protocol Possible values include: 'TCP', 'UDP', 'All' * @member {string} [allowedSourceAddressPrefix] Mutually exclusive with the * "allowedSourceAddressPrefixes" parameter. Should be an IP address or CIDR, * for example "192.168.0.3" or "192.168.0.0/16". * @member {array} [allowedSourceAddressPrefixes] Mutually exclusive with the * "allowedSourceAddressPrefix" parameter. * @member {string} maxRequestAccessDuration Maximum duration requests can be * made for. In ISO 8601 duration format. Minimum 5 minutes, maximum 1 day */ export interface JitNetworkAccessPortRule { number: number; protocol: string; allowedSourceAddressPrefix?: string; allowedSourceAddressPrefixes?: string[]; maxRequestAccessDuration: string; } /** * @class * Initializes a new instance of the JitNetworkAccessPolicyVirtualMachine class. * @constructor * @member {string} id Resource ID of the virtual machine that is linked to * this policy * @member {array} ports Port configurations for the virtual machine */ export interface JitNetworkAccessPolicyVirtualMachine { id: string; ports: JitNetworkAccessPortRule[]; } /** * @class * Initializes a new instance of the JitNetworkAccessRequestPort class. * @constructor * @member {number} number * @member {string} [allowedSourceAddressPrefix] Mutually exclusive with the * "allowedSourceAddressPrefixes" parameter. Should be an IP address or CIDR, * for example "192.168.0.3" or "192.168.0.0/16". * @member {array} [allowedSourceAddressPrefixes] Mutually exclusive with the * "allowedSourceAddressPrefix" parameter. * @member {date} endTimeUtc The date & time at which the request ends in UTC * @member {string} status The status of the port. Possible values include: * 'Revoked', 'Initiated' * @member {string} statusReason A description of why the `status` has its * value. Possible values include: 'Expired', 'UserRequested', * 'NewerRequestInitiated' */ export interface JitNetworkAccessRequestPort { number: number; allowedSourceAddressPrefix?: string; allowedSourceAddressPrefixes?: string[]; endTimeUtc: Date; status: string; statusReason: string; } /** * @class * Initializes a new instance of the JitNetworkAccessRequestVirtualMachine class. * @constructor * @member {string} id Resource ID of the virtual machine that is linked to * this policy * @member {array} ports The ports that were opened for the virtual machine */ export interface JitNetworkAccessRequestVirtualMachine { id: string; ports: JitNetworkAccessRequestPort[]; } /** * @class * Initializes a new instance of the JitNetworkAccessRequest class. * @constructor * @member {array} virtualMachines * @member {date} startTimeUtc The start time of the request in UTC * @member {string} requestor The identity of the person who made the request */ export interface JitNetworkAccessRequest { virtualMachines: JitNetworkAccessRequestVirtualMachine[]; startTimeUtc: Date; requestor: string; } /** * @class * Initializes a new instance of the JitNetworkAccessPolicy class. * @constructor * @member {string} [id] Resource Id * @member {string} [name] Resource name * @member {string} [type] Resource type * @member {string} [kind] Kind of the resource * @member {string} [location] Location where the resource is stored * @member {array} virtualMachines Configurations for * Microsoft.Compute/virtualMachines resource type. * @member {array} [requests] * @member {string} [provisioningState] Gets the provisioning state of the * Just-in-Time policy. */ export interface JitNetworkAccessPolicy { readonly id?: string; readonly name?: string; readonly type?: string; kind?: string; readonly location?: string; virtualMachines: JitNetworkAccessPolicyVirtualMachine[]; requests?: JitNetworkAccessRequest[]; readonly provisioningState?: string; } /** * @class * Initializes a new instance of the JitNetworkAccessPolicyInitiatePort class. * @constructor * @member {number} number * @member {string} [allowedSourceAddressPrefix] Source of the allowed traffic. * If omitted, the request will be for the source IP address of the initiate * request. * @member {date} endTimeUtc The time to close the request in UTC */ export interface JitNetworkAccessPolicyInitiatePort { number: number; allowedSourceAddressPrefix?: string; endTimeUtc: Date; } /** * @class * Initializes a new instance of the JitNetworkAccessPolicyInitiateVirtualMachine class. * @constructor * @member {string} id Resource ID of the virtual machine that is linked to * this policy * @member {array} ports The ports to open for the resource with the `id` */ export interface JitNetworkAccessPolicyInitiateVirtualMachine { id: string; ports: JitNetworkAccessPolicyInitiatePort[]; } /** * @class * Initializes a new instance of the JitNetworkAccessPolicyInitiateRequest class. * @constructor * @member {array} virtualMachines A list of virtual machines & ports to open * access for */ export interface JitNetworkAccessPolicyInitiateRequest { virtualMachines: JitNetworkAccessPolicyInitiateVirtualMachine[]; } /** * @class * Initializes a new instance of the ExternalSecuritySolution class. * @constructor * Represents a security solution external to Azure Security Center which sends * information to an OMS workspace and whos data is displayed by Azure Security * Center. * * @member {string} [id] Resource Id * @member {string} [name] Resource name * @member {string} [type] Resource type * @member {string} [location] Location where the resource is stored * @member {string} kind Polymorphic Discriminator */ export interface ExternalSecuritySolution { readonly id?: string; readonly name?: string; readonly type?: string; readonly location?: string; kind: string; } /** * @class * Initializes a new instance of the ExternalSecuritySolutionProperties class. * @constructor * The solution properties (correspond to the solution kind) * * @member {string} [deviceVendor] * @member {string} [deviceType] * @member {object} [workspace] * @member {string} [workspace.id] Azure resource ID of the connected OMS * workspace */ export interface ExternalSecuritySolutionProperties { deviceVendor?: string; deviceType?: string; workspace?: ConnectedWorkspace; /** * @property Describes unknown properties. The value of an unknown property * can be of "any" type. */ [property: string]: any; } /** * @class * Initializes a new instance of the CefSolutionProperties class. * @constructor * @summary The external security solution properties for CEF solutions * * @member {string} [hostname] * @member {string} [agent] * @member {string} [lastEventReceived] */ export interface CefSolutionProperties extends ExternalSecuritySolutionProperties { hostname?: string; agent?: string; lastEventReceived?: string; } /** * @class * Initializes a new instance of the CefExternalSecuritySolution class. * @constructor * Represents a security solution which sends CEF logs to an OMS workspace * * @member {object} [properties] * @member {string} [properties.hostname] * @member {string} [properties.agent] * @member {string} [properties.lastEventReceived] */ export interface CefExternalSecuritySolution extends ExternalSecuritySolution { properties?: CefSolutionProperties; } /** * @class * Initializes a new instance of the AtaSolutionProperties class. * @constructor * @summary The external security solution properties for ATA solutions * * @member {string} [lastEventReceived] */ export interface AtaSolutionProperties extends ExternalSecuritySolutionProperties { lastEventReceived?: string; } /** * @class * Initializes a new instance of the AtaExternalSecuritySolution class. * @constructor * Represents an ATA security solution which sends logs to an OMS workspace * * @member {object} [properties] * @member {string} [properties.lastEventReceived] */ export interface AtaExternalSecuritySolution extends ExternalSecuritySolution { properties?: AtaSolutionProperties; } /** * @class * Initializes a new instance of the ConnectedWorkspace class. * @constructor * @summary Represents an OMS workspace to which the solution is connected * * @member {string} [id] Azure resource ID of the connected OMS workspace */ export interface ConnectedWorkspace { id?: string; } /** * @class * Initializes a new instance of the AadSolutionProperties class. * @constructor * @summary The external security solution properties for AAD solutions * * @member {string} [deviceVendor] * @member {string} [deviceType] * @member {object} [workspace] * @member {string} [workspace.id] Azure resource ID of the connected OMS * workspace * @member {string} [connectivityState] The connectivity state of the external * AAD solution . Possible values include: 'Discovered', 'NotLicensed', * 'Connected' */ export interface AadSolutionProperties { deviceVendor?: string; deviceType?: string; workspace?: ConnectedWorkspace; connectivityState?: string; } /** * @class * Initializes a new instance of the AadExternalSecuritySolution class. * @constructor * Represents an AAD identity protection solution which sends logs to an OMS * workspace. * * @member {object} [properties] * @member {string} [properties.deviceVendor] * @member {string} [properties.deviceType] * @member {object} [properties.workspace] * @member {string} [properties.workspace.id] Azure resource ID of the * connected OMS workspace * @member {string} [properties.connectivityState] Possible values include: * 'Discovered', 'NotLicensed', 'Connected' */ export interface AadExternalSecuritySolution extends ExternalSecuritySolution { properties?: AadSolutionProperties; } /** * @class * Initializes a new instance of the ExternalSecuritySolutionKind1 class. * @constructor * Describes an Azure resource with kind * * @member {string} [kind] The kind of the external solution. Possible values * include: 'CEF', 'ATA', 'AAD' */ export interface ExternalSecuritySolutionKind1 { kind?: string; } /** * @class * Initializes a new instance of the AadConnectivityState1 class. * @constructor * Describes an Azure resource with kind * * @member {string} [connectivityState] The connectivity state of the external * AAD solution . Possible values include: 'Discovered', 'NotLicensed', * 'Connected' */ export interface AadConnectivityState1 { connectivityState?: string; } /** * @class * Initializes a new instance of the ConnectedResource class. * @constructor * Describes properties of a connected resource * * @member {string} [connectedResourceId] The Azure resource id of the * connected resource * @member {string} [tcpPorts] The allowed tcp ports * @member {string} [udpPorts] The allowed udp ports */ export interface ConnectedResource { readonly connectedResourceId?: string; readonly tcpPorts?: string; readonly udpPorts?: string; } /** * @class * Initializes a new instance of the ConnectableResource class. * @constructor * Describes the allowed inbound and outbound traffic of an Azure resource * * @member {string} [id] The Azure resource id * @member {array} [inboundConnectedResources] The list of Azure resources that * the resource has inbound allowed connection from * @member {array} [outboundConnectedResources] The list of Azure resources * that the resource has outbound allowed connection to */ export interface ConnectableResource { readonly id?: string; readonly inboundConnectedResources?: ConnectedResource[]; readonly outboundConnectedResources?: ConnectedResource[]; } /** * @class * Initializes a new instance of the AllowedConnectionsResource class. * @constructor * The resource whose properties describes the allowed traffic between Azure * resources * * @member {string} [id] Resource Id * @member {string} [name] Resource name * @member {string} [type] Resource type * @member {string} [location] Location where the resource is stored * @member {date} [calculatedDateTime] The UTC time on which the allowed * connections resource was calculated * @member {array} [connectableResources] List of connectable resources */ export interface AllowedConnectionsResource { readonly id?: string; readonly name?: string; readonly type?: string; readonly location?: string; readonly calculatedDateTime?: Date; readonly connectableResources?: ConnectableResource[]; } /** * @class * Initializes a new instance of the PricingList class. * @constructor * List of pricing configurations response * * @member {string} [nextLink] The URI to fetch the next page. */ export interface PricingList extends Array<Pricing> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the SecurityContactList class. * @constructor * List of security contacts response * * @member {string} [nextLink] The URI to fetch the next page. */ export interface SecurityContactList extends Array<SecurityContact> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the WorkspaceSettingList class. * @constructor * List of workspace settings response * * @member {string} [nextLink] The URI to fetch the next page. */ export interface WorkspaceSettingList extends Array<WorkspaceSetting> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the AutoProvisioningSettingList class. * @constructor * List of all the auto provisioning settings response * * @member {string} [nextLink] The URI to fetch the next page. */ export interface AutoProvisioningSettingList extends Array<AutoProvisioningSetting> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the ComplianceList class. * @constructor * List of Compliance objects response * * @member {string} [nextLink] The URI to fetch the next page. */ export interface ComplianceList extends Array<Compliance> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the SettingsList class. * @constructor * Subscription settings list. * * @member {string} [nextLink] The URI to fetch the next page. */ export interface SettingsList extends Array<Setting> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the InformationProtectionPolicyList class. * @constructor * Information protection policies response. * * @member {string} [nextLink] The URI to fetch the next page. */ export interface InformationProtectionPolicyList extends Array<InformationProtectionPolicy> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the OperationList class. * @constructor * List of possible operations for Microsoft.Security resource provider * * @member {string} [nextLink] The URI to fetch the next page. */ export interface OperationList extends Array<Operation> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the AscLocationList class. * @constructor * List of locations where ASC saves your data * * @member {string} [nextLink] The URI to fetch the next page. */ export interface AscLocationList extends Array<AscLocation> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the SecurityTaskList class. * @constructor * List of security task recommendations * * @member {string} [nextLink] The URI to fetch the next page. */ export interface SecurityTaskList extends Array<SecurityTask> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the AlertList class. * @constructor * List of security alerts * * @member {string} [nextLink] The URI to fetch the next page. */ export interface AlertList extends Array<Alert> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the DiscoveredSecuritySolutionList class. * @constructor * @member {string} [nextLink] The URI to fetch the next page. */ export interface DiscoveredSecuritySolutionList extends Array<DiscoveredSecuritySolution> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the JitNetworkAccessPoliciesList class. * @constructor * @member {string} [nextLink] The URI to fetch the next page. */ export interface JitNetworkAccessPoliciesList extends Array<JitNetworkAccessPolicy> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the ExternalSecuritySolutionList class. * @constructor * @member {string} [nextLink] The URI to fetch the next page. */ export interface ExternalSecuritySolutionList extends Array<ExternalSecuritySolution> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the TopologyList class. * @constructor * @member {string} [nextLink] The URI to fetch the next page. */ export interface TopologyList extends Array<TopologyResource> { readonly nextLink?: string; } /** * @class * Initializes a new instance of the AllowedConnectionsList class. * @constructor * List of all possible traffic between Azure resources * * @member {string} [nextLink] The URI to fetch the next page. */ export interface AllowedConnectionsList extends Array<AllowedConnectionsResource> { readonly nextLink?: string; }
the_stack
import { addClass, detach, EventHandler, L10n, isNullOrUndefined, KeyboardEventArgs, select, Ajax, formatUnit } from '@syncfusion/ej2-base'; import { Browser, closest, removeClass, isNullOrUndefined as isNOU } from '@syncfusion/ej2-base'; import { IImageCommandsArgs, IRenderer, IDropDownItemModel, IToolbarItemModel, OffsetPosition, ImageSuccessEventArgs, ImageDropEventArgs, ActionBeginEventArgs, ActionCompleteEventArgs, AfterImageDeleteEventArgs, ImageUploadingEventArgs } from '../base/interface'; import { IRichTextEditor, IImageNotifyArgs, NotifyArgs, IShowPopupArgs, ResizeArgs } from '../base/interface'; import * as events from '../base/constant'; import * as classes from '../base/classes'; import { ServiceLocator } from '../services/service-locator'; import { NodeSelection } from '../../selection/selection'; import { Uploader, SelectedEventArgs, MetaData, TextBox, InputEventArgs, FileInfo, BeforeUploadEventArgs } from '@syncfusion/ej2-inputs'; import { RemovingEventArgs, UploadingEventArgs, ProgressEventArgs } from '@syncfusion/ej2-inputs'; import { Dialog, DialogModel, Popup } from '@syncfusion/ej2-popups'; import { Button, CheckBox, ChangeEventArgs } from '@syncfusion/ej2-buttons'; import { RendererFactory } from '../services/renderer-factory'; import { ClickEventArgs } from '@syncfusion/ej2-navigations'; import { RenderType } from '../base/enum'; import { dispatchEvent, parseHtml, hasClass, convertToBlob } from '../base/util'; import { DialogRenderer } from './dialog-renderer'; import { isIDevice } from '../../common/util'; /** * `Image` module is used to handle image actions. */ export class Image { public element: HTMLElement; private rteID: string; private parent: IRichTextEditor; public dialogObj: Dialog; private popupObj: Popup; public uploadObj: Uploader; private i10n: L10n; private inputUrl: HTMLElement; private captionEle: HTMLElement; private checkBoxObj: CheckBox; private uploadUrl: IImageCommandsArgs; private contentModule: IRenderer; private rendererFactory: RendererFactory; private quickToolObj: IRenderer; private imgResizeDiv: HTMLElement; private imgDupPos: { [key: string]: number | string }; private resizeBtnStat: { [key: string]: boolean }; private imgEle: HTMLImageElement; private prevSelectedImgEle: HTMLImageElement; private isImgUploaded: boolean = false; private isAllowedTypes: boolean = true; private pageX: number = null; private pageY: number = null; private dialogRenderObj: DialogRenderer; private deletedImg: Node[] = []; private changedWidthValue: string; private changedHeightValue: string; private inputWidthValue: string; private inputHeightValue: string; private constructor(parent?: IRichTextEditor, serviceLocator?: ServiceLocator) { this.parent = parent; this.rteID = parent.element.id; this.i10n = serviceLocator.getService<L10n>('rteLocale'); this.rendererFactory = serviceLocator.getService<RendererFactory>('rendererFactory'); this.dialogRenderObj = serviceLocator.getService<DialogRenderer>('dialogRenderObject'); this.addEventListener(); } protected addEventListener(): void { if (this.parent.isDestroyed) { return; } this.parent.on(events.keyDown, this.onKeyDown, this); this.parent.on(events.keyUp, this.onKeyUp, this); this.parent.on(events.insertImage, this.insertImage, this); this.parent.on(events.showImageDialog, this.showDialog, this); this.parent.on(events.closeImageDialog, this.closeDialog, this); this.parent.on(events.windowResize, this.onWindowResize, this); this.parent.on(events.insertCompleted, this.showImageQuickToolbar, this); this.parent.on(events.clearDialogObj, this.clearDialogObj, this); this.parent.on(events.imageToolbarAction, this.onToolbarAction, this); this.parent.on(events.imageCaption, this.caption, this); this.parent.on(events.imageDelete, this.deleteImg, this); this.parent.on(events.imageLink, this.insertImgLink, this); this.parent.on(events.imageAlt, this.insertAltText, this); this.parent.on(events.editAreaClick, this.editAreaClickHandler, this); this.parent.on(events.iframeMouseDown, this.onIframeMouseDown, this); this.parent.on(events.imageSize, this.imageSize, this); this.parent.on(events.dropDownSelect, this.alignmentSelect, this); this.parent.on(events.initialEnd, this.afterRender, this); this.parent.on(events.dynamicModule, this.afterRender, this); this.parent.on(events.paste, this.imagePaste, this); this.parent.on(events.destroy, this.removeEventListener, this); } protected removeEventListener(): void { if (this.parent.isDestroyed) { return; } this.parent.off(events.keyDown, this.onKeyDown); this.parent.off(events.keyUp, this.onKeyUp); this.parent.off(events.windowResize, this.onWindowResize); this.parent.off(events.insertImage, this.insertImage); this.parent.off(events.showImageDialog, this.showDialog); this.parent.off(events.closeImageDialog, this.closeDialog); this.parent.off(events.insertCompleted, this.showImageQuickToolbar); this.parent.off(events.clearDialogObj, this.clearDialogObj); this.parent.off(events.imageCaption, this.caption); this.parent.off(events.imageToolbarAction, this.onToolbarAction); this.parent.off(events.imageDelete, this.deleteImg); this.parent.off(events.imageLink, this.insertImgLink); this.parent.off(events.imageAlt, this.insertAltText); this.parent.off(events.editAreaClick, this.editAreaClickHandler); this.parent.off(events.iframeMouseDown, this.onIframeMouseDown); this.parent.off(events.imageSize, this.imageSize); this.parent.off(events.dropDownSelect, this.alignmentSelect); this.parent.off(events.initialEnd, this.afterRender); this.parent.off(events.dynamicModule, this.afterRender); this.parent.off(events.paste, this.imagePaste); this.parent.off(events.destroy, this.removeEventListener); const dropElement: HTMLElement | Document = this.parent.iframeSettings.enable ? this.parent.inputElement.ownerDocument : this.parent.inputElement; dropElement.removeEventListener('drop', this.dragDrop.bind(this), true); dropElement.removeEventListener('dragstart', this.dragStart.bind(this), true); dropElement.removeEventListener('dragenter', this.dragEnter.bind(this), true); dropElement.removeEventListener('dragover', this.dragOver.bind(this), true); if (!isNullOrUndefined(this.contentModule)) { EventHandler.remove(this.contentModule.getEditPanel(), Browser.touchEndEvent, this.imageClick); this.parent.formatter.editorManager.observer.off(events.checkUndo, this.undoStack); if (this.parent.insertImageSettings.resize) { EventHandler.remove(this.parent.contentModule.getEditPanel(), Browser.touchStartEvent, this.resizeStart); EventHandler.remove(this.parent.element.ownerDocument, 'mousedown', this.onDocumentClick); EventHandler.remove(this.contentModule.getEditPanel(), 'cut', this.onCutHandler); } } } private onIframeMouseDown(): void { if (this.dialogObj) { this.dialogObj.hide({ returnValue: true } as Event); } } private afterRender(): void { this.contentModule = this.rendererFactory.getRenderer(RenderType.Content); EventHandler.add(this.contentModule.getEditPanel(), Browser.touchEndEvent, this.imageClick, this); if (this.parent.insertImageSettings.resize) { EventHandler.add(this.parent.contentModule.getEditPanel(), Browser.touchStartEvent, this.resizeStart, this); EventHandler.add(this.parent.element.ownerDocument, 'mousedown', this.onDocumentClick, this); EventHandler.add(this.contentModule.getEditPanel(), 'cut', this.onCutHandler, this); } const dropElement: HTMLElement | Document = this.parent.iframeSettings.enable ? this.parent.inputElement.ownerDocument : this.parent.inputElement; dropElement.addEventListener('drop', this.dragDrop.bind(this), true); dropElement.addEventListener('dragstart', this.dragStart.bind(this), true); dropElement.addEventListener('dragenter', this.dragOver.bind(this), true); dropElement.addEventListener('dragover', this.dragOver.bind(this), true); } private undoStack(args?: { [key: string]: string }): void { if (args.subCommand.toLowerCase() === 'undo' || args.subCommand.toLowerCase() === 'redo') { for (let i: number = 0; i < this.parent.formatter.getUndoRedoStack().length; i++) { const temp: Element = this.parent.createElement('div'); const contentElem: DocumentFragment = parseHtml(this.parent.formatter.getUndoRedoStack()[i].text); temp.appendChild(contentElem); const img: NodeListOf<HTMLElement> = temp.querySelectorAll('img'); if (temp.querySelector('.e-img-resize') && img.length > 0) { for (let j: number = 0; j < img.length; j++) { img[j].style.outline = ''; } detach(temp.querySelector('.e-img-resize')); this.parent.formatter.getUndoRedoStack()[i].text = temp.innerHTML; } } } } private resizeEnd(e: PointerEvent | TouchEvent): void { this.resizeBtnInit(); this.imgEle.parentElement.style.cursor = 'auto'; if (Browser.isDevice) { removeClass([(e.target as HTMLElement).parentElement], 'e-mob-span'); } const args: ResizeArgs = { event: e, requestType: 'images' }; this.parent.trigger(events.resizeStop, args); /* eslint-disable */ let pageX: number = this.getPointX(e); let pageY: number = (this.parent.iframeSettings.enable) ? window.pageYOffset + this.parent.element.getBoundingClientRect().top + (e as PointerEvent).clientY : (e as PointerEvent).pageY; /* eslint-enable */ this.parent.formatter.editorManager.observer.on(events.checkUndo, this.undoStack, this); this.parent.formatter.saveData(); } private resizeStart(e: PointerEvent | TouchEvent, ele?: Element): void { if (this.parent.readonly) { return; } const target: HTMLElement = ele ? ele as HTMLElement : e.target as HTMLElement; this.prevSelectedImgEle = this.imgEle; if ((target as HTMLElement).tagName === 'IMG') { this.parent.preventDefaultResize(e as MouseEvent); const img: HTMLImageElement = target as HTMLImageElement; if (this.imgResizeDiv && this.contentModule.getEditPanel().contains(this.imgResizeDiv)) { detach(this.imgResizeDiv); } this.imageResize(img); } if ((target as HTMLElement).classList.contains('e-rte-imageboxmark')) { if (this.parent.formatter.getUndoRedoStack().length === 0) { this.parent.formatter.saveData(); } this.pageX = this.getPointX(e); this.pageY = this.getPointY(e); e.preventDefault(); e.stopImmediatePropagation(); this.resizeBtnInit(); if (this.quickToolObj) { this.quickToolObj.imageQTBar.hidePopup(); } if ((target as HTMLElement).classList.contains('e-rte-topLeft')) { this.resizeBtnStat.topLeft = true; } if ((target as HTMLElement).classList.contains('e-rte-topRight')) { this.resizeBtnStat.topRight = true; } if ((target as HTMLElement).classList.contains('e-rte-botLeft')) { this.resizeBtnStat.botLeft = true; } if ((target as HTMLElement).classList.contains('e-rte-botRight')) { this.resizeBtnStat.botRight = true; } if (Browser.isDevice && this.contentModule.getEditPanel().contains(this.imgResizeDiv) && !this.imgResizeDiv.classList.contains('e-mob-span')) { addClass([this.imgResizeDiv], 'e-mob-span'); } else { const args: ResizeArgs = { event: e, requestType: 'images' }; this.parent.trigger(events.resizeStart, args, (resizeStartArgs: ResizeArgs) => { if (resizeStartArgs.cancel) { this.cancelResizeAction(); } }); } EventHandler.add(this.contentModule.getDocument(), Browser.touchEndEvent, this.resizeEnd, this); } } private imageClick(e: MouseEvent): void { if (Browser.isDevice) { if (((e.target as HTMLElement).tagName === 'IMG' && (e.target as HTMLElement).parentElement.tagName === 'A') || ((e.target as Element).tagName === 'IMG')) { this.contentModule.getEditPanel().setAttribute('contenteditable', 'false'); (e.target as HTMLElement).focus(); } else { if (!this.parent.readonly) { this.contentModule.getEditPanel().setAttribute('contenteditable', 'true'); } } } if ((e.target as HTMLElement).tagName === 'IMG' && (e.target as HTMLElement).parentElement.tagName === 'A') { e.preventDefault(); } } private onCutHandler(): void { if (this.imgResizeDiv && this.contentModule.getEditPanel().contains(this.imgResizeDiv)) { this.cancelResizeAction(); } } private imageResize(e: HTMLImageElement): void { this.resizeBtnInit(); this.imgEle = e; addClass([this.imgEle], 'e-resize'); this.imgResizeDiv = this.parent.createElement('span', { className: 'e-img-resize', id: this.rteID + '_imgResize' }); this.imgResizeDiv.appendChild(this.parent.createElement('span', { className: 'e-rte-imageboxmark e-rte-topLeft', styles: 'cursor: nwse-resize' })); this.imgResizeDiv.appendChild(this.parent.createElement('span', { className: 'e-rte-imageboxmark e-rte-topRight', styles: 'cursor: nesw-resize' })); this.imgResizeDiv.appendChild(this.parent.createElement('span', { className: 'e-rte-imageboxmark e-rte-botLeft', styles: 'cursor: nesw-resize' })); this.imgResizeDiv.appendChild(this.parent.createElement('span', { className: 'e-rte-imageboxmark e-rte-botRight', styles: 'cursor: nwse-resize' })); if (Browser.isDevice) { addClass([this.imgResizeDiv], 'e-mob-rte'); } e.style.outline = '2px solid #4a90e2'; this.imgResizePos(e, this.imgResizeDiv); this.resizeImgDupPos(e); this.contentModule.getEditPanel().appendChild(this.imgResizeDiv); EventHandler.add(this.contentModule.getDocument(), Browser.touchMoveEvent, this.resizing, this); } private getPointX(e: PointerEvent | TouchEvent): number { if ((e as TouchEvent).touches && (e as TouchEvent).touches.length) { return (e as TouchEvent).touches[0].pageX; } else { return (e as PointerEvent).pageX; } } private getPointY(e: PointerEvent | TouchEvent): number { if ((e as TouchEvent).touches && (e as TouchEvent).touches.length) { return (e as TouchEvent).touches[0].pageY; } else { return (e as PointerEvent).pageY; } } private imgResizePos(e: HTMLImageElement, imgResizeDiv: HTMLElement): void { const pos: OffsetPosition = this.calcPos(e); const top: number = pos.top; const left: number = pos.left; const imgWid: number = e.width; const imgHgt: number = e.height; const borWid: number = (Browser.isDevice) ? (4 * parseInt((e.style.outline.slice(-3)), 10)) + 2 : (2 * parseInt((e.style.outline.slice(-3)), 10)) + 2; //span border width + image outline width const devWid: number = ((Browser.isDevice) ? 0 : 2); // span border width (imgResizeDiv.querySelector('.e-rte-botLeft') as HTMLElement).style.left = (left - borWid) + 'px'; (imgResizeDiv.querySelector('.e-rte-botLeft') as HTMLElement).style.top = ((imgHgt - borWid) + top) + 'px'; (imgResizeDiv.querySelector('.e-rte-botRight') as HTMLElement).style.left = ((imgWid - (borWid - devWid)) + left) + 'px'; (imgResizeDiv.querySelector('.e-rte-botRight') as HTMLElement).style.top = ((imgHgt - borWid) + top) + 'px'; (imgResizeDiv.querySelector('.e-rte-topRight') as HTMLElement).style.left = ((imgWid - (borWid - devWid)) + left) + 'px'; (imgResizeDiv.querySelector('.e-rte-topRight') as HTMLElement).style.top = (top - (borWid)) + 'px'; (imgResizeDiv.querySelector('.e-rte-topLeft') as HTMLElement).style.left = (left - borWid) + 'px'; (imgResizeDiv.querySelector('.e-rte-topLeft') as HTMLElement).style.top = (top - borWid) + 'px'; } private calcPos(elem: HTMLElement): OffsetPosition { const ignoreOffset: string[] = ['TD', 'TH', 'TABLE', 'A']; let parentOffset: OffsetPosition = { top: 0, left: 0 }; const doc: Document = elem.ownerDocument; let offsetParent: Node = ((elem.offsetParent && (elem.offsetParent.classList.contains('e-img-caption') || ignoreOffset.indexOf(elem.offsetParent.tagName) > -1)) ? closest(elem, '#' + this.parent.getID() + '_rte-edit-view') : elem.offsetParent) || doc.documentElement; while (offsetParent && (offsetParent === doc.body || offsetParent === doc.documentElement) && (<HTMLElement>offsetParent).style.position === 'static') { offsetParent = offsetParent.parentNode; } if (offsetParent && offsetParent !== elem && offsetParent.nodeType === 1) { // eslint-disable-next-line parentOffset = (<HTMLElement>offsetParent).getBoundingClientRect(); } return { top: elem.offsetTop, left: elem.offsetLeft }; } private setAspectRatio(img: HTMLImageElement, expectedX: number, expectedY: number): void { if (isNullOrUndefined(img.width)) { return; } const width: number = img.style.width !== '' ? img.style.width.match(/^\d+(\.\d*)?%$/g) ? parseFloat(img.style.width) : parseInt(img.style.width, 10) : img.width; const height: number = img.style.height !== '' ? parseInt(img.style.height, 10) : img.height; if (width > height) { img.style.minWidth = '20px'; if (this.parent.insertImageSettings.resizeByPercent) { if (parseInt('' + img.getBoundingClientRect().width + '') !== 0 && parseInt('' + width + '') !== 0) { const percentageValue = this.pixToPerc((width / height * expectedY), (img.previousElementSibling || img.parentElement)); img.style.width = Math.min(Math.round((percentageValue / img.getBoundingClientRect().width) * expectedX * 100) / 100, 100) + '%'; } else { img.style.width = this.pixToPerc((width / height * expectedY), (img.previousElementSibling || img.parentElement)) + '%'; } img.style.height = null; img.removeAttribute('height'); } else if (img.style.width === '' && img.style.height !== '') { img.style.height = expectedY + 'px'; } else if (img.style.width !== '' && img.style.height === '') { img.style.width = ((width / height * expectedY) + width / height).toString() + 'px'; } else if (img.style.width !== '') { img.style.width = (width / height * expectedY) + 'px'; img.style.height = expectedY + 'px'; } else { img.setAttribute('width', ((width / height * expectedY) + width / height).toString()); } } else if (height > width) { if (this.parent.insertImageSettings.resizeByPercent) { if (parseInt('' + img.getBoundingClientRect().width + '') !== 0 && parseInt('' + width + '') !== 0) { img.style.width = Math.min(Math.round((width / img.getBoundingClientRect().width) * expectedX * 100) / 100, 100) + '%'; } else { img.style.width = this.pixToPerc((expectedX / height * expectedY), (img.previousElementSibling || img.parentElement)) + '%'; } img.style.height = null; img.removeAttribute('height'); } else if (img.style.width !== '') { img.style.width = expectedX + 'px'; img.style.height = (height / width * expectedX) + 'px'; } else { img.setAttribute('width', expectedX.toString()); } } else { if (this.parent.insertImageSettings.resizeByPercent) { img.style.width = this.pixToPerc(expectedX, (img.previousElementSibling || img.parentElement)) + '%'; img.style.height = null; img.removeAttribute('height'); } else if (img.style.width !== '') { img.style.width = expectedX + 'px'; img.style.height = expectedX + 'px'; } else { img.setAttribute('width', expectedX.toString()); img.setAttribute('height', expectedX.toString()); } } } private pixToPerc(expected: number, parentEle: Element): number { return expected / parseFloat(getComputedStyle(parentEle).width) * 100; } private imgDupMouseMove(width: string, height: string, e: PointerEvent | TouchEvent): void { const args: ResizeArgs = { event: e, requestType: 'images' }; this.parent.trigger(events.onResize, args, (resizingArgs: ResizeArgs) => { if (resizingArgs.cancel) { this.cancelResizeAction(); } else { if ((parseInt(this.parent.insertImageSettings.minWidth as string, 10) >= parseInt(width, 10) || (parseInt(this.parent.getInsertImgMaxWidth() as string, 10) <= parseInt(width, 10) && isNOU(this.imgEle.style.width)))) { return; } if (!this.parent.insertImageSettings.resizeByPercent && (parseInt(this.parent.insertImageSettings.minHeight as string, 10) >= parseInt(height, 10) || parseInt(this.parent.insertImageSettings.maxHeight as string, 10) <= parseInt(height, 10))) { return; } this.imgEle.parentElement.style.cursor = 'pointer'; this.setAspectRatio(this.imgEle, parseInt(width, 10), parseInt(height, 10)); this.resizeImgDupPos(this.imgEle); this.imgResizePos(this.imgEle, this.imgResizeDiv); this.parent.setContentHeight('', false); } }); } private resizing(e: PointerEvent | TouchEvent): void { if (this.imgEle.offsetWidth >= this.parent.getInsertImgMaxWidth()) { this.imgEle.style.maxHeight = this.imgEle.offsetHeight + 'px'; } const pageX: number = this.getPointX(e); const pageY: number = this.getPointY(e); const mouseX: number = (this.resizeBtnStat.botLeft || this.resizeBtnStat.topLeft) ? -(pageX - this.pageX) : (pageX - this.pageX); const mouseY: number = (this.resizeBtnStat.topLeft || this.resizeBtnStat.topRight) ? -(pageY - this.pageY) : (pageY - this.pageY); const width: number = parseInt(this.imgDupPos.width as string, 10) + mouseX; const height: number = parseInt(this.imgDupPos.height as string, 10) + mouseY; this.pageX = pageX; this.pageY = pageY; if (this.resizeBtnStat.botRight) { this.imgDupMouseMove(width + 'px', height + 'px', e); } else if (this.resizeBtnStat.botLeft) { this.imgDupMouseMove(width + 'px', height + 'px', e); } else if (this.resizeBtnStat.topRight) { this.imgDupMouseMove(width + 'px', height + 'px', e); } else if (this.resizeBtnStat.topLeft) { this.imgDupMouseMove(width + 'px', height + 'px', e); } } private cancelResizeAction(): void { EventHandler.remove(this.contentModule.getDocument(), Browser.touchMoveEvent, this.resizing); EventHandler.remove(this.contentModule.getDocument(), Browser.touchEndEvent, this.resizeEnd); if (this.imgEle && this.imgResizeDiv && this.contentModule.getEditPanel().contains(this.imgResizeDiv)) { detach(this.imgResizeDiv); (this.imgEle as HTMLElement).style.outline = ''; this.imgResizeDiv = null; this.pageX = null; this.pageY = null; } } private resizeImgDupPos(e: HTMLImageElement): void { this.imgDupPos = { width: (e.style.height !== '') ? this.imgEle.style.width : e.width + 'px', height: (e.style.height !== '') ? this.imgEle.style.height : e.height + 'px' }; } private resizeBtnInit(): { [key: string]: boolean } { return this.resizeBtnStat = { botLeft: false, botRight: false, topRight: false, topLeft: false }; } private onToolbarAction(args: NotifyArgs): void { if (isIDevice()) { this.parent.notify(events.selectionRestore, {}); } const item: IToolbarItemModel = (args.args as ClickEventArgs).item as IToolbarItemModel; switch (item.subCommand) { case 'Replace': if (this.parent.fileManagerSettings.enable) { this.parent.notify(events.renderFileManager, args); } else { this.parent.notify(events.insertImage, args); } break; case 'Caption': this.parent.notify(events.imageCaption, args); break; case 'InsertLink': this.parent.notify(events.imageLink, args); break; case 'AltText': this.parent.notify(events.imageAlt, args); break; case 'Remove': this.parent.notify(events.imageDelete, args); break; case 'Dimension': this.parent.notify(events.imageSize, args); break; case 'OpenImageLink': this.openImgLink(args); break; case 'EditImageLink': this.editImgLink(args); break; case 'RemoveImageLink': this.removeImgLink(args); break; } } private openImgLink(e: NotifyArgs): void { const target: string = (e.selectParent[0].parentNode as HTMLAnchorElement).target === '' ? '_self' : '_blank'; this.parent.formatter.process( this.parent, e.args, e.args, { url: (e.selectParent[0].parentNode as HTMLAnchorElement).href, target: target, selectNode: e.selectNode, subCommand: ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand }); } private editImgLink(e: NotifyArgs): void { const selectParentEle: HTMLElement = e.selectParent[0].parentNode as HTMLElement; const linkUpdate: string = this.i10n.getConstant('dialogUpdate'); const inputDetails: { [key: string]: string } = { url: (selectParentEle as HTMLAnchorElement).href, target: (selectParentEle as HTMLAnchorElement).target, header: 'Edit Link', btnText: linkUpdate }; this.insertImgLink(e, inputDetails); } private removeImgLink(e: NotifyArgs): void { if (Browser.isIE) { (this.contentModule.getEditPanel() as HTMLElement).focus(); } e.selection.restore(); const isCapLink: boolean = (this.contentModule.getEditPanel().contains(this.captionEle) && select('a', this.captionEle)) ? true : false; const selectParent: Node[] = isCapLink ? [this.captionEle] : [e.selectNode[0].parentElement]; this.parent.formatter.process( this.parent, e.args, e.args, { insertElement: e.selectNode[0] as HTMLElement, selectParent: selectParent, selection: e.selection, subCommand: ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand }); if (this.quickToolObj && document.body.contains(this.quickToolObj.imageQTBar.element)) { this.quickToolObj.imageQTBar.hidePopup(); if (!isNullOrUndefined(e.selectParent as Node[])) { removeClass([e.selectParent[0] as HTMLElement], 'e-img-focus'); } } if (isCapLink) { (select('.e-img-inner', this.captionEle) as HTMLElement).focus(); } } private onKeyDown(event: NotifyArgs): void { const originalEvent: KeyboardEventArgs = event.args as KeyboardEventArgs; let range: Range; let save: NodeSelection; let selectNodeEle: Node[]; let selectParentEle: Node[]; this.deletedImg = []; let isCursor: boolean; const keyCodeValues: number[] = [27, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 44, 45, 9, 16, 17, 18, 19, 20, 33, 34, 35, 36, 37, 38, 39, 40, 91, 92, 93, 144, 145, 182, 183]; if (this.parent.editorMode === 'HTML') { range = this.parent.formatter.editorManager.nodeSelection.getRange(this.parent.contentModule.getDocument()); isCursor = range.startContainer === range.endContainer && range.startOffset === range.endOffset; } if (!isCursor && this.parent.editorMode === 'HTML' && keyCodeValues.indexOf(originalEvent.which) < 0) { const nodes: Node[] = this.parent.formatter.editorManager.nodeSelection.getNodeCollection(range); for (let i: number = 0; i < nodes.length; i++) { if (nodes[i].nodeName === 'IMG') { this.deletedImg.push(nodes[i]); } } } if (this.parent.editorMode === 'HTML' && ((originalEvent.which === 8 && originalEvent.code === 'Backspace') || (originalEvent.which === 46 && originalEvent.code === 'Delete'))) { const isCursor: boolean = range.startContainer === range.endContainer && range.startOffset === range.endOffset; if ((originalEvent.which === 8 && originalEvent.code === 'Backspace' && isCursor)) { this.checkImageBack(range); } else if ((originalEvent.which === 46 && originalEvent.code === 'Delete' && isCursor)) { this.checkImageDel(range); } } if (!isNullOrUndefined(this.parent.formatter.editorManager.nodeSelection) && originalEvent.code !== 'KeyK') { range = this.parent.formatter.editorManager.nodeSelection.getRange(this.parent.contentModule.getDocument()); save = this.parent.formatter.editorManager.nodeSelection.save(range, this.parent.contentModule.getDocument()); selectNodeEle = this.parent.formatter.editorManager.nodeSelection.getNodeCollection(range); selectParentEle = this.parent.formatter.editorManager.nodeSelection.getParentNodeCollection(range); if (!originalEvent.ctrlKey && originalEvent.key && (originalEvent.key.length === 1 || originalEvent.action === 'enter') && ((selectParentEle[0] as HTMLElement).tagName === 'IMG') && (selectParentEle[0] as HTMLElement).parentElement) { const prev: Node = ((selectParentEle[0] as HTMLElement).parentElement as HTMLElement).childNodes[0]; if (this.contentModule.getEditPanel().querySelector('.e-img-resize')) { this.removeResizeEle(); } this.parent.formatter.editorManager.nodeSelection.setSelectionText( this.contentModule.getDocument(), prev, prev, prev.textContent.length, prev.textContent.length); removeClass([selectParentEle[0] as HTMLElement], 'e-img-focus'); this.quickToolObj.imageQTBar.hidePopup(); } } if (originalEvent.ctrlKey && (originalEvent.keyCode === 89 || originalEvent.keyCode === 90)) { this.undoStack({ subCommand: (originalEvent.keyCode === 90 ? 'undo' : 'redo') }); } if (originalEvent.keyCode === 8 || originalEvent.keyCode === 46) { if (selectNodeEle && selectNodeEle[0].nodeName === 'IMG' && selectNodeEle.length < 1) { originalEvent.preventDefault(); const event: IImageNotifyArgs = { selectNode: selectNodeEle, selection: save, selectParent: selectParentEle, args: { item: { command: 'Images', subCommand: 'Remove' } as IToolbarItemModel, originalEvent: originalEvent } }; this.deleteImg(event, originalEvent.keyCode); } if (this.parent.contentModule.getEditPanel().querySelector('.e-img-resize')) { this.removeResizeEle(); } } if (originalEvent.code === 'Backspace') { originalEvent.action = 'backspace'; } switch (originalEvent.action) { case 'escape': if (!isNullOrUndefined(this.dialogObj)) { this.dialogObj.close(); } break; case 'backspace': case 'delete': for (let i: number = 0; i < this.deletedImg.length; i++) { const src: string = (this.deletedImg[i] as HTMLImageElement).src; this.imageRemovePost(src as string); } break; case 'insert-image': this.openDialog(true, originalEvent, save, selectNodeEle, selectParentEle); originalEvent.preventDefault(); break; } } private openDialog(isInternal?: boolean, event?: KeyboardEventArgs, selection?: NodeSelection, ele?: Node[], parentEle?: Node[]): void { let range: Range; let save: NodeSelection; let selectNodeEle: Node[]; let selectParentEle: Node[]; if (!isInternal && !isNOU(this.parent.formatter.editorManager.nodeSelection)) { range = this.parent.formatter.editorManager.nodeSelection.getRange(this.parent.contentModule.getDocument()); save = this.parent.formatter.editorManager.nodeSelection.save( range, this.parent.contentModule.getDocument()); selectNodeEle = this.parent.formatter.editorManager.nodeSelection.getNodeCollection(range); selectParentEle = this.parent.formatter.editorManager.nodeSelection.getParentNodeCollection(range); } else { save = selection; selectNodeEle = ele; selectParentEle = parentEle; } if (this.parent.editorMode === 'HTML') { this.insertImage({ args: { item: { command: 'Images', subCommand: 'Image' } as IToolbarItemModel, originalEvent: event }, selectNode: selectNodeEle, selection: save, selectParent: selectParentEle }); } else { this.insertImage({ args: { item: { command: 'Images', subCommand: 'Image' } as IToolbarItemModel, originalEvent: event }, member: 'image', text: this.parent.formatter.editorManager.markdownSelection.getSelectedText( this.parent.contentModule.getEditPanel() as HTMLTextAreaElement), module: 'Markdown', name: 'insertImage' }); } } private showDialog(): void { this.openDialog(false); } private closeDialog(): void { if (this.dialogObj) { this.dialogObj.hide({ returnValue: true } as Event); } } // eslint-disable-next-line private onKeyUp(event: NotifyArgs): void { if (!isNOU(this.deletedImg) && this.deletedImg.length > 0) { for (let i: number = 0; i < this.deletedImg.length; i++) { const args: AfterImageDeleteEventArgs = { element: this.deletedImg[i], src: (this.deletedImg[i] as HTMLElement).getAttribute('src') }; this.parent.trigger(events.afterImageDelete, args); } } } private checkImageBack(range: Range): void { if (range.startContainer.nodeName === '#text' && range.startOffset === 0 && !isNOU(range.startContainer.previousSibling) && range.startContainer.previousSibling.nodeName === 'IMG') { this.deletedImg.push(range.startContainer.previousSibling); } else if (range.startContainer.nodeName !== '#text' && !isNOU(range.startContainer.childNodes[range.startOffset - 1]) && range.startContainer.childNodes[range.startOffset - 1].nodeName === 'IMG') { this.deletedImg.push(range.startContainer.childNodes[range.startOffset - 1]); } } private checkImageDel(range: Range): void { if (range.startContainer.nodeName === '#text' && range.startOffset === range.startContainer.textContent.length && !isNOU(range.startContainer.nextSibling) && range.startContainer.nextSibling.nodeName === 'IMG') { this.deletedImg.push(range.startContainer.nextSibling); } else if (range.startContainer.nodeName !== '#text' && !isNOU(range.startContainer.childNodes[range.startOffset]) && range.startContainer.childNodes[range.startOffset].nodeName === 'IMG') { this.deletedImg.push(range.startContainer.childNodes[range.startOffset]); } } private alignmentSelect(e: ClickEventArgs): void { const item: IDropDownItemModel = e.item as IDropDownItemModel; if (!document.body.contains(document.body.querySelector('.e-rte-quick-toolbar')) || item.command !== 'Images') { return; } const range: Range = this.parent.formatter.editorManager.nodeSelection.getRange(this.parent.contentModule.getDocument()); let selectNodeEle: Node[] = this.parent.formatter.editorManager.nodeSelection.getNodeCollection(range); selectNodeEle = (selectNodeEle[0].nodeName === 'IMG') ? selectNodeEle : [this.imgEle]; const args: IImageNotifyArgs = { args: e, selectNode: selectNodeEle }; if (this.parent.formatter.getUndoRedoStack().length === 0) { this.parent.formatter.saveData(); } switch (item.subCommand) { case 'JustifyLeft': this.alignImage(args, 'JustifyLeft'); break; case 'JustifyCenter': this.alignImage(args, 'JustifyCenter'); break; case 'JustifyRight': this.alignImage(args, 'JustifyRight'); break; case 'Inline': this.inline(args); break; case 'Break': this.break(args); break; } if (this.quickToolObj && document.body.contains(this.quickToolObj.imageQTBar.element)) { this.quickToolObj.imageQTBar.hidePopup(); removeClass([selectNodeEle[0] as HTMLElement], 'e-img-focus'); } this.cancelResizeAction(); } private imageWithLinkQTBarItemUpdate(): void { let separator: HTMLElement; const items: NodeListOf<Element> = this.quickToolObj.imageQTBar.toolbarElement.querySelectorAll('.e-toolbar-item'); for (let i: number = 0; i < items.length; i++) { if (items[i].getAttribute('title') === this.i10n.getConstant('openLink') || items[i].getAttribute('title') === this.i10n.getConstant('editLink') || items[i].getAttribute('title') === this.i10n.getConstant('removeLink')) { addClass([items[i]], 'e-link-groups'); (items[i] as HTMLElement).style.display = 'none'; } else if (items[i].getAttribute('title') === 'Insert Link') { (items[i] as HTMLElement).style.display = ''; } else if (items[i].classList.contains('e-rte-horizontal-separator')) { // eslint-disable-next-line separator = items[i] as HTMLElement; detach(items[i]); } } const newItems: NodeListOf<Element> = this.quickToolObj.imageQTBar.toolbarElement.querySelectorAll( '.e-toolbar-item:not(.e-link-groups)'); this.quickToolObj.imageQTBar.addQTBarItem(['-'], Math.round(newItems.length / 2)); } private showImageQuickToolbar(e: IShowPopupArgs): void { if (e.type !== 'Images' || isNullOrUndefined(this.parent.quickToolbarModule) || isNullOrUndefined(this.parent.quickToolbarModule.imageQTBar) || isNullOrUndefined(e.args)) { return; } this.quickToolObj = this.parent.quickToolbarModule; const args: MouseEvent = e.args as MouseEvent; let target: HTMLElement = e.elements as HTMLElement; [].forEach.call(e.elements, (element: Element, index: number) => { if (index === 0) { target = <HTMLElement>element; } }); if (target && !closest(target, 'a')) { this.imageWithLinkQTBarItemUpdate(); } if (target.nodeName === 'IMG') { addClass([target], ['e-img-focus']); } const pageY: number = (this.parent.iframeSettings.enable) ? window.pageYOffset + this.parent.element.getBoundingClientRect().top + args.clientY : args.pageY; if (this.parent.quickToolbarModule.imageQTBar) { if (e.isNotify) { setTimeout(() => { this.quickToolObj.imageQTBar.showPopup(args.pageX, pageY, target as Element); }, 400); } else { this.quickToolObj.imageQTBar.showPopup(args.pageX, pageY, target as Element); } } } private hideImageQuickToolbar(): void { if (!isNullOrUndefined(this.contentModule.getEditPanel().querySelector('.e-img-focus'))) { removeClass([this.contentModule.getEditPanel().querySelector('.e-img-focus')], 'e-img-focus'); if (this.quickToolObj && this.quickToolObj.imageQTBar && document.body.contains(this.quickToolObj.imageQTBar.element)) { this.quickToolObj.imageQTBar.hidePopup(); } } } private editAreaClickHandler(e: IImageNotifyArgs): void { if (this.parent.readonly) { this.hideImageQuickToolbar(); return; } const args: MouseEvent = e.args as MouseEvent; const showOnRightClick: boolean = this.parent.quickToolbarSettings.showOnRightClick; if (args.which === 2 || (showOnRightClick && args.which === 1) || (!showOnRightClick && args.which === 3)) { if ((showOnRightClick && args.which === 1) && !isNullOrUndefined((args.target as HTMLElement)) && (args.target as HTMLElement).tagName === 'IMG') { this.parent.formatter.editorManager.nodeSelection.Clear(this.contentModule.getDocument()); this.parent.formatter.editorManager.nodeSelection.setSelectionContents( this.contentModule.getDocument(), args.target as Node); } return; } if (this.parent.editorMode === 'HTML' && this.parent.quickToolbarModule && this.parent.quickToolbarModule.imageQTBar) { this.quickToolObj = this.parent.quickToolbarModule; const target: HTMLElement = args.target as HTMLElement; this.contentModule = this.rendererFactory.getRenderer(RenderType.Content); const isPopupOpen: boolean = this.quickToolObj.imageQTBar.element.classList.contains('e-rte-pop'); if (target.nodeName === 'IMG' && this.parent.quickToolbarModule) { if (isPopupOpen) { return; } this.parent.formatter.editorManager.nodeSelection.Clear(this.contentModule.getDocument()); this.parent.formatter.editorManager.nodeSelection.setSelectionContents(this.contentModule.getDocument(), target); if (isIDevice()) { this.parent.notify(events.selectionSave, e); } addClass([target], 'e-img-focus'); const items: NodeListOf<Element> = this.quickToolObj.imageQTBar.toolbarElement.querySelectorAll('.e-toolbar-item'); let separator: HTMLElement; if (closest(target, 'a')) { for (let i: number = 0; i < items.length; i++) { if (items[i].getAttribute('title') === this.i10n.getConstant('openLink') || items[i].getAttribute('title') === this.i10n.getConstant('editLink') || items[i].getAttribute('title') === this.i10n.getConstant('removeLink')) { (items[i] as HTMLElement).style.display = ''; removeClass([items[i]], 'e-link-groups'); } else if (items[i].getAttribute('title') === 'Insert Link') { (items[i] as HTMLElement).style.display = 'none'; } else if (items[i].classList.contains('e-rte-horizontal-separator')) { // eslint-disable-next-line separator = items[i] as HTMLElement; detach(items[i]); } } const newItems: NodeListOf<Element> = this.quickToolObj.imageQTBar.toolbarElement.querySelectorAll( '.e-toolbar-item:not(.e-link-groups)'); this.quickToolObj.imageQTBar.addQTBarItem(['-'], Math.round(newItems.length / 2)); } else if (!closest(target, 'a')) { this.imageWithLinkQTBarItemUpdate(); } this.showImageQuickToolbar({ args: args, type: 'Images', elements: [args.target as Element] } as IShowPopupArgs); } else { this.hideImageQuickToolbar(); } } } private insertImgLink(e: IImageNotifyArgs, inputDetails?: { [key: string]: string }): void { if (e.selectNode[0].nodeName !== 'IMG') { return; } this.imagDialog(e); if (!isNullOrUndefined(this.dialogObj)) { const linkWrap: HTMLElement = this.parent.createElement('div', { className: 'e-img-linkwrap' }); const linkUrl: string = this.i10n.getConstant('linkurl'); const content: string = '<div class="e-rte-field">' + '<input type="text" data-role ="none" class="e-input e-img-link" spellcheck="false" placeholder="' + linkUrl + '"/></div>' + '<div class="e-rte-label"></div>' + '<div class="e-rte-field">' + '<input type="checkbox" class="e-rte-linkTarget" data-role ="none"></div>'; const contentElem: DocumentFragment = parseHtml(content); linkWrap.appendChild(contentElem); const linkTarget: HTMLInputElement = linkWrap.querySelector('.e-rte-linkTarget') as HTMLInputElement; const inputLink: HTMLElement = linkWrap.querySelector('.e-img-link') as HTMLElement; const linkOpenLabel: string = this.i10n.getConstant('linkOpenInNewWindow'); this.checkBoxObj = new CheckBox({ label: linkOpenLabel, checked: true, enableRtl: this.parent.enableRtl, change: (e: ChangeEventArgs) => { if (e.checked) { target = '_blank'; } else { target = null; } } }); this.checkBoxObj.isStringTemplate = true; this.checkBoxObj.createElement = this.parent.createElement; this.checkBoxObj.appendTo(linkTarget); let target: string = this.checkBoxObj.checked ? '_blank' : null; const linkUpdate: string = this.i10n.getConstant('dialogUpdate'); const linkargs: IImageNotifyArgs = { args: e.args, selfImage: this, selection: e.selection, selectNode: e.selectNode, selectParent: e.selectParent, link: inputLink, target: target }; this.dialogObj.setProperties({ height: 'inherit', width: '290px', header: this.parent.localeObj.getConstant('imageInsertLinkHeader'), content: linkWrap, position: { X: 'center', Y: 'center' }, buttons: [{ // eslint-disable-next-line click: (e: MouseEvent) => { this.insertlink(linkargs); }, buttonModel: { content: linkUpdate, cssClass: 'e-flat e-update-link', isPrimary: true } }] }); if (!isNullOrUndefined(inputDetails)) { (inputLink as HTMLInputElement).value = inputDetails.url; // eslint-disable-next-line (inputDetails.target) ? this.checkBoxObj.checked = true : this.checkBoxObj.checked = false; this.dialogObj.header = inputDetails.header; } this.dialogObj.element.style.maxHeight = 'inherit'; (this.dialogObj.content as HTMLElement).querySelector('input').focus(); } } private insertAltText(e: IImageNotifyArgs): void { if (e.selectNode[0].nodeName !== 'IMG') { return; } this.imagDialog(e); const altText: string = this.i10n.getConstant('altText'); if (!isNullOrUndefined(this.dialogObj)) { const altWrap: HTMLElement = this.parent.createElement('div', { className: 'e-img-altwrap' }); const altHeader: string = this.i10n.getConstant('alternateHeader'); const linkUpdate: string = this.i10n.getConstant('dialogUpdate'); const getAlt: string = ((e.selectNode[0] as HTMLElement).getAttribute('alt') === null) ? '' : (e.selectNode[0] as HTMLElement).getAttribute('alt'); const content: string = '<div class="e-rte-field">' + '<input type="text" spellcheck="false" value="' + getAlt + '" class="e-input e-img-alt" placeholder="' + altText + '"/>' + '</div>'; const contentElem: DocumentFragment = parseHtml(content); altWrap.appendChild(contentElem); const inputAlt: HTMLElement = altWrap.querySelector('.e-img-alt') as HTMLElement; const altArgs: IImageNotifyArgs = { args: e.args, selfImage: this, selection: e.selection, selectNode: e.selectNode, alt: inputAlt }; this.dialogObj.setProperties({ height: 'inherit', width: '290px', header: altHeader, content: altWrap, position: { X: 'center', Y: 'center' }, buttons: [{ // eslint-disable-next-line click: (e: MouseEvent) => { this.insertAlt(altArgs); }, buttonModel: { content: linkUpdate, cssClass: 'e-flat e-update-alt', isPrimary: true } }] }); this.dialogObj.element.style.maxHeight = 'inherit'; (this.dialogObj.content as HTMLElement).querySelector('input').focus(); } } private insertAlt(e: IImageNotifyArgs): void { if (!isNullOrUndefined(e.alt)) { e.selection.restore(); if (this.parent.formatter.getUndoRedoStack().length === 0) { this.parent.formatter.saveData(); } const altText: string = (e.alt as HTMLInputElement).value; this.parent.formatter.process( this.parent, e.args, e.args, { altText: altText, selectNode: e.selectNode, subCommand: ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand }); this.dialogObj.hide({ returnValue: false } as Event); } } private insertlink(e: IImageNotifyArgs): void { if (e.selectNode[0].nodeName !== 'IMG') { return; } let url: string = (e.link as HTMLInputElement).value; if (url === '') { addClass([e.link], 'e-error'); (e.link as HTMLInputElement).setSelectionRange(0, url.length); (e.link as HTMLInputElement).focus(); return; } if (!this.isUrl(url)) { url = 'http://' + url; } else { removeClass([e.link], 'e-error'); } const proxy: Image = e.selfImage; if (proxy.parent.editorMode === 'HTML') { e.selection.restore(); } if (proxy.parent.formatter.getUndoRedoStack().length === 0) { proxy.parent.formatter.saveData(); } if (e.selectNode[0].parentElement.nodeName === 'A') { proxy.parent.formatter.process( proxy.parent, e.args, e.args, { url: url, target: proxy.checkBoxObj.checked ? '_blank' : null, selectNode: e.selectNode, subCommand: ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand }); proxy.dialogObj.hide({ returnValue: true } as Event); return; } proxy.parent.formatter.process( proxy.parent, e.args, e.args, { url: url, target: proxy.checkBoxObj.checked ? '_blank' : null, selectNode: e.selectNode, subCommand: ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand, selection: e.selection }); const captionEle: Element = closest(e.selectNode[0], '.e-img-caption'); if (captionEle) { (select('.e-img-inner', captionEle) as HTMLElement).focus(); } if (captionEle) { (select('.e-img-inner', captionEle) as HTMLElement).focus(); } proxy.dialogObj.hide({ returnValue: false } as Event); } private isUrl(url: string): boolean { // eslint-disable-next-line const regexp: RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi; return regexp.test(url); } private deleteImg(e: IImageNotifyArgs, keyCode?: number): void { if (e.selectNode[0].nodeName !== 'IMG') { return; } const args: AfterImageDeleteEventArgs = { element: e.selectNode[0], src: (e.selectNode[0] as HTMLElement).getAttribute('src') }; if (this.parent.formatter.getUndoRedoStack().length === 0) { this.parent.formatter.saveData(); } e.selection.restore(); if (this.contentModule.getEditPanel().querySelector('.e-img-resize')) { this.removeResizeEle(); } this.parent.formatter.process( this.parent, e.args, e.args, { selectNode: e.selectNode, captionClass: classes.CLS_CAPTION, subCommand: ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand }); this.imageRemovePost(args.src as string); if (this.quickToolObj && document.body.contains(this.quickToolObj.imageQTBar.element)) { this.quickToolObj.imageQTBar.hidePopup(); } this.cancelResizeAction(); if (isNullOrUndefined(keyCode)) { this.parent.trigger(events.afterImageDelete, args); } } private imageRemovePost(src: string): void { const removeUrl: string = this.parent.insertImageSettings.removeUrl; if (isNOU(removeUrl) || removeUrl === '') { return; } const ajax: Ajax = new Ajax(removeUrl, 'POST', true, null); const formData: FormData = new FormData(); formData.append(name, src as string); ajax.send(formData); } private caption(e: IImageNotifyArgs): void { const selectNode: HTMLElement = e.selectNode[0] as HTMLElement; if (selectNode.nodeName !== 'IMG') { return; } e.selection.restore(); if (this.parent.formatter.getUndoRedoStack().length === 0) { this.parent.formatter.saveData(); } this.cancelResizeAction(); addClass([selectNode], 'e-rte-image'); const subCommand: string = ((e.args as ClickEventArgs).item) ? ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand : 'Caption'; if (!isNullOrUndefined(closest(selectNode, '.' + classes.CLS_CAPTION))) { detach(closest(selectNode, '.' + classes.CLS_CAPTION)); if (Browser.isIE) { (this.contentModule.getEditPanel() as HTMLElement).focus(); e.selection.restore(); } if (selectNode.parentElement.tagName === 'A') { this.parent.formatter.process( this.parent, e.args, e.args, { insertElement: selectNode.parentElement, selectNode: e.selectNode, subCommand: subCommand }); } else { this.parent.formatter.process( this.parent, e.args, e.args, { insertElement: selectNode, selectNode: e.selectNode, subCommand: subCommand }); } } else { this.captionEle = this.parent.createElement('span', { className: classes.CLS_CAPTION + ' ' + classes.CLS_RTE_CAPTION, attrs: { contenteditable: 'false', draggable: 'false', style: 'width:' + this.parent.insertImageSettings.width } }); const imgWrap: HTMLElement = this.parent.createElement('span', { className: 'e-img-wrap' }); const imgInner: HTMLElement = this.parent.createElement('span', { className: 'e-img-inner', attrs: { contenteditable: 'true' } }); const parent: HTMLElement = e.selectNode[0].parentElement; if (parent.tagName === 'A') { parent.setAttribute('contenteditable', 'true'); } imgWrap.appendChild(parent.tagName === 'A' ? parent : e.selectNode[0]); imgWrap.appendChild(imgInner); const imgCaption: string = this.i10n.getConstant('imageCaption'); imgInner.innerHTML = imgCaption; this.captionEle.appendChild(imgWrap); if (selectNode.classList.contains(classes.CLS_IMGINLINE)) { addClass([this.captionEle], classes.CLS_CAPINLINE); } if (selectNode.classList.contains(classes.CLS_IMGBREAK)) { addClass([this.captionEle], classes.CLS_IMGBREAK); } if (selectNode.classList.contains(classes.CLS_IMGLEFT)) { addClass([this.captionEle], classes.CLS_IMGLEFT); } if (selectNode.classList.contains(classes.CLS_IMGRIGHT)) { addClass([this.captionEle], classes.CLS_IMGRIGHT); } if (selectNode.classList.contains(classes.CLS_IMGCENTER)) { addClass([this.captionEle], classes.CLS_IMGCENTER); } this.parent.formatter.process( this.parent, e.args, e.args, { insertElement: this.captionEle, selectNode: e.selectNode, subCommand: subCommand }); this.parent.formatter.editorManager.nodeSelection.setSelectionText( this.contentModule.getDocument(), imgInner.childNodes[0], imgInner.childNodes[0], 0, imgInner.childNodes[0].textContent.length); } if (this.quickToolObj && document.body.contains(this.quickToolObj.imageQTBar.element)) { this.quickToolObj.imageQTBar.hidePopup(); removeClass([selectNode as HTMLElement], 'e-img-focus'); } } private imageSize(e: IImageNotifyArgs): void { if (e.selectNode[0].nodeName !== 'IMG') { return; } this.imagDialog(e); if (!isNullOrUndefined(this.dialogObj)) { const imgSizeHeader: string = this.i10n.getConstant('imageSizeHeader'); const linkUpdate: string = this.i10n.getConstant('dialogUpdate'); const dialogContent: HTMLElement = this.imgsizeInput(e); const selectObj: IImageNotifyArgs = { args: e.args, selfImage: this, selection: e.selection, selectNode: e.selectNode }; this.dialogObj.setProperties({ height: 'inherit', width: '290px', header: imgSizeHeader, content: dialogContent, position: { X: 'center', Y: 'center' }, buttons: [{ // eslint-disable-next-line click: (e: MouseEvent) => { this.insertSize(selectObj); }, buttonModel: { content: linkUpdate, cssClass: 'e-flat e-update-size', isPrimary: true } }] }); this.dialogObj.element.style.maxHeight = 'inherit'; (this.dialogObj.content as HTMLElement).querySelector('input').focus(); } } private break(e: IImageNotifyArgs): void { if (e.selectNode[0].nodeName !== 'IMG') { return; } const subCommand: string = ((e.args as ClickEventArgs).item) ? ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand : 'Break'; this.parent.formatter.process(this.parent, e.args, e.args, { selectNode: e.selectNode, subCommand: subCommand }); } private inline(e: IImageNotifyArgs): void { if (e.selectNode[0].nodeName !== 'IMG') { return; } const subCommand: string = ((e.args as ClickEventArgs).item) ? ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand : 'Inline'; this.parent.formatter.process(this.parent, e.args, e.args, { selectNode: e.selectNode, subCommand: subCommand }); } private alignImage(e: IImageNotifyArgs, type: string): void { const subCommand: string = ((e.args as ClickEventArgs).item) ? ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand : type; this.parent.formatter.process(this.parent, e.args, e.args, { selectNode: e.selectNode, subCommand: subCommand }); } private clearDialogObj(): void { if (this.dialogObj) { this.dialogObj.destroy(); detach(this.dialogObj.element); this.dialogObj = null; } } private imagDialog(e: IImageNotifyArgs): void { if (this.dialogObj) { this.dialogObj.hide({ returnValue: true } as Event); return; } const imgDialog: HTMLElement = this.parent.createElement('div', { className: 'e-rte-img-dialog', id: this.rteID + '_image' }); this.parent.element.appendChild(imgDialog); const imgInsert: string = this.i10n.getConstant('dialogInsert'); const imglinkCancel: string = this.i10n.getConstant('dialogCancel'); const imgHeader: string = this.i10n.getConstant('imageHeader'); const selection: NodeSelection = e.selection; const selectObj: IImageNotifyArgs = { selfImage: this, selection: e.selection, args: e.args, selectParent: e.selectParent }; const dialogModel: DialogModel = { header: imgHeader, cssClass: classes.CLS_RTE_ELEMENTS, enableRtl: this.parent.enableRtl, locale: this.parent.locale, showCloseIcon: true, closeOnEscape: true, width: (Browser.isDevice) ? '290px' : '340px', height: 'inherit', position: { X: 'center', Y: (Browser.isDevice) ? 'center' : 'top' }, isModal: (Browser.isDevice as boolean), buttons: [{ click: this.insertImageUrl.bind(selectObj), buttonModel: { content: imgInsert, cssClass: 'e-flat e-insertImage', isPrimary: true, disabled: true } }, { click: (e: MouseEvent) => { this.cancelDialog(e); }, buttonModel: { cssClass: 'e-flat e-cancel', content: imglinkCancel } }], target: (Browser.isDevice) ? document.body : this.parent.element, animationSettings: { effect: 'None' }, close: (event: { [key: string]: object }) => { if (this.isImgUploaded) { this.uploadObj.removing(); } this.parent.isBlur = false; if (event && (event.event as { [key: string]: string }).returnValue) { if (this.parent.editorMode === 'HTML') { selection.restore(); } else { this.parent.formatter.editorManager.markdownSelection.restore( this.parent.contentModule.getEditPanel() as HTMLTextAreaElement); } } this.dialogObj.destroy(); detach(this.dialogObj.element); this.dialogRenderObj.close(event); this.dialogObj = null; } }; const dialogContent: HTMLElement = this.parent.createElement('div', { className: 'e-img-content' }); if ((!isNullOrUndefined(this.parent.insertImageSettings.path) && this.parent.editorMode === 'Markdown') || this.parent.editorMode === 'HTML') { dialogContent.appendChild(this.imgUpload(e)); } const linkHeader: HTMLElement = this.parent.createElement('div', { className: 'e-linkheader' }); const linkHeaderText: string = this.i10n.getConstant('imageLinkHeader'); if (this.parent.editorMode === 'HTML') { linkHeader.innerHTML = linkHeaderText; } else { linkHeader.innerHTML = this.i10n.getConstant('mdimageLink'); } dialogContent.appendChild(linkHeader); dialogContent.appendChild(this.imageUrlPopup(e)); if (e.selectNode && e.selectNode[0].nodeName === 'IMG') { dialogModel.header = this.parent.localeObj.getConstant('editImageHeader'); dialogModel.content = dialogContent; } else { dialogModel.content = dialogContent; } this.dialogObj = this.dialogRenderObj.render(dialogModel); this.dialogObj.createElement = this.parent.createElement; this.dialogObj.appendTo(imgDialog); if (isNullOrUndefined(this.dialogObj)) { return; } if (e.selectNode && e.selectNode[0].nodeName === 'IMG' && (e.name === 'insertImage')) { this.dialogObj.element.querySelector('.e-insertImage').textContent = this.parent.localeObj.getConstant('dialogUpdate'); } imgDialog.style.maxHeight = 'inherit'; if (this.quickToolObj) { if (this.quickToolObj.imageQTBar && document.body.contains(this.quickToolObj.imageQTBar.element)) { this.quickToolObj.imageQTBar.hidePopup(); if (!isNullOrUndefined(e.selectParent as Node[])) { removeClass([e.selectParent[0] as HTMLElement], 'e-img-focus'); } } if (this.quickToolObj.inlineQTBar && document.body.contains(this.quickToolObj.inlineQTBar.element)) { this.quickToolObj.inlineQTBar.hidePopup(); } } } // eslint-disable-next-line private cancelDialog(e: MouseEvent): void { this.parent.isBlur = false; this.dialogObj.hide({ returnValue: true } as Event); if (this.isImgUploaded) { this.uploadObj.removing(); } } private onDocumentClick(e: MouseEvent): void { const target: HTMLElement = <HTMLElement>e.target; if (target.nodeName === 'IMG') { this.imgEle = target as HTMLImageElement; } if (!isNullOrUndefined(this.dialogObj) && (( // eslint-disable-next-line !closest(target, '[id=' + "'" + this.dialogObj.element.id + "'" + ']') && this.parent.toolbarSettings.enable && this.parent.getToolbarElement() && !this.parent.getToolbarElement().contains(e.target as Node)) || (this.parent.getToolbarElement() && this.parent.getToolbarElement().contains(e.target as Node) && !closest(target, '#' + this.parent.getID() + '_toolbar_Image') && !target.querySelector('#' + this.parent.getID() + '_toolbar_Image'))) ) { this.dialogObj.hide({ returnValue: true } as Event); this.parent.isBlur = true; dispatchEvent(this.parent.element, 'focusout'); } if ((e.target as HTMLElement).tagName !== 'IMG' && this.imgResizeDiv && !(this.quickToolObj && this.quickToolObj.imageQTBar && this.quickToolObj.imageQTBar.element.contains(e.target as HTMLElement)) && this.contentModule.getEditPanel().contains(this.imgResizeDiv)) { this.cancelResizeAction(); } if (this.contentModule.getEditPanel().querySelector('.e-img-resize')) { if (target.tagName !== 'IMG') { this.removeResizeEle(); } if (target.tagName !== 'IMG' && !isNOU(this.imgEle)) { this.imgEle.style.outline = ''; } else if (!isNOU(this.prevSelectedImgEle) && this.prevSelectedImgEle !== target) { this.prevSelectedImgEle.style.outline = ''; } } } private removeResizeEle(): void { EventHandler.remove(this.contentModule.getDocument(), Browser.touchMoveEvent, this.resizing); EventHandler.remove(this.contentModule.getDocument(), Browser.touchEndEvent, this.resizeEnd); detach(this.contentModule.getEditPanel().querySelector('.e-img-resize')); } private onWindowResize(): void { if (!isNOU(this.contentModule) && !isNOU(this.contentModule.getEditPanel().querySelector('.e-img-resize'))) { this.cancelResizeAction(); } } // eslint-disable-next-line private imageUrlPopup(e: IImageNotifyArgs): HTMLElement { const imgUrl: HTMLElement = this.parent.createElement('div', { className: 'imgUrl' }); const placeUrl: string = this.i10n.getConstant('imageUrl'); this.inputUrl = this.parent.createElement('input', { className: 'e-input e-img-url', attrs: { placeholder: placeUrl, spellcheck: 'false' } }); this.inputUrl.addEventListener('input', () => { if (!isNOU(this.inputUrl)) { if ((this.inputUrl as HTMLInputElement).value.length === 0) { (this.dialogObj.getButtons(0) as Button).element.disabled = true; } else { (this.dialogObj.getButtons(0) as Button).element.removeAttribute('disabled'); } } }); imgUrl.appendChild(this.inputUrl); return imgUrl; } // eslint-disable-next-line private insertImageUrl(e: MouseEvent): void { const proxy: Image = (this as IImageNotifyArgs).selfImage; proxy.isImgUploaded = false; const url: string = (proxy.inputUrl as HTMLInputElement).value; if (proxy.parent.formatter.getUndoRedoStack().length === 0) { proxy.parent.formatter.saveData(); } if (!isNullOrUndefined(proxy.uploadUrl) && proxy.uploadUrl.url !== '') { proxy.uploadUrl.cssClass = (proxy.parent.insertImageSettings.display === 'inline' ? classes.CLS_IMGINLINE : classes.CLS_IMGBREAK); proxy.dialogObj.hide({ returnValue: false } as Event); proxy.parent.formatter.process( proxy.parent, (this as IImageNotifyArgs).args, ((this as IImageNotifyArgs).args as ClickEventArgs).originalEvent, proxy.uploadUrl); proxy.uploadUrl.url = ''; if (proxy.contentModule.getEditPanel().querySelector('.e-img-resize')) { (proxy.imgEle as HTMLElement).style.outline = ''; proxy.removeResizeEle(); } } else if (url !== '') { if (proxy.parent.editorMode === 'HTML' && isNullOrUndefined( closest( // eslint-disable-next-line (this as IImageNotifyArgs).selection.range.startContainer.parentNode, '[id=' + "'" + proxy.contentModule.getPanel().id + "'" + ']'))) { (proxy.contentModule.getEditPanel() as HTMLElement).focus(); const range: Range = proxy.parent.formatter.editorManager.nodeSelection.getRange(proxy.contentModule.getDocument()); (this as IImageNotifyArgs).selection = proxy.parent.formatter.editorManager.nodeSelection.save( range, proxy.contentModule.getDocument()); (this as IImageNotifyArgs).selectParent = proxy.parent.formatter.editorManager.nodeSelection.getParentNodeCollection(range); } const regex: RegExp = /[\w-]+.(jpg|png|jpeg|gif)/g; const matchUrl: string = (!isNullOrUndefined(url.match(regex)) && proxy.parent.editorMode === 'HTML') ? url.match(regex)[0] : ''; const value: IImageCommandsArgs = { cssClass: (proxy.parent.insertImageSettings.display === 'inline' ? classes.CLS_IMGINLINE : classes.CLS_IMGBREAK), url: url, selection: (this as IImageNotifyArgs).selection, altText: matchUrl, selectParent: (this as IImageNotifyArgs).selectParent, width: { width: proxy.parent.insertImageSettings.width, minWidth: proxy.parent.insertImageSettings.minWidth, maxWidth: proxy.parent.getInsertImgMaxWidth() }, height: { height: proxy.parent.insertImageSettings.height, minHeight: proxy.parent.insertImageSettings.minHeight, maxHeight: proxy.parent.insertImageSettings.maxHeight } }; proxy.parent.formatter.process( proxy.parent, (this as IImageNotifyArgs).args, ((this as IImageNotifyArgs).args as ClickEventArgs).originalEvent, value); proxy.dialogObj.hide({ returnValue: false } as Event); } } private imgsizeInput(e: IImageNotifyArgs): HTMLElement { const selectNode: HTMLImageElement = (e as IImageNotifyArgs).selectNode[0] as HTMLImageElement; const imgHeight: string = this.i10n.getConstant('imageHeight'); const imgWidth: string = this.i10n.getConstant('imageWidth'); const imgSizeWrap: HTMLElement = this.parent.createElement('div', { className: 'e-img-sizewrap' }); const widthVal: string = isNullOrUndefined(this.changedWidthValue) && (selectNode.style.width.toString() === 'auto' || selectNode.style.width !== "") ? selectNode.style.width : !isNullOrUndefined(this.changedWidthValue) ? this.changedWidthValue : (parseInt(selectNode.getClientRects()[0].width.toString())).toString(); const heightVal: string = isNullOrUndefined(this.changedHeightValue) && (selectNode.style.height.toString() === 'auto' || selectNode.style.height !== "") ? selectNode.style.height : !isNullOrUndefined(this.changedHeightValue) ? this.changedHeightValue : (parseInt(selectNode.getClientRects()[0].height.toString())).toString(); this.changedWidthValue = null; this.changedHeightValue = null; const content: string = '<div class="e-rte-label"><label>' + imgWidth + '</label></div><div class="e-rte-field"><input type="text" id="imgwidth" class="e-img-width" value=' + widthVal + ' /></div>' + '<div class="e-rte-label">' + '<label>' + imgHeight + '</label></div><div class="e-rte-field"> ' + '<input type="text" id="imgheight" class="e-img-height" value=' + heightVal + ' /></div>'; const contentElem: DocumentFragment = parseHtml(content); imgSizeWrap.appendChild(contentElem); const widthNum: TextBox = new TextBox({ value: formatUnit(widthVal as string), enableRtl: this.parent.enableRtl, input: (e: InputEventArgs) => { this.inputWidthValue = formatUnit(this.inputValue(e.value)); } }); widthNum.createElement = this.parent.createElement; widthNum.appendTo(imgSizeWrap.querySelector('#imgwidth') as HTMLElement); const heightNum: TextBox = new TextBox({ value: formatUnit(heightVal as string), enableRtl: this.parent.enableRtl, input: (e: InputEventArgs) => { this.inputHeightValue = formatUnit(this.inputValue(e.value)); } }); heightNum.createElement = this.parent.createElement; heightNum.appendTo(imgSizeWrap.querySelector('#imgheight') as HTMLElement); return imgSizeWrap; } private inputValue(value: string): string { if (value === 'auto' || value.indexOf('%') !== -1 || value.indexOf('px') !== -1 || value.match(/(\d+)/)) { return value; } else { return "auto"; } } private insertSize(e: IImageNotifyArgs): void { e.selection.restore(); const proxy: Image = e.selfImage; if (proxy.parent.formatter.getUndoRedoStack().length === 0) { proxy.parent.formatter.saveData(); } const dialogEle: Element = proxy.dialogObj.element; this.changedWidthValue = this.inputWidthValue; this.changedHeightValue = this.inputHeightValue; const width: string = (dialogEle.querySelector('.e-img-width') as HTMLInputElement).value; const height: string = (dialogEle.parentElement.querySelector('.e-img-height') as HTMLInputElement).value; proxy.parent.formatter.process( this.parent, e.args, e.args, { width: width, height: height, selectNode: e.selectNode, subCommand: ((e.args as ClickEventArgs).item as IDropDownItemModel).subCommand }); if (this.imgResizeDiv) { proxy.imgResizePos(e.selectNode[0] as HTMLImageElement, this.imgResizeDiv); } proxy.dialogObj.hide({ returnValue: true } as Event); } private insertImage(e: IImageNotifyArgs): void { this.imagDialog(e); if (!isNullOrUndefined(this.dialogObj)) { this.dialogObj.element.style.maxHeight = 'inherit'; const dialogContent: HTMLElement = this.dialogObj.element.querySelector('.e-img-content'); if (((!isNullOrUndefined(this.parent.insertImageSettings.path) && this.parent.editorMode === 'Markdown') || this.parent.editorMode === 'HTML')) { (document.getElementById(this.rteID + '_insertImage') as HTMLElement).focus(); } else { (dialogContent.querySelector('.e-img-url') as HTMLElement).focus(); } } } private imgUpload(e: IImageNotifyArgs): HTMLElement { let save: NodeSelection; let selectParent: Node[]; // eslint-disable-next-line const proxy: this = this; const iframe: boolean = proxy.parent.iframeSettings.enable; if (proxy.parent.editorMode === 'HTML' && (!iframe && isNullOrUndefined(closest(e.selection.range.startContainer.parentNode, '[id=' // eslint-disable-next-line + "'" + this.parent.contentModule.getPanel().id + "'" + ']')) || (iframe && !hasClass(e.selection.range.startContainer.parentNode.ownerDocument.querySelector('body'), 'e-lib')))) { (this.contentModule.getEditPanel() as HTMLElement).focus(); const range: Range = this.parent.formatter.editorManager.nodeSelection.getRange(this.parent.contentModule.getDocument()); save = this.parent.formatter.editorManager.nodeSelection.save( range, this.parent.contentModule.getDocument()); selectParent = this.parent.formatter.editorManager.nodeSelection.getParentNodeCollection(range); } else { save = e.selection; selectParent = e.selectParent; } const uploadParentEle: HTMLElement = this.parent.createElement('div', { className: 'e-img-uploadwrap e-droparea' }); const deviceImgUpMsg: string = this.i10n.getConstant('imageDeviceUploadMessage'); const imgUpMsg: string = this.i10n.getConstant('imageUploadMessage'); const span: HTMLElement = this.parent.createElement('span', { className: 'e-droptext' }); const spanMsg: HTMLElement = this.parent.createElement('span', { className: 'e-rte-upload-text', innerHTML: ((Browser.isDevice) ? deviceImgUpMsg : imgUpMsg) }); span.appendChild(spanMsg); const btnEle: HTMLElement = this.parent.createElement('button', { className: 'e-browsebtn', id: this.rteID + '_insertImage', attrs: { autofocus: 'true', type: 'button' } }); span.appendChild(btnEle); uploadParentEle.appendChild(span); const browserMsg: string = this.i10n.getConstant('browse'); const button: Button = new Button({ content: browserMsg, enableRtl: this.parent.enableRtl }); button.isStringTemplate = true; button.createElement = this.parent.createElement; button.appendTo(btnEle); const btnClick: HTMLElement = (Browser.isDevice) ? span : btnEle; EventHandler.add(btnClick, 'click', this.fileSelect, this); const uploadEle: HTMLInputElement | HTMLElement = this.parent.createElement('input', { id: this.rteID + '_upload', attrs: { type: 'File', name: 'UploadFiles' } }); uploadParentEle.appendChild(uploadEle); let altText: string; let rawFile: FileInfo[]; let selectArgs: SelectedEventArgs; let filesData: FileInfo[]; let beforeUploadArgs: ImageUploadingEventArgs; this.uploadObj = new Uploader({ asyncSettings: { saveUrl: this.parent.insertImageSettings.saveUrl, removeUrl: this.parent.insertImageSettings.removeUrl }, dropArea: span, multiple: false, enableRtl: this.parent.enableRtl, allowedExtensions: this.parent.insertImageSettings.allowedTypes.toString(), selected: (e: SelectedEventArgs) => { proxy.isImgUploaded = true; selectArgs = e; filesData = e.filesData; if (this.parent.isServerRendered) { selectArgs = JSON.parse(JSON.stringify(e)); e.cancel = true; rawFile = e.filesData; selectArgs.filesData = rawFile; } this.parent.trigger(events.imageSelected, selectArgs, (selectArgs: SelectedEventArgs) => { if (!selectArgs.cancel) { this.checkExtension(selectArgs.filesData[0]); altText = selectArgs.filesData[0].name; if (this.parent.editorMode === 'HTML' && isNullOrUndefined(this.parent.insertImageSettings.path)) { const reader: FileReader = new FileReader(); // eslint-disable-next-line reader.addEventListener('load', (e: MouseEvent) => { const url: string = this.parent.insertImageSettings.saveFormat === 'Base64' ? reader.result as string : URL.createObjectURL(convertToBlob(reader.result as string)); proxy.uploadUrl = { url: url, selection: save, altText: altText, selectParent: selectParent, width: { width: proxy.parent.insertImageSettings.width, minWidth: proxy.parent.insertImageSettings.minWidth, maxWidth: proxy.parent.getInsertImgMaxWidth() }, height: { height: proxy.parent.insertImageSettings.height, minHeight: proxy.parent.insertImageSettings.minHeight, maxHeight: proxy.parent.insertImageSettings.maxHeight } }; proxy.inputUrl.setAttribute('disabled', 'true'); if (isNullOrUndefined(proxy.parent.insertImageSettings.saveUrl) && this.isAllowedTypes && !isNullOrUndefined(this.dialogObj)) { (this.dialogObj.getButtons(0) as Button).element.removeAttribute('disabled'); } }); reader.readAsDataURL(selectArgs.filesData[0].rawFile as Blob); } if (this.parent.isServerRendered) { /* eslint-disable */ (this.uploadObj as any)._internalRenderSelect(selectArgs, rawFile); /* eslint-enable */ } } }); }, beforeUpload: (args: BeforeUploadEventArgs) => { if (this.parent.isServerRendered) { beforeUploadArgs = JSON.parse(JSON.stringify(args)); beforeUploadArgs.filesData = filesData; args.cancel = true; this.parent.trigger(events.imageUploading, beforeUploadArgs, (beforeUploadArgs: ImageUploadingEventArgs) => { if (beforeUploadArgs.cancel) { return; } /* eslint-disable */ (this.uploadObj as any).currentRequestHeader = beforeUploadArgs.currentRequest ? beforeUploadArgs.currentRequest : (this.uploadObj as any).currentRequestHeader; (this.uploadObj as any).customFormDatas = beforeUploadArgs.customFormData && beforeUploadArgs.customFormData.length > 0 ? beforeUploadArgs.customFormData : (this.uploadObj as any).customFormDatas; (this.uploadObj as any).uploadFiles(rawFile, null); /* eslint-enable */ }); } else { this.parent.trigger(events.beforeImageUpload, args); } }, uploading: (e: UploadingEventArgs) => { if (!this.parent.isServerRendered) { this.parent.trigger(events.imageUploading, e); } }, success: (e: Object) => { this.parent.trigger(events.imageUploadSuccess, e, (e: object) => { if (!isNullOrUndefined(this.parent.insertImageSettings.path)) { const url: string = this.parent.insertImageSettings.path + (e as MetaData).file.name; // eslint-disable-next-line const value: IImageCommandsArgs = { url: url, selection: save }; proxy.uploadUrl = { url: url, selection: save, altText: altText, selectParent: selectParent, width: { width: proxy.parent.insertImageSettings.width, minWidth: proxy.parent.insertImageSettings.minWidth, maxWidth: proxy.parent.getInsertImgMaxWidth() }, height: { height: proxy.parent.insertImageSettings.height, minHeight: proxy.parent.insertImageSettings.minHeight, maxHeight: proxy.parent.insertImageSettings.maxHeight } }; proxy.inputUrl.setAttribute('disabled', 'true'); } if ((e as ProgressEventArgs).operation === 'upload' && !isNullOrUndefined(this.dialogObj)) { (this.dialogObj.getButtons(0) as Button).element.removeAttribute('disabled'); } }); }, failure: (e: object) => { this.parent.trigger(events.imageUploadFailed, e); }, removing: () => { // eslint-disable-next-line this.parent.trigger(events.imageRemoving, e, (e: RemovingEventArgs) => { proxy.isImgUploaded = false; (this.dialogObj.getButtons(0) as Button).element.disabled = true; proxy.inputUrl.removeAttribute('disabled'); if (proxy.uploadUrl) { proxy.uploadUrl.url = ''; } }); } }); this.uploadObj.isStringTemplate = true; this.uploadObj.createElement = this.parent.createElement; this.uploadObj.appendTo(uploadEle); return uploadParentEle; } private checkExtension(e: FileInfo): void { if (this.uploadObj.allowedExtensions) { if (this.uploadObj.allowedExtensions.toLocaleLowerCase().indexOf(('.' + e.type).toLocaleLowerCase()) === -1) { (this.dialogObj.getButtons(0) as Button).element.setAttribute('disabled', 'disabled'); this.isAllowedTypes = false; } else { this.isAllowedTypes = true; } } } private fileSelect(): boolean { this.dialogObj.element.getElementsByClassName('e-file-select-wrap')[0].querySelector('button').click(); return false; } private dragStart(e: DragEvent): void | boolean { if ((e.target as HTMLElement).nodeName === 'IMG') { this.parent.trigger(events.actionBegin, e, (actionBeginArgs: ActionBeginEventArgs) => { if (actionBeginArgs.cancel) { e.preventDefault(); } else { e.dataTransfer.effectAllowed = 'copyMove'; (e.target as HTMLElement).classList.add(classes.CLS_RTE_DRAG_IMAGE); } }); } else { return true; } } private dragEnter(e?: DragEvent): void { e.dataTransfer.dropEffect = 'copy'; e.preventDefault(); } private dragOver(e?: DragEvent): void | boolean { if ((Browser.info.name === 'edge' && e.dataTransfer.items[0].type.split('/')[0].indexOf('image') > -1) || (Browser.isIE && e.dataTransfer.types[0] === 'Files')) { e.preventDefault(); } else { return true; } } /** * Used to set range When drop an image * * @param {ImageDropEventArgs} args - specifies the image arguments. * @returns {void} */ private dragDrop(args: ImageDropEventArgs): void { this.parent.trigger(events.beforeImageDrop, args, (e: ImageDropEventArgs) => { const imgElement: HTMLElement = this.parent.inputElement.ownerDocument.querySelector('.' + classes.CLS_RTE_DRAG_IMAGE); const isImgOrFileDrop: boolean = (imgElement && imgElement.tagName === 'IMG') || e.dataTransfer.files.length > 0; if (!e.cancel && isImgOrFileDrop) { this.parent.trigger(events.actionBegin, e, (actionBeginArgs: ActionBeginEventArgs) => { if (actionBeginArgs.cancel) { e.preventDefault(); } else { if (closest((e.target as HTMLElement), '#' + this.parent.getID() + '_toolbar') || this.parent.inputElement.contentEditable === 'false') { e.preventDefault(); return; } if (this.parent.element.querySelector('.' + classes.CLS_IMG_RESIZE)) { detach(this.imgResizeDiv); } e.preventDefault(); let range: Range; if (this.contentModule.getDocument().caretRangeFromPoint) { //For chrome range = this.contentModule.getDocument().caretRangeFromPoint(e.clientX, e.clientY); } else if ((e.rangeParent)) { //For mozilla firefox range = this.contentModule.getDocument().createRange(); range.setStart(e.rangeParent, e.rangeOffset); } else { range = this.getDropRange(e.clientX, e.clientY); //For internet explorer } this.parent.notify(events.selectRange, { range: range }); const uploadArea: HTMLElement = this.parent.element.querySelector('.' + classes.CLS_DROPAREA) as HTMLElement; if (uploadArea) { return; } this.insertDragImage(e as DragEvent); } }); } else { if (isImgOrFileDrop) { e.preventDefault(); } } }); } /** * Used to calculate range on internet explorer * * @param {number} x - specifies the x range. * @param {number} y - specifies the y range. * @returns {void} */ private getDropRange(x: number, y: number): Range { const startRange: Range = this.contentModule.getDocument().createRange(); this.parent.formatter.editorManager.nodeSelection.setRange(this.contentModule.getDocument(), startRange); const elem: Element = this.contentModule.getDocument().elementFromPoint(x, y); const startNode: Node = (elem.childNodes.length > 0 ? elem.childNodes[0] : elem); let startCharIndexCharacter: number = 0; if ((this.parent.inputElement.firstChild as HTMLElement).innerHTML === '<br>') { startRange.setStart(startNode, startCharIndexCharacter); startRange.setEnd(startNode, startCharIndexCharacter); } else { let rangeRect: ClientRect; do { startCharIndexCharacter++; startRange.setStart(startNode, startCharIndexCharacter); startRange.setEnd(startNode, startCharIndexCharacter + 1); rangeRect = startRange.getBoundingClientRect(); } while (rangeRect.left < x && startCharIndexCharacter < (startNode as Text).length - 1); } return startRange; } private insertDragImage(e: DragEvent): void { e.preventDefault(); const activePopupElement: HTMLElement = this.parent.element.querySelector('' + classes.CLS_POPUP_OPEN); this.parent.notify(events.drop, { args: e }); if (activePopupElement) { activePopupElement.classList.add(classes.CLS_HIDE); } if (e.dataTransfer.files.length > 0) { //For external image drag and drop if (e.dataTransfer.files.length > 1) { return; } const imgFiles: FileList = e.dataTransfer.files; const fileName: string = imgFiles[0].name; const imgType: string = fileName.substring(fileName.lastIndexOf('.')); const allowedTypes: string[] = this.parent.insertImageSettings.allowedTypes; for (let i: number = 0; i < allowedTypes.length; i++) { if (imgType.toLocaleLowerCase() === allowedTypes[i].toLowerCase()) { if (this.parent.insertImageSettings.saveUrl) { this.onSelect(e); } else { const args: NotifyArgs = { args: e, text: '', file: imgFiles[0] }; e.preventDefault(); this.imagePaste(args); } } } } else { //For internal image drag and drop const range: Range = this.parent.formatter.editorManager.nodeSelection.getRange(this.parent.contentModule.getDocument()); const imgElement: HTMLElement = this.parent.inputElement.ownerDocument.querySelector('.' + classes.CLS_RTE_DRAG_IMAGE); if (imgElement && imgElement.tagName === 'IMG') { if (imgElement.nextElementSibling) { if (imgElement.nextElementSibling.classList.contains(classes.CLS_IMG_INNER)) { range.insertNode(imgElement.parentElement.parentElement); } else { range.insertNode(imgElement); } } else { range.insertNode(imgElement); } imgElement.classList.remove(classes.CLS_RTE_DRAG_IMAGE); const imgArgs: ActionCompleteEventArgs = { elements: [imgElement] }; imgElement.addEventListener('load', () => { this.parent.trigger(events.actionComplete, imgArgs); }); this.parent.formatter.editorManager.nodeSelection.Clear(this.contentModule.getDocument()); const args: MouseEvent = e as MouseEvent; this.resizeStart(args as PointerEvent, imgElement); this.hideImageQuickToolbar(); } } } private onSelect(args: DragEvent): void { // eslint-disable-next-line const proxy: Image = this; const range: Range = this.parent.formatter.editorManager.nodeSelection.getRange(this.parent.contentModule.getDocument()); const parentElement: HTMLElement = this.parent.createElement('ul', { className: classes.CLS_UPLOAD_FILES }); this.parent.element.appendChild(parentElement); const validFiles: FileInfo = { name: '', size: 0, status: '', statusCode: '', type: '', rawFile: args.dataTransfer.files[0], validationMessages: {} }; const imageTag: HTMLImageElement = <HTMLImageElement>this.parent.createElement('IMG'); imageTag.style.opacity = '0.5'; imageTag.classList.add(classes.CLS_RTE_IMAGE); imageTag.classList.add(classes.CLS_IMGINLINE); imageTag.classList.add(classes.CLS_RESIZE); const file: File = validFiles.rawFile as File; const reader: FileReader = new FileReader(); reader.addEventListener('load', () => { const url: string = URL.createObjectURL(convertToBlob(reader.result as string)); imageTag.src = proxy.parent.insertImageSettings.saveFormat === 'Blob' ? url : reader.result as string; }); if (file) { reader.readAsDataURL(file); } range.insertNode(imageTag); this.uploadMethod(args, imageTag); const e: ActionCompleteEventArgs = { elements: [imageTag] }; imageTag.addEventListener('load', () => { this.parent.trigger(events.actionComplete, e); }); } /** * Rendering uploader and popup for drag and drop * * @param {DragEvent} dragEvent - specifies the event. * @param {HTMLImageElement} imageElement - specifies the element. * @returns {void} */ private uploadMethod(dragEvent: DragEvent, imageElement: HTMLImageElement): void { let isUploading: boolean = false; // eslint-disable-next-line const proxy: Image = this; const popupEle: HTMLElement = this.parent.createElement('div'); this.parent.element.appendChild(popupEle); const uploadEle: HTMLInputElement | HTMLElement = this.parent.createElement('input', { id: this.rteID + '_upload', attrs: { type: 'File', name: 'UploadFiles' } }); const offsetY: number = this.parent.iframeSettings.enable ? -50 : -90; this.popupObj = new Popup(popupEle, { relateTo: imageElement, height: '85px', width: '300px', offsetY: offsetY, content: uploadEle, viewPortElement: this.parent.element, position: { X: 'center', Y: 'top' }, enableRtl: this.parent.enableRtl, zIndex: 10001, // eslint-disable-next-line close: (event: { [key: string]: object }) => { this.parent.isBlur = false; this.popupObj.destroy(); detach(this.popupObj.element); this.popupObj = null; } }); this.popupObj.element.style.display = 'none'; addClass([this.popupObj.element], classes.CLS_POPUP_OPEN); addClass([this.popupObj.element], classes.CLS_RTE_UPLOAD_POPUP); const range: Range = this.parent.formatter.editorManager.nodeSelection.getRange(this.parent.contentModule.getDocument()); const timeOut: number = dragEvent.dataTransfer.files[0].size > 1000000 ? 300 : 100; setTimeout(() => { proxy.refreshPopup(imageElement); }, timeOut); let rawFile: FileInfo[]; let beforeUploadArgs: ImageUploadingEventArgs; this.uploadObj = new Uploader({ asyncSettings: { saveUrl: this.parent.insertImageSettings.saveUrl, removeUrl: this.parent.insertImageSettings.removeUrl }, cssClass: classes.CLS_RTE_DIALOG_UPLOAD, dropArea: this.parent.element, allowedExtensions: this.parent.insertImageSettings.allowedTypes.toString(), removing: () => { this.parent.inputElement.contentEditable = 'true'; isUploading = false; detach(imageElement); this.popupObj.close(); }, canceling: () => { this.parent.inputElement.contentEditable = 'true'; isUploading = false; detach(imageElement); this.popupObj.close(); }, beforeUpload: (args: BeforeUploadEventArgs) => { if (this.parent.isServerRendered) { beforeUploadArgs = JSON.parse(JSON.stringify(args)); beforeUploadArgs.filesData = rawFile; isUploading = true; args.cancel = true; this.parent.trigger(events.imageUploading, beforeUploadArgs, (beforeUploadArgs: ImageUploadingEventArgs) => { if (beforeUploadArgs.cancel) { return; } /* eslint-disable */ (this.uploadObj as any).currentRequestHeader = beforeUploadArgs.currentRequest ? beforeUploadArgs.currentRequest : (this.uploadObj as any).currentRequestHeader; (this.uploadObj as any).customFormDatas = beforeUploadArgs.customFormData && beforeUploadArgs.customFormData.length > 0 ? beforeUploadArgs.customFormData : (this.uploadObj as any).customFormDatas; (this.uploadObj as any).uploadFiles(rawFile, null); this.parent.inputElement.contentEditable = 'false'; /* eslint-enable */ }); } else { this.parent.trigger(events.beforeImageUpload, args); } }, uploading: (e: UploadingEventArgs) => { if (!this.parent.isServerRendered) { isUploading = true; this.parent.trigger(events.imageUploading, e, (imageUploadingArgs: UploadingEventArgs) => { if (imageUploadingArgs.cancel) { if (!isNullOrUndefined(imageElement)) { detach(imageElement); } if(!isNullOrUndefined(this.popupObj.element)) { detach(this.popupObj.element); } } else { this.parent.inputElement.contentEditable = 'false'; } }); } }, selected: (e: SelectedEventArgs) => { if (isUploading) { e.cancel = true; } if (this.parent.isServerRendered) { rawFile = e.filesData; } }, failure: (e: Object) => { isUploading = false; this.parent.inputElement.contentEditable = 'true'; const args: IShowPopupArgs = { args: dragEvent as MouseEvent, type: 'Images', isNotify: undefined, elements: imageElement }; setTimeout(() => { this.uploadFailure(imageElement, args, e); }, 900); }, success: (e: ImageSuccessEventArgs) => { isUploading = false; this.parent.inputElement.contentEditable = 'true'; const args: IShowPopupArgs = { args: dragEvent as MouseEvent, type: 'Images', isNotify: undefined, elements: imageElement }; setTimeout(() => { this.uploadSuccess(imageElement, dragEvent, args, e); }, 900); } }); this.uploadObj.appendTo(this.popupObj.element.childNodes[0] as HTMLElement); (this.popupObj.element.querySelector('.e-rte-dialog-upload .e-file-select-wrap') as HTMLElement).style.display = 'none'; range.selectNodeContents(imageElement); this.parent.formatter.editorManager.nodeSelection.setRange(this.contentModule.getDocument(), range); } private refreshPopup(imageElement: HTMLElement): void { const imgPosition: number = this.parent.iframeSettings.enable ? this.parent.element.offsetTop + imageElement.offsetTop : imageElement.offsetTop; const rtePosition: number = this.parent.element.offsetTop + this.parent.element.offsetHeight; if (imgPosition > rtePosition) { this.popupObj.relateTo = this.parent.inputElement; this.popupObj.offsetY = this.parent.iframeSettings.enable ? -30 : -65; this.popupObj.element.style.display = 'block'; } else { if (this.popupObj) { this.popupObj.refreshPosition(imageElement); this.popupObj.element.style.display = 'block'; } } } /** * Called when drop image upload was failed * * @param {HTMLElement} imgEle - specifies the image element. * @param {IShowPopupArgs} args - specifies the arguments. * @param {Object} e - specfies the object. * @returns {void} */ private uploadFailure(imgEle: HTMLElement, args: IShowPopupArgs, e: Object): void { detach(imgEle); if (this.popupObj) { this.popupObj.close(); } this.parent.trigger(events.imageUploadFailed, e); this.uploadObj.destroy(); } /** * Called when drop image upload was successful * * @param {HTMLElement} imageElement - specifies the image element. * @param {DragEvent} dragEvent - specifies the drag event. * @param {IShowPopupArgs} args - specifies the arguments. * @param {ImageSuccessEventArgs} e - specifies the success event. * @returns {void} */ private uploadSuccess(imageElement: HTMLElement, dragEvent: DragEvent, args: IShowPopupArgs, e: ImageSuccessEventArgs): void { imageElement.style.opacity = '1'; imageElement.classList.add(classes.CLS_IMG_FOCUS); e.element = imageElement; this.parent.trigger(events.imageUploadSuccess, e, (e: object) => { if (!isNullOrUndefined(this.parent.insertImageSettings.path)) { const url: string = this.parent.insertImageSettings.path + (e as MetaData).file.name; (imageElement as HTMLImageElement).src = url; imageElement.setAttribute('alt', (e as MetaData).file.name); } }); if (this.popupObj) { this.popupObj.close(); this.uploadObj.destroy(); } this.showImageQuickToolbar(args); this.resizeStart((dragEvent as MouseEvent) as PointerEvent, imageElement); } private imagePaste(args: NotifyArgs): void { if (args.text.length === 0 && !isNullOrUndefined((args as NotifyArgs).file)) { // eslint-disable-next-line const proxy: Image = this; const reader: FileReader = new FileReader(); (args.args as KeyboardEvent).preventDefault(); // eslint-disable-next-line reader.addEventListener('load', (e: MouseEvent) => { const url: IImageCommandsArgs = { cssClass: (proxy.parent.insertImageSettings.display === 'inline' ? classes.CLS_IMGINLINE : classes.CLS_IMGBREAK), url: this.parent.insertImageSettings.saveFormat === 'Base64' || !isNullOrUndefined(args.callBack) ? reader.result as string : URL.createObjectURL(convertToBlob(reader.result as string)), width: { width: proxy.parent.insertImageSettings.width, minWidth: proxy.parent.insertImageSettings.minWidth, maxWidth: proxy.parent.getInsertImgMaxWidth() }, height: { height: proxy.parent.insertImageSettings.height, minHeight: proxy.parent.insertImageSettings.minHeight, maxHeight: proxy.parent.insertImageSettings.maxHeight } }; if (!isNullOrUndefined(args.callBack)) { args.callBack(url); return; } else { proxy.parent.formatter.process(proxy.parent, { item: { command: 'Images', subCommand: 'Image' } }, args.args, url); this.showPopupToolBar(args, url); } }); reader.readAsDataURL((args as NotifyArgs).file); } } private showPopupToolBar(e: NotifyArgs, url: IImageCommandsArgs): void { const imageSrc: string = 'img[src="' + url.url + '"]'; const imageElement: Element = this.parent.inputElement.querySelector(imageSrc); this.parent.quickToolbarModule.createQTBar('Image', 'MultiRow', this.parent.quickToolbarSettings.image, RenderType.ImageToolbar); const args: IShowPopupArgs = { args: e.args as MouseEvent, type: 'Images', isNotify: undefined, elements: imageElement }; if (imageElement) { setTimeout(() => { this.showImageQuickToolbar(args); this.resizeStart(e.args as PointerEvent, imageElement); }, 0); } } /* eslint-disable */ /** * Destroys the ToolBar. * * @method destroy * @returns {void} * @hidden * @deprecated */ /* eslint-enable */ public destroy(): void { this.prevSelectedImgEle = undefined; this.removeEventListener(); } /** * For internal use only - Get the module name. * * @returns {void} */ private getModuleName(): string { return 'image'; } }
the_stack
import { WeightRecord } from '../types' import { dice } from './dice' import { random } from './random' export type Biome = 'temperate' | 'tropical' | 'arid' | 'polar' export type Seasons = 'spring' | 'summer' | 'autumn' | 'winter' export interface TerrainData { start: WeightRecord<Locations> weather: WeatherData location: Record<string, LocationData> } interface WeatherData { tempVariation: Record<number, TempVariation> season: Record<Seasons, SeasonData> } export interface SeasonData { precipitationLevel: number precipitationIntensity: number baseTemp: number } interface TempVariation { temperature(): number temperatureTimer(): number } interface LocationData { preposition: string precipitationIntensity: number origin: string[] vegetation: Record<string, number> plants: WeightRecord<string> possibleMaterials: string[] } // function makeTerrain<T extends X> () { export const terrain: Record<Biome, TerrainData> = { temperate: { start: { 'seashore': 4, 'forest': 2, 'river coast': 2, 'hills': 1, 'plains': 1, 'mountains': 1 }, weather: { tempVariation: { 95: { temperature: () => dice(3, 10), temperatureTimer: () => random(24, 48) }, 85: { temperature: () => dice(2, 10), temperatureTimer: () => random(24, 96) }, 65: { temperature: () => random(1, 10), temperatureTimer: () => random(48, 120) }, 35: { temperature: () => random(-5, 5), temperatureTimer: () => random(48, 144) }, 15: { temperature: () => random(-1, -10), temperatureTimer: () => random(48, 120) }, 5: { temperature: () => 0 - dice(2, 10), temperatureTimer: () => random(24, 96) }, 0: { temperature: () => random(-1, -24), temperatureTimer: () => random(24, 48) } }, season: { summer: { precipitationLevel: 4, precipitationIntensity: 1, baseTemp: 80 }, autumn: { precipitationLevel: 3, precipitationIntensity: 1, baseTemp: 60 }, winter: { precipitationLevel: 2, precipitationIntensity: 1, baseTemp: 30 }, spring: { precipitationLevel: 3, precipitationIntensity: 1, baseTemp: 60 } } } as WeatherData, location: { // town.Name is located in the _ 'seashore': { preposition: 'on', precipitationIntensity: 3, // town.Name grew around _ origin: [ 'a coastal harbor', 'a calm, coastal bay', 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'the mouth of a river', 'the confluence of two rivers', 'a series of natural springs', 'a well-traveled crossroads', 'a water source and a well-traveled road' ], // where the vegetation is _ vegetation: { sparse: 1, lush: 4, thick: 3 }, plants: { 'shrubs': 1, 'bush': 1, 'windswept trees': 1 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone'] }, 'forest': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'the mouth of a river', 'a deep freshwater river', 'a river that runs through the forest', 'a series of natural springs', 'a well-traveled crossroads', 'a road that passes through the forests', 'a water source and a well-traveled road leading through the forest' ], vegetation: { sparse: 1, lush: 3, thick: 6 }, plants: { 'oak trees': 3, 'pine trees': 1, 'maple trees': 1, 'birch trees': 1, 'ash trees': 1, 'elm trees': 1, 'fir trees': 1, 'spruce trees': 1, 'sycamore trees': 1, 'alder trees': 1, 'cypress trees': 1, 'yew trees': 1 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob'] }, 'hills': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { sparse: 1, lush: 3, thick: 6 }, plants: { // TODO: expand out the plants for everything past this point- they're all placeholder text. shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob'] }, 'plains': { preposition: 'on', precipitationIntensity: 2, origin: [ 'a wide, navigable river', 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { sparse: 5, lush: 1, thick: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob'] }, 'mountains': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a river navigable by small craft', 'a series of natural springs', 'a road that connects two other cities', 'a road that leads through the mountains', 'a trade route through the mountains', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { sparse: 5, lush: 1, thick: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob'] }, 'river coast': { preposition: 'on', precipitationIntensity: 2, origin: [ 'a coastal harbor', 'a calm, coastal bay', 'a wide, navigable river', 'a river navigable by small craft'], vegetation: { sparse: 1, lush: 4, thick: 3 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob'] } } }, tropical: { start: { 'seacoast': 1, 'forest': 1, 'river coast': 2, 'jungle': 1, 'volcanic field': 1, 'hills': 1, 'plains': 1, 'mountains': 1 }, weather: { tempVariation: { 85: { temperature: () => dice(2, 10), temperatureTimer: () => random(24, 48) }, 55: { temperature: () => random(1, 10), temperatureTimer: () => random(48, 120) }, 25: { temperature: () => 0 - random(-5, 5), temperatureTimer: () => random(48, 120) }, 10: { temperature: () => 0 - random(1, 10), temperatureTimer: () => random(24, 48) }, 0: { temperature: () => 0 - dice(2, 10), temperatureTimer: () => random(24, 48) } }, season: { summer: { precipitationLevel: 3, precipitationIntensity: 1, baseTemp: 90 }, autumn: { precipitationLevel: 3, precipitationIntensity: 1, baseTemp: 75 }, winter: { precipitationLevel: 2, precipitationIntensity: 1, baseTemp: 50 }, spring: { precipitationLevel: 4, precipitationIntensity: 1, baseTemp: 75 } } } as WeatherData, location: { 'seacoast': { preposition: 'on', precipitationIntensity: 3, origin: [ 'a coastal harbor', 'a calm, coastal bay', 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'the mouth of a river', 'the confluence of two rivers', 'a series of natural springs', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { sparse: 1, lush: 4, thick: 3 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'forest': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'the mouth of a river', 'a deep freshwater river', 'a river that runs through the forest', 'a series of natural springs', 'a well-traveled crossroads', 'a road that passes through the forests', 'a water source and a well-traveled road leading through the forest'], vegetation: { sparse: 1, lush: 3, thick: 6 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'hills': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads'], vegetation: { sparse: 1, lush: 4, thick: 3 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'plains': { preposition: 'on', precipitationIntensity: 2, origin: [ 'a wide, navigable river', 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { sparse: 5, lush: 1, thick: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'mountains': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a river navigable by small craft', 'a series of natural springs', 'a road that connects two other cities', 'a road that leads through the mountains', 'a trade route through the mountains', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { sparse: 5, lush: 1, thick: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'river coast': { preposition: 'on', precipitationIntensity: 2, origin: [ 'a coastal harbor', 'a calm, coastal bay', 'a wide, navigable river', 'a river navigable by small craft'], vegetation: { sparse: 1, lush: 4, thick: 3 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'jungle': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a river navigable by small craft', 'a series of natural springs', 'a road that connects two other cities', 'a road that leads through the jungle', 'a trade route through the jungle', 'a water source and a well-traveled road that leads through the jungle'], vegetation: { sparse: 1, lush: 1, thick: 9 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'volcanic field': { preposition: 'on', precipitationIntensity: 3, origin: [ 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'the mouth of a river', 'a series of natural springs', 'a series of natural springs', 'a series of natural springs', 'a water source and a well-traveled road'], // vegetation: ['desolate', 'desolate', 'desolate', 'desolate', 'desolate', 'desolate', 'desolate', 'sparse', 'sparse', 'sparse', 'lush'], vegetation: { desolate: 7, sparse: 3, lush: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'cobblestone', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] } } }, arid: { start: { 'oasis': 2, 'river coast': 2, 'desert': 1, 'wastelant': 1, 'hills': 1, 'plains': 1, 'mountains': 1 }, weather: { tempVariation: { 95: { temperature: () => dice(3, 10), temperatureTimer: () => random(24, 48) }, 85: { temperature: () => dice(2, 10), temperatureTimer: () => random(24, 96) }, 65: { temperature: () => random(1, 10), temperatureTimer: () => random(48, 120) }, 35: { temperature: () => 0 - random(-5, 5), temperatureTimer: () => random(48, 144) }, 15: { temperature: () => 0 - random(1, 4), temperatureTimer: () => random(48, 120) }, 5: { temperature: () => 0 - dice(1, 10), temperatureTimer: () => random(24, 96) }, 0: { temperature: () => 0 - dice(2, 6), temperatureTimer: () => random(24, 48) } }, season: { summer: { precipitationLevel: 3, precipitationIntensity: -1, baseTemp: 95 }, autumn: { precipitationLevel: 3, precipitationIntensity: -1, baseTemp: 75 }, winter: { precipitationLevel: 2, precipitationIntensity: -1, baseTemp: 50 }, spring: { precipitationLevel: 2, precipitationIntensity: -1, baseTemp: 75 } } } as WeatherData, location: { 'desert': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a coastal harbor', 'a calm, coastal bay', 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'the mouth of a river', 'the confluence of two rivers', 'a series of natural springs', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 5, sparse: 4 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw'] }, 'forest': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'the mouth of a river', 'a deep freshwater river', 'a river that runs through the forest', 'a series of natural springs', 'a well-traveled crossroads', 'a road that passes through the forests', 'a water source and a well-traveled road leading through the forest'], vegetation: { desolate: 2, sparse: 1, lush: 2, thick: 6 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'hills': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 5, sparse: 5, lush: 1, thick: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'plains': { preposition: 'on', precipitationIntensity: 2, origin: [ 'a wide, navigable river', 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 3, sparse: 5 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'mountains': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a river navigable by small craft', 'a series of natural springs', 'a road that connects two other cities', 'a road that leads through the mountains', 'a trade route through the mountains', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 5, sparse: 5, lush: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'river coast': { preposition: 'on', precipitationIntensity: 2, origin: [ 'a coastal harbor', 'a calm, coastal bay', 'a wide, navigable river', 'a river navigable by small craft'], vegetation: { desolate: 3, sparse: 1, lush: 4, thick: 3 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] }, 'wasteland': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 7, sparse: 3, lush: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob'] }, 'oasis': { preposition: 'in', precipitationIntensity: 1, origin: [ 'a series of natural springs', 'a series of natural springs', 'a large oasis of water', 'a large oasis of water', 'a large oasis of water', 'a large oasis of water', 'a water source and a well-traveled road'], vegetation: { sparse: 1, lush: 4, thick: 3 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone', 'plaster', 'gypsum', 'adobe', 'daub', 'cob', 'straw', 'terra cotta', 'clay'] } } }, polar: { start: { 'seacoast': 2, 'forest': 2, 'river coast': 1, 'hills': 1, 'plains': 1, 'mountains': 1, 'tundra': 1, 'ice sheet': 1 }, weather: { tempVariation: { 100: { temperature: () => dice(3, 10), temperatureTimer: () => random(24, 48) }, 95: { temperature: () => dice(2, 10), temperatureTimer: () => random(24, 96) }, 80: { temperature: () => random(1, 10), temperatureTimer: () => random(48, 120) }, 60: { temperature: () => random(-5, 5), temperatureTimer: () => random(48, 144) }, 40: { temperature: () => random(0, -10), temperatureTimer: () => random(48, 120) }, 20: { temperature: () => random(-2, -20), temperatureTimer: () => random(24, 96) }, 0: { temperature: () => random(-3, -30), temperatureTimer: () => random(24, 48) } }, season: { summer: { precipitationLevel: 4, precipitationIntensity: 1, baseTemp: 40 }, autumn: { precipitationLevel: 4, precipitationIntensity: 1, baseTemp: 30 }, winter: { precipitationLevel: 2, precipitationIntensity: 1, baseTemp: 20 }, spring: { precipitationLevel: 3, precipitationIntensity: 1, baseTemp: 30 } } } as WeatherData, location: { 'seacoast': { preposition: 'on', precipitationIntensity: 3, origin: [ 'a coastal harbor', 'a calm, coastal bay', 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'the mouth of a river', 'the confluence of two rivers', 'a series of natural springs', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 3, sparse: 1, lush: 4, thick: 3 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone'] }, 'forest': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'the mouth of a river', 'a deep freshwater river', 'a river that runs through the forest', 'a series of natural springs', 'a well-traveled crossroads', 'a road that passes through the forests', 'a water source and a well-traveled road leading through the forest'], vegetation: { desolate: 2, sparse: 1, lush: 3, thick: 6 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone'] }, 'hills': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a wide, navigable river', 'a river navigable by small craft', 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 4, sparse: 1, lush: 4, thick: 3 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone'] }, 'plains': { preposition: 'on', precipitationIntensity: 2, origin: [ 'a wide, navigable river', 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 5, sparse: 5, lush: 1, thick: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone'] }, 'mountains': { preposition: 'in', precipitationIntensity: 2, origin: [ 'a large freshwater lake', 'a river navigable by small craft', 'a series of natural springs', 'a road that connects two other cities', 'a road that leads through the mountains', 'a trade route through the mountains', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 5, sparse: 5, lush: 1, thick: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone'] }, 'river coast': { preposition: 'on', precipitationIntensity: 2, origin: [ 'a coastal harbor', 'a calm, coastal bay', 'a wide, navigable river', 'a river navigable by small craft'], vegetation: { desolate: 3, sparse: 1, lush: 4, thick: 3 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone'] }, 'tundra': { preposition: 'on', precipitationIntensity: 2, origin: [ 'a wide, navigable river', 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 7, sparse: 3, lush: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone'] }, 'ice sheet': { preposition: 'on', precipitationIntensity: 3, origin: [ 'a wide, navigable river', 'a road traveled by merchants on the way to another, larger city', 'a well maintained road', 'a road that connects two other cities', 'a well-traveled crossroads', 'a water source and a well-traveled road'], vegetation: { desolate: 7, sparse: 3, lush: 1 }, plants: { shrubs: 1, bush: 1, trees: 2 } as WeightRecord<string>, possibleMaterials: ['hewn rock', 'stone', 'cobblestone', 'wood', 'brick', 'limestone'] } } } } // return terrain // } // export const terrain = makeTerrain() // eslint-disable-next-line @typescript-eslint/no-explicit-any type UnionKeys<T> = T extends any ? keyof T : never type Terrain = typeof terrain export type Locations = UnionKeys<Terrain[keyof Terrain]['location']>
the_stack
import "@material/mwc-list/mwc-list-item"; import { css, CSSResultGroup, html, LitElement, PropertyValues, TemplateResult, } from "lit"; import { property } from "lit/decorators"; import { classMap } from "lit/directives/class-map"; import { fireEvent } from "../../../common/dom/fire_event"; import { stopPropagation } from "../../../common/dom/stop_propagation"; import { supportsFeature } from "../../../common/entity/supports-feature"; import { computeRTLDirection } from "../../../common/util/compute_rtl"; import "../../../components/ha-climate-control"; import "../../../components/ha-select"; import "../../../components/ha-slider"; import "../../../components/ha-switch"; import { ClimateEntity, CLIMATE_SUPPORT_AUX_HEAT, CLIMATE_SUPPORT_FAN_MODE, CLIMATE_SUPPORT_PRESET_MODE, CLIMATE_SUPPORT_SWING_MODE, CLIMATE_SUPPORT_TARGET_HUMIDITY, CLIMATE_SUPPORT_TARGET_TEMPERATURE, CLIMATE_SUPPORT_TARGET_TEMPERATURE_RANGE, compareClimateHvacModes, } from "../../../data/climate"; import { HomeAssistant } from "../../../types"; class MoreInfoClimate extends LitElement { @property({ attribute: false }) public hass!: HomeAssistant; @property() public stateObj?: ClimateEntity; private _resizeDebounce?: number; protected render(): TemplateResult { if (!this.stateObj) { return html``; } const hass = this.hass; const stateObj = this.stateObj; const supportTargetTemperature = supportsFeature( stateObj, CLIMATE_SUPPORT_TARGET_TEMPERATURE ); const supportTargetTemperatureRange = supportsFeature( stateObj, CLIMATE_SUPPORT_TARGET_TEMPERATURE_RANGE ); const supportTargetHumidity = supportsFeature( stateObj, CLIMATE_SUPPORT_TARGET_HUMIDITY ); const supportFanMode = supportsFeature(stateObj, CLIMATE_SUPPORT_FAN_MODE); const supportPresetMode = supportsFeature( stateObj, CLIMATE_SUPPORT_PRESET_MODE ); const supportSwingMode = supportsFeature( stateObj, CLIMATE_SUPPORT_SWING_MODE ); const supportAuxHeat = supportsFeature(stateObj, CLIMATE_SUPPORT_AUX_HEAT); const temperatureStepSize = stateObj.attributes.target_temp_step || (hass.config.unit_system.temperature.indexOf("F") === -1 ? 0.5 : 1); const rtlDirection = computeRTLDirection(hass); return html` <div class=${classMap({ "has-current_temperature": "current_temperature" in stateObj.attributes, "has-current_humidity": "current_humidity" in stateObj.attributes, "has-target_temperature": supportTargetTemperature, "has-target_temperature_range": supportTargetTemperatureRange, "has-target_humidity": supportTargetHumidity, "has-fan_mode": supportFanMode, "has-swing_mode": supportSwingMode, "has-aux_heat": supportAuxHeat, "has-preset_mode": supportPresetMode, })} > <div class="container-temperature"> <div class=${stateObj.state}> ${supportTargetTemperature || supportTargetTemperatureRange ? html` <div> ${hass.localize("ui.card.climate.target_temperature")} </div> ` : ""} ${stateObj.attributes.temperature !== undefined && stateObj.attributes.temperature !== null ? html` <ha-climate-control .hass=${this.hass} .value=${stateObj.attributes.temperature} .unit=${hass.config.unit_system.temperature} .step=${temperatureStepSize} .min=${stateObj.attributes.min_temp} .max=${stateObj.attributes.max_temp} @change=${this._targetTemperatureChanged} ></ha-climate-control> ` : ""} ${(stateObj.attributes.target_temp_low !== undefined && stateObj.attributes.target_temp_low !== null) || (stateObj.attributes.target_temp_high !== undefined && stateObj.attributes.target_temp_high !== null) ? html` <ha-climate-control .hass=${this.hass} .value=${stateObj.attributes.target_temp_low} .unit=${hass.config.unit_system.temperature} .step=${temperatureStepSize} .min=${stateObj.attributes.min_temp} .max=${stateObj.attributes.target_temp_high} class="range-control-left" @change=${this._targetTemperatureLowChanged} ></ha-climate-control> <ha-climate-control .hass=${this.hass} .value=${stateObj.attributes.target_temp_high} .unit=${hass.config.unit_system.temperature} .step=${temperatureStepSize} .min=${stateObj.attributes.target_temp_low} .max=${stateObj.attributes.max_temp} class="range-control-right" @change=${this._targetTemperatureHighChanged} ></ha-climate-control> ` : ""} </div> </div> ${supportTargetHumidity ? html` <div class="container-humidity"> <div>${hass.localize("ui.card.climate.target_humidity")}</div> <div class="single-row"> <div class="target-humidity"> ${stateObj.attributes.humidity} % </div> <ha-slider step="1" pin ignore-bar-touch dir=${rtlDirection} .min=${stateObj.attributes.min_humidity} .max=${stateObj.attributes.max_humidity} .value=${stateObj.attributes.humidity} @change=${this._targetHumiditySliderChanged} > </ha-slider> </div> </div> ` : ""} <div class="container-hvac_modes"> <div class="controls"> <ha-select .label=${hass.localize("ui.card.climate.operation")} .value=${stateObj.state} fixedMenuPosition naturalMenuWidth @selected=${this._handleOperationmodeChanged} @closed=${stopPropagation} > ${stateObj.attributes.hvac_modes .concat() .sort(compareClimateHvacModes) .map( (mode) => html` <mwc-list-item .value=${mode}> ${hass.localize(`component.climate.state._.${mode}`)} </mwc-list-item> ` )} </ha-select> </div> </div> ${supportPresetMode && stateObj.attributes.preset_modes ? html` <div class="container-preset_modes"> <ha-select .label=${hass.localize("ui.card.climate.preset_mode")} .value=${stateObj.attributes.preset_mode} fixedMenuPosition naturalMenuWidth @selected=${this._handlePresetmodeChanged} @closed=${stopPropagation} > ${stateObj.attributes.preset_modes!.map( (mode) => html` <mwc-list-item .value=${mode}> ${hass.localize( `state_attributes.climate.preset_mode.${mode}` ) || mode} </mwc-list-item> ` )} </ha-select> </div> ` : ""} ${supportFanMode && stateObj.attributes.fan_modes ? html` <div class="container-fan_list"> <ha-select .label=${hass.localize("ui.card.climate.fan_mode")} .value=${stateObj.attributes.fan_mode} fixedMenuPosition naturalMenuWidth @selected=${this._handleFanmodeChanged} @closed=${stopPropagation} > ${stateObj.attributes.fan_modes!.map( (mode) => html` <mwc-list-item .value=${mode}> ${hass.localize( `state_attributes.climate.fan_mode.${mode}` ) || mode} </mwc-list-item> ` )} </ha-select> </div> ` : ""} ${supportSwingMode && stateObj.attributes.swing_modes ? html` <div class="container-swing_list"> <ha-select .label=${hass.localize("ui.card.climate.swing_mode")} .value=${stateObj.attributes.swing_mode} fixedMenuPosition naturalMenuWidth @selected=${this._handleSwingmodeChanged} @closed=${stopPropagation} > ${stateObj.attributes.swing_modes!.map( (mode) => html` <mwc-list-item .value=${mode}>${mode}</mwc-list-item> ` )} </ha-select> </div> ` : ""} ${supportAuxHeat ? html` <div class="container-aux_heat"> <div class="center horizontal layout single-row"> <div class="flex"> ${hass.localize("ui.card.climate.aux_heat")} </div> <ha-switch .checked=${stateObj.attributes.aux_heat === "on"} @change=${this._auxToggleChanged} ></ha-switch> </div> </div> ` : ""} </div> `; } protected updated(changedProps: PropertyValues) { super.updated(changedProps); if (!changedProps.has("stateObj") || !this.stateObj) { return; } if (this._resizeDebounce) { clearTimeout(this._resizeDebounce); } this._resizeDebounce = window.setTimeout(() => { fireEvent(this, "iron-resize"); this._resizeDebounce = undefined; }, 500); } private _targetTemperatureChanged(ev) { const newVal = ev.target.value; this._callServiceHelper( this.stateObj!.attributes.temperature, newVal, "set_temperature", { temperature: newVal } ); } private _targetTemperatureLowChanged(ev) { const newVal = ev.currentTarget.value; this._callServiceHelper( this.stateObj!.attributes.target_temp_low, newVal, "set_temperature", { target_temp_low: newVal, target_temp_high: this.stateObj!.attributes.target_temp_high, } ); } private _targetTemperatureHighChanged(ev) { const newVal = ev.currentTarget.value; this._callServiceHelper( this.stateObj!.attributes.target_temp_high, newVal, "set_temperature", { target_temp_low: this.stateObj!.attributes.target_temp_low, target_temp_high: newVal, } ); } private _targetHumiditySliderChanged(ev) { const newVal = ev.target.value; this._callServiceHelper( this.stateObj!.attributes.humidity, newVal, "set_humidity", { humidity: newVal } ); } private _auxToggleChanged(ev) { const newVal = ev.target.checked; this._callServiceHelper( this.stateObj!.attributes.aux_heat === "on", newVal, "set_aux_heat", { aux_heat: newVal } ); } private _handleFanmodeChanged(ev) { const newVal = ev.target.value; this._callServiceHelper( this.stateObj!.attributes.fan_mode, newVal, "set_fan_mode", { fan_mode: newVal } ); } private _handleOperationmodeChanged(ev) { const newVal = ev.target.value; this._callServiceHelper(this.stateObj!.state, newVal, "set_hvac_mode", { hvac_mode: newVal, }); } private _handleSwingmodeChanged(ev) { const newVal = ev.target.value; this._callServiceHelper( this.stateObj!.attributes.swing_mode, newVal, "set_swing_mode", { swing_mode: newVal } ); } private _handlePresetmodeChanged(ev) { const newVal = ev.target.value || null; this._callServiceHelper( this.stateObj!.attributes.preset_mode, newVal, "set_preset_mode", { preset_mode: newVal } ); } private async _callServiceHelper( oldVal: unknown, newVal: unknown, service: string, data: { entity_id?: string; [key: string]: unknown; } ) { if (oldVal === newVal) { return; } data.entity_id = this.stateObj!.entity_id; const curState = this.stateObj; await this.hass.callService("climate", service, data); // We reset stateObj to re-sync the inputs with the state. It will be out // of sync if our service call did not result in the entity to be turned // on. Since the state is not changing, the resync is not called automatic. await new Promise((resolve) => setTimeout(resolve, 2000)); // No need to resync if we received a new state. if (this.stateObj !== curState) { return; } this.stateObj = undefined; await this.updateComplete; // Only restore if not set yet by a state change if (this.stateObj === undefined) { this.stateObj = curState; } } static get styles(): CSSResultGroup { return css` :host { color: var(--primary-text-color); } ha-select { width: 100%; margin-top: 8px; } ha-slider { width: 100%; } .container-humidity .single-row { display: flex; height: 50px; } .target-humidity { width: 90px; font-size: 200%; margin: auto; direction: ltr; } ha-climate-control.range-control-left, ha-climate-control.range-control-right { float: left; width: 46%; } ha-climate-control.range-control-left { margin-right: 4%; } ha-climate-control.range-control-right { margin-left: 4%; } .single-row { padding: 8px 0; } `; } } customElements.define("more-info-climate", MoreInfoClimate); declare global { interface HTMLElementTagNameMap { "more-info-climate": MoreInfoClimate; } }
the_stack
import React, { Fragment, Component } from 'react' import { connect } from 'dva' import { Form, Input, Icon, Tooltip, InputNumber, Switch, Collapse, Button, Select, message } from 'antd' import { } from 'antd/es/form' import _ from 'lodash' import classNames from 'classnames' import { emitter } from '~/utils/events' import styles from './index.module.less' import { InterfaceProperty, InterfaceEditConfig, InterfaceSubProperty, properties } from '~/types/components/interfaceEditConfig' import { Props, ConnectState } from './interface' // import { isJavascriptStr } from '~/utils' import { isKeyboardEvent } from '~/constant/keyboardEvent' import FormInput from './compontent/input' import FormItem from './compontent/FormItem' import JsonEditor from '~/components/JsonEditor/Controled' const Panel = Collapse.Panel const ButtonGroup = Button.Group class TheFormEditor extends Component<Props, {}> { static propTypes = {} state = {} // json类型的表单 jsonFields: dynamicObject = {} componentWillMount() { emitter.on('TheFormEditor.submit', this.onSubmit) window.addEventListener('keydown', this.onKeyDown) } componentWillUnmount = () => { emitter.off('TheFormEditor.submit', this.onSubmit) window.removeEventListener('keydown', this.onKeyDown) } // 绑定键盘事件 onKeyDown = (e: KeyboardEvent) => { if (isKeyboardEvent(e, 'save')) { this.onSubmit(e) } } // 提交表单 onSubmit = (e?: KeyboardEvent) => { e && e.preventDefault() const { form, activeTab, updatePageConfigAndReload } = this.props if (activeTab !== 'base') { return false } form.validateFieldsAndScroll({ force: true }, async (err: any, allValues: dynamicObject) => { if (err) { console.log('err', err) return err } updatePageConfigAndReload(allValues) }) } /** * 渲染FormContent * type、children属性不可编辑, * * @param dataProps 当前组件的配置 * @param dataPageConfigPath 当前属性在pageConfig中的路径 */ renderFormContent = (formData: dynamicObject) => { const { selectedComponentData, editConfigData, form } = this.props let type = selectedComponentData['dataComponentType'] // 类型二, 组件内置属性, 例如 fields、columns等 const { getFieldDecorator } = form const AdvancedAttributes = this.renderProps(formData, editConfigData, 'extend') return ( <div> <FormItem formItemLayout={{ labelCol: { span: 8 }, wrapperCol: { span: 16 } }} label={<span>组件类型</span>}> <div style={{ display: 'none' }}>{getFieldDecorator('type', { initialValue: type })(<FormInput disabled />)}</div> <span style={{ color: '#FFF' }}>{type}</span> </FormItem> {this.renderProps(formData, editConfigData, 'default')} { AdvancedAttributes && (<Collapse activeKey="extend" bordered={false}> <Panel key="extend" header="高级属性"> {AdvancedAttributes} </Panel> </Collapse>) } </div> ) } /** * 将属性渲染为form表单 * @param compontentProps 组件属性 * @param compontentPropsConfig 组件属性定义文档 */ renderProps = ( compontentProps: dynamicObject, compontentPropsConfig: InterfaceEditConfig, group: 'extend' | 'default' ) => { if (_.isPlainObject(compontentPropsConfig)) { // 只对明确声明了的组件属性进行编辑, 方便统一生成文档 let propEditorItemList = [] for (let fieldKey of Object.keys(compontentPropsConfig)) { let _group = compontentPropsConfig[fieldKey].group || 'default' if (_group !== group) { continue } let propConfig = compontentPropsConfig[fieldKey] let propValue = compontentProps[fieldKey] !== undefined ? compontentProps[fieldKey] : compontentPropsConfig[fieldKey].defaultValue let editorItem = this.renderPropEditorItem(`${fieldKey}`, propConfig, propValue, 1) propEditorItemList.push(editorItem) } return propEditorItemList.length ? propEditorItemList : null } return null } /** * 获取数组的默认项, 用于添加时的默认值 */ getDefaultArrayItem = (properties: properties) => { // 生成默认元素值 let defaultItemValue: { [key: string]: any } = {} if (properties) { for (let key of Object.keys(properties)) { defaultItemValue[key] = properties[key].defaultValue } } return defaultItemValue } // 将对象渲染为panel, object/arrayOf类型都需要用到 renderProperties = ( fieldKey: string, propConfig: InterfaceProperty, propValue: any, isRenderArray = false, level: number ) => { const { dataPageConfigPath } = this.props.selectedComponentData /****************************↓↓↓↓↓为方便渲染数组↓↓↓↓↓****************************/ // 如果是数组的话, 需要绑定操作, 以便添加/删除数据 // 根据当前路径, 还原出数组key对应的路径 let propJsPathArray = _.toPath(fieldKey) // 最后一位肯定是当前元素的index值 let currentItemIndex = Number.parseInt(propJsPathArray.pop()) || 0 // 生成默认元素值 let defaultItemValue = this.getDefaultArrayItem(propConfig.properties) /****************************↑↑↑↑↑方便渲染数组↑↑↑↑↑****************************/ // 正式的渲染逻辑 let itemList = [] for (let key of Object.keys(propConfig.properties)) { // 只有单层嵌套, 不考虑多层属性嵌套的情况 let _propConfig: InterfaceProperty = propConfig.properties[key] let defaultValue = _propConfig.defaultValue let initialPropertyValue = _.get(propValue, key, defaultValue) let item = this.renderPropEditorItem( `${fieldKey}.${key}`, _propConfig, initialPropertyValue, level + 1 ) itemList.push(item) } let extraActionList = this.renderExtraActionList( fieldKey, currentItemIndex, defaultItemValue, ) if (isRenderArray) { // 如果为ArrayOf return ( <div key={`${fieldKey}_${dataPageConfigPath}_arrayof`} className={classNames(styles['m-collapse'], `level-${level}`)} > <div style={{ display: 'flex', padding: '2px 16px 6px 16px', color: '#fff' }}> <span>[{currentItemIndex}]</span> <div style={{ textAlign: 'right', flex: 1 }}>{extraActionList}</div> </div> <div style={{ paddingBottom: "12px" }}>{itemList}</div> </div> ) } return ( <div key={`${fieldKey}_${dataPageConfigPath}_object`} className={classNames(styles['m-collapse'], `level-${level}`)} > <div style={{ padding: '14px 0 14px 16px', color: 'rgba(255,255,255,.9)' }}> {propConfig.title}&nbsp; {propConfig.desc && <Tooltip title={propConfig.desc}> <Icon type="question-circle-o" /> </Tooltip>} </div> <div style={{ padding: '0px 0 8px 16px' }}>{itemList}</div> </div> ) } renderExtraActionList = ( relativePath: string, currentItemIndex: number, defaultItemValue: any, ) => { const parentRelativePath = relativePath.replace(/\[\d\]$/, '') function getFieldValue(form: any, path: string) { const formData = form.getFieldsValue() return _.get(formData, path) } let extraActionList = ( <ButtonGroup> <Button onClick={() => { const currentParentValue: dynamicObject[] = getFieldValue(this.props.form, parentRelativePath) // 执行添加操作, 添加到该元素之前 let newParentValue = [ ...currentParentValue.slice(0, currentItemIndex), defaultItemValue, ...currentParentValue.slice(currentItemIndex), ] this.props.updatePageConfig(parentRelativePath, newParentValue) }} size="small" icon="plus" /> <Button onClick={() => { const currentParentValue: dynamicObject[] = getFieldValue(this.props.form, parentRelativePath) // 删除元素 let newParentValue = [ ...currentParentValue.slice(0, currentItemIndex), ...currentParentValue.slice(currentItemIndex + 1), ] this.props.updatePageConfig(parentRelativePath, newParentValue) console.info('remove success') }} size="small" icon="delete" /> <Button onClick={() => { const currentParentValue: dynamicObject[] = getFieldValue(this.props.form, parentRelativePath) let currentItem = currentParentValue[currentItemIndex] let newParentValue = _.cloneDeep(currentParentValue) if (currentItemIndex === 0) { console.info('up success') return } else { let beforeItemIndex = currentItemIndex - 1 let beforeItem = _.cloneDeep(currentParentValue[beforeItemIndex]) newParentValue[beforeItemIndex] = currentItem newParentValue[currentItemIndex] = beforeItem } console.log('parentRelativePath', parentRelativePath) console.log('newParentValue', JSON.stringify(newParentValue)) this.props.updatePageConfig(parentRelativePath, newParentValue) console.info('up success') }} size="small" icon="arrow-up" /> <Button onClick={() => { const currentParentValue: dynamicObject[] = getFieldValue(this.props.form, parentRelativePath) let currentItem = currentParentValue[currentItemIndex] let newParentValue = _.cloneDeep(currentParentValue) if (currentItemIndex === currentParentValue.length - 1) { console.info('down success') return } else { let nextItemIndex = currentItemIndex + 1 let nextItem = _.cloneDeep(currentParentValue[nextItemIndex]) newParentValue[currentItemIndex] = nextItem newParentValue[nextItemIndex] = currentItem } this.props.updatePageConfig(parentRelativePath, newParentValue) console.info('down success') }} size="small" icon="arrow-down" /> </ButtonGroup> ) return extraActionList } /** * @param fieldKey 字段 * @param propConfig 字段配置 * @param fieldValue 字段的值 * @param level 层级 */ renderPropEditorItem = (fieldKey: string, propConfig: InterfaceProperty, fieldValue: any, level: number = 1): React.ReactNode => { if (propConfig.visible !== undefined && !propConfig.visible) return null const { dataPageConfigPath } = this.props.selectedComponentData const { getFieldDecorator } = this.props.form fieldKey = fieldKey.trim() let dataType = propConfig.type const getFieldDecoratorOption = { initialValue: fieldValue, } const showTooltip = propConfig.showTooltip const disabled = propConfig.isEditable === false let labelItem = propConfig.title const desc = propConfig.desc && <>{propConfig.desc}{propConfig.doc && <Button type="link" target="_blank" href={propConfig.doc}>详情</Button>}</> switch (dataType) { case 'string': return (() => { return ( <FormItem key={`${fieldKey}_${dataPageConfigPath}_${dataType}`} extra={desc} showTooltip={showTooltip} propConfig={propConfig} label={labelItem} > {getFieldDecorator(fieldKey, getFieldDecoratorOption)(<FormInput disabled={disabled} autoSize={propConfig.autoSize} placeholder={propConfig.placeholder} />)} </FormItem> ) })() case 'number': return (() => { return ( <FormItem key={`${fieldKey}_${dataPageConfigPath}_${dataType}`} extra={desc} label={labelItem} showTooltip={showTooltip} propConfig={propConfig} > {getFieldDecorator(fieldKey, getFieldDecoratorOption)(<InputNumber disabled={disabled} />)} </FormItem> ) })() case 'bool': return (() => { return ( <FormItem key={`${fieldKey}_${dataPageConfigPath}_${dataType}`} extra={desc} label={labelItem} showTooltip={showTooltip} propConfig={propConfig} > {getFieldDecorator(fieldKey, { ...getFieldDecoratorOption, valuePropName: 'checked' })( <Switch disabled={disabled} />, )} </FormItem> ) })() case 'enum': return (() => { const mode = propConfig.mode let optionList = [] let index = 0 for (let item of propConfig.enumList) { let enumItem = propConfig.enumList[index] let enumDesc = propConfig.enumDescriptionList[index] optionList.push( <Select.Option key={`option-${index}`} value={enumItem}> {enumDesc} </Select.Option> ) index++ } return ( <FormItem key={`${fieldKey}_${dataPageConfigPath}_${dataType}`} extra={desc} label={labelItem} showTooltip={showTooltip} propConfig={propConfig} > {getFieldDecorator(fieldKey, { ...getFieldDecoratorOption, valuePropName: 'checked' })( <Select disabled={disabled} defaultValue={fieldValue} mode={mode}>{optionList}</Select>, )} </FormItem> ) })() case 'object': return (() => { let objectPanelItem = this.renderProperties(fieldKey, propConfig, fieldValue, false, level + 1) return ( <div key={fieldKey} className={classNames(styles['m-collapse'], `level-${level}`)} > {objectPanelItem} </div> ) })() case 'arrayOf': return (() => { if (!_.isArray(fieldValue)) { fieldValue = [] } let propertyValueList: Array<dynamicObject> = fieldValue let index = 0 let itemList = [] for (let propertyValue of propertyValueList) { let clonePropConfig = _.cloneDeep(propConfig) if (_.isFunction(propConfig.arrayItemProperty)) { // 如果propConfig.arrayItemProperty为函数, 则说明列每一项配置是动态获取 clonePropConfig.properties = propConfig.arrayItemProperty(index, propertyValue, fieldValue) } // 数组元素每一项的title都应该不一样, 所以这里需要hack掉 clonePropConfig.title = `[${index}]` let childFieldKey = `${fieldKey}[${index}]` let item = this.renderProperties(childFieldKey, clonePropConfig, propertyValue, true, level + 1) itemList.push(item) index++ } return ( <Collapse bordered={false} className={classNames(styles['m-collapse'], `level-${level}`)} defaultActiveKey={[`${fieldKey}`]} key={fieldKey} > <Panel key={fieldKey} header={labelItem} forceRender className={classNames(styles['m-collapse'], `level-${level}`)} > {itemList} <Button type="link" onClick={() => { // 生成默认元素值 let defaultItemValue = this.getDefaultArrayItem(propConfig.properties) let currentParentValue = this.props.form.getFieldValue(fieldKey) || [] // 执行添加操作, 添加到该元素之前 let newParentValue = defaultItemValue ? [ ...currentParentValue, defaultItemValue, ] : currentParentValue this.props.updatePageConfig(fieldKey, newParentValue) console.info('add success') }}>添加选项</Button> </Panel> </Collapse> ) })() case 'json': case 'json-inline': default: return (() => { let formItemLayout: any = { labelCol: propConfig.labelCol || { xs: { span: 24 }, sm: { span: 24 }, }, wrapperCol: propConfig.wrapperCol || { xs: { span: 24, offset: 0 }, sm: { span: 24, offset: 0 }, } } let $JsonEditor: any = {} function jsonValidator(rule: any, value: any, cb: Function) { if ($JsonEditor.errorMessage) { return cb($JsonEditor.errorMessage) } cb() } this.jsonFields[fieldKey] = 1 return ( <FormItem key={`${fieldKey}_${dataPageConfigPath}_${dataType}`} extra={desc} label={labelItem} showTooltip={showTooltip} propConfig={propConfig} formItemLayout={formItemLayout}> {getFieldDecorator(fieldKey, { initialValue: fieldValue === undefined ? propConfig.defaultValue : fieldValue, rules: [ { validator: jsonValidator } ] })(<JsonEditor disabled={disabled} height={propConfig.height} getRef={c => $JsonEditor = c} />)} </FormItem> ) })() } } render() { const { formData } = this.props if (_.isPlainObject(formData)) { return <Form className={styles['the-form-guiEditor']}>{this.renderFormContent(formData)}</Form> } return null } } const WrapperForm = Form.create<Props>({ name: 'form', mapPropsToFields(props) { const { formData } = props let result: dynamicObject = {} if (_.isPlainObject(formData)) { for (let key in formData) { _.set(result, key, Form.createFormField({ value: formData[key] })) } } return result }, onValuesChange(props, changeValues: dynamicObject, allValues: dynamicObject) { const { onChange } = props onChange(allValues) } })(TheFormEditor) export default connect(({ guiEditor }: ConnectState) => ({ pageId: guiEditor.pageId, pageConfig: guiEditor.pageConfig, selectedComponentData: guiEditor.selectedComponentData, activeTab: guiEditor.activeTab, }))(WrapperForm)
the_stack
import * as zrUtil from 'zrender/src/core/util'; import VisualMapModel, { VisualMapOption, VisualMeta } from './VisualMapModel'; import VisualMapping, { VisualMappingOption } from '../../visual/VisualMapping'; import visualDefault from '../../visual/visualDefault'; import {reformIntervals} from '../../util/number'; import { VisualOptionPiecewise, BuiltinVisualProperty } from '../../util/types'; import { Dictionary } from 'zrender/src/core/types'; import { inheritDefaultOption } from '../../util/component'; // TODO: use `relationExpression.ts` instead interface VisualPiece extends VisualOptionPiecewise { min?: number max?: number lt?: number gt?: number lte?: number gte?: number value?: number label?: string } type VisualState = VisualMapModel['stateList'][number]; type InnerVisualPiece = VisualMappingOption['pieceList'][number]; type GetPieceValueType<T extends InnerVisualPiece> = T extends { interval: InnerVisualPiece['interval'] } ? number : string; /** * Order Rule: * * option.categories / option.pieces / option.text / option.selected: * If !option.inverse, * Order when vertical: ['top', ..., 'bottom']. * Order when horizontal: ['left', ..., 'right']. * If option.inverse, the meaning of * the order should be reversed. * * this._pieceList: * The order is always [low, ..., high]. * * Mapping from location to low-high: * If !option.inverse * When vertical, top is high. * When horizontal, right is high. * If option.inverse, reverse. */ export interface PiecewiseVisualMapOption extends VisualMapOption { align?: 'auto' | 'left' | 'right' minOpen?: boolean maxOpen?: boolean /** * When put the controller vertically, it is the length of * horizontal side of each item. Otherwise, vertical side. * When put the controller vertically, it is the length of * vertical side of each item. Otherwise, horizontal side. */ itemWidth?: number itemHeight?: number itemSymbol?: string pieces?: VisualPiece[] /** * category names, like: ['some1', 'some2', 'some3']. * Attr min/max are ignored when categories set. See "Order Rule" */ categories?: string[] /** * If set to 5, auto split five pieces equally. * If set to 0 and component type not set, component type will be * determined as "continuous". (It is less reasonable but for ec2 * compatibility, see echarts/component/visualMap/typeDefaulter) */ splitNumber?: number /** * Object. If not specified, means selected. When pieces and splitNumber: {'0': true, '5': true} * When categories: {'cate1': false, 'cate3': true} When selected === false, means all unselected. */ selected?: Dictionary<boolean> selectedMode?: 'multiple' | 'single' /** * By default, when text is used, label will hide (the logic * is remained for compatibility reason) */ showLabel?: boolean itemGap?: number hoverLink?: boolean } class PiecewiseModel extends VisualMapModel<PiecewiseVisualMapOption> { static type = 'visualMap.piecewise' as const; type = PiecewiseModel.type; /** * The order is always [low, ..., high]. * [{text: string, interval: Array.<number>}, ...] */ private _pieceList: InnerVisualPiece[] = []; private _mode: 'pieces' | 'categories' | 'splitNumber'; optionUpdated(newOption: PiecewiseVisualMapOption, isInit?: boolean) { super.optionUpdated.apply(this, arguments as any); this.resetExtent(); const mode = this._mode = this._determineMode(); this._pieceList = []; resetMethods[this._mode].call(this, this._pieceList); this._resetSelected(newOption, isInit); const categories = this.option.categories; this.resetVisual(function (mappingOption, state) { if (mode === 'categories') { mappingOption.mappingMethod = 'category'; mappingOption.categories = zrUtil.clone(categories); } else { mappingOption.dataExtent = this.getExtent(); mappingOption.mappingMethod = 'piecewise'; mappingOption.pieceList = zrUtil.map(this._pieceList, function (piece) { piece = zrUtil.clone(piece); if (state !== 'inRange') { // FIXME // outOfRange do not support special visual in pieces. piece.visual = null; } return piece; }); } }); } /** * @protected * @override */ completeVisualOption() { // Consider this case: // visualMap: { // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}] // } // where no inRange/outOfRange set but only pieces. So we should make // default inRange/outOfRange for this case, otherwise visuals that only // appear in `pieces` will not be taken into account in visual encoding. const option = this.option; const visualTypesInPieces: {[key in BuiltinVisualProperty]?: 0 | 1} = {}; const visualTypes = VisualMapping.listVisualTypes(); const isCategory = this.isCategory(); zrUtil.each(option.pieces, function (piece) { zrUtil.each(visualTypes, function (visualType: BuiltinVisualProperty) { if (piece.hasOwnProperty(visualType)) { visualTypesInPieces[visualType] = 1; } }); }); zrUtil.each(visualTypesInPieces, function (v, visualType: BuiltinVisualProperty) { let exists = false; zrUtil.each(this.stateList, function (state: VisualState) { exists = exists || has(option, state, visualType) || has(option.target, state, visualType); }, this); !exists && zrUtil.each(this.stateList, function (state: VisualState) { (option[state] || (option[state] = {}))[visualType] = visualDefault.get( visualType, state === 'inRange' ? 'active' : 'inactive', isCategory ); }); }, this); function has(obj: PiecewiseVisualMapOption['target'], state: VisualState, visualType: BuiltinVisualProperty) { return obj && obj[state] && obj[state].hasOwnProperty(visualType); } super.completeVisualOption.apply(this, arguments as any); } private _resetSelected(newOption: PiecewiseVisualMapOption, isInit?: boolean) { const thisOption = this.option; const pieceList = this._pieceList; // Selected do not merge but all override. const selected = (isInit ? thisOption : newOption).selected || {}; thisOption.selected = selected; // Consider 'not specified' means true. zrUtil.each(pieceList, function (piece, index) { const key = this.getSelectedMapKey(piece); if (!selected.hasOwnProperty(key)) { selected[key] = true; } }, this); if (thisOption.selectedMode === 'single') { // Ensure there is only one selected. let hasSel = false; zrUtil.each(pieceList, function (piece, index) { const key = this.getSelectedMapKey(piece); if (selected[key]) { hasSel ? (selected[key] = false) : (hasSel = true); } }, this); } // thisOption.selectedMode === 'multiple', default: all selected. } /** * @public */ getItemSymbol(): string { return this.get('itemSymbol'); } /** * @public */ getSelectedMapKey(piece: InnerVisualPiece) { return this._mode === 'categories' ? piece.value + '' : piece.index + ''; } /** * @public */ getPieceList(): InnerVisualPiece[] { return this._pieceList; } /** * @return {string} */ private _determineMode() { const option = this.option; return option.pieces && option.pieces.length > 0 ? 'pieces' : this.option.categories ? 'categories' : 'splitNumber'; } /** * @override */ setSelected(selected: this['option']['selected']) { this.option.selected = zrUtil.clone(selected); } /** * @override */ getValueState(value: number): VisualState { const index = VisualMapping.findPieceIndex(value, this._pieceList); return index != null ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])] ? 'inRange' : 'outOfRange' ) : 'outOfRange'; } /** * @public * @param pieceIndex piece index in visualMapModel.getPieceList() */ findTargetDataIndices(pieceIndex: number) { type DataIndices = { seriesId: string dataIndex: number[] }; const result: DataIndices[] = []; const pieceList = this._pieceList; this.eachTargetSeries(function (seriesModel) { const dataIndices: number[] = []; const data = seriesModel.getData(); data.each(this.getDataDimensionIndex(data), function (value: number, dataIndex: number) { // Should always base on model pieceList, because it is order sensitive. const pIdx = VisualMapping.findPieceIndex(value, pieceList); pIdx === pieceIndex && dataIndices.push(dataIndex); }, this); result.push({seriesId: seriesModel.id, dataIndex: dataIndices}); }, this); return result; } /** * @private * @param piece piece.value or piece.interval is required. * @return Can be Infinity or -Infinity */ getRepresentValue(piece: InnerVisualPiece) { let representValue; if (this.isCategory()) { representValue = piece.value; } else { if (piece.value != null) { representValue = piece.value; } else { const pieceInterval = piece.interval || []; representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity) ? 0 : (pieceInterval[0] + pieceInterval[1]) / 2; } } return representValue; } getVisualMeta( getColorVisual: (value: number, valueState: VisualState) => string ): VisualMeta { // Do not support category. (category axis is ordinal, numerical) if (this.isCategory()) { return; } const stops: VisualMeta['stops'] = []; const outerColors: VisualMeta['outerColors'] = ['', '']; const visualMapModel = this; function setStop(interval: [number, number], valueState?: VisualState) { const representValue = visualMapModel.getRepresentValue({ interval: interval }) as number;// Not category if (!valueState) { valueState = visualMapModel.getValueState(representValue); } const color = getColorVisual(representValue, valueState); if (interval[0] === -Infinity) { outerColors[0] = color; } else if (interval[1] === Infinity) { outerColors[1] = color; } else { stops.push( {value: interval[0], color: color}, {value: interval[1], color: color} ); } } // Suplement const pieceList = this._pieceList.slice(); if (!pieceList.length) { pieceList.push({interval: [-Infinity, Infinity]}); } else { let edge = pieceList[0].interval[0]; edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]}); edge = pieceList[pieceList.length - 1].interval[1]; edge !== Infinity && pieceList.push({interval: [edge, Infinity]}); } let curr = -Infinity; zrUtil.each(pieceList, function (piece) { const interval = piece.interval; if (interval) { // Fulfill gap. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange'); setStop(interval.slice() as [number, number]); curr = interval[1]; } }, this); return {stops: stops, outerColors: outerColors}; } static defaultOption = inheritDefaultOption(VisualMapModel.defaultOption, { selected: null, minOpen: false, // Whether include values that smaller than `min`. maxOpen: false, // Whether include values that bigger than `max`. align: 'auto', // 'auto', 'left', 'right' itemWidth: 20, itemHeight: 14, itemSymbol: 'roundRect', pieces: null, categories: null, splitNumber: 5, selectedMode: 'multiple', // Can be 'multiple' or 'single'. itemGap: 10, // The gap between two items, in px. hoverLink: true // Enable hover highlight. }) as PiecewiseVisualMapOption; }; type ResetMethod = (outPieceList: InnerVisualPiece[]) => void; /** * Key is this._mode * @type {Object} * @this {module:echarts/component/viusalMap/PiecewiseMode} */ const resetMethods: Dictionary<ResetMethod> & ThisType<PiecewiseModel> = { splitNumber(outPieceList) { const thisOption = this.option; let precision = Math.min(thisOption.precision, 20); const dataExtent = this.getExtent(); let splitNumber = thisOption.splitNumber; splitNumber = Math.max(parseInt(splitNumber as unknown as string, 10), 1); thisOption.splitNumber = splitNumber; let splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber; // Precision auto-adaption while (+splitStep.toFixed(precision) !== splitStep && precision < 5) { precision++; } thisOption.precision = precision; splitStep = +splitStep.toFixed(precision); if (thisOption.minOpen) { outPieceList.push({ interval: [-Infinity, dataExtent[0]], close: [0, 0] }); } for ( let index = 0, curr = dataExtent[0]; index < splitNumber; curr += splitStep, index++ ) { const max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep); outPieceList.push({ interval: [curr, max], close: [1, 1] }); } if (thisOption.maxOpen) { outPieceList.push({ interval: [dataExtent[1], Infinity], close: [0, 0] }); } reformIntervals(outPieceList as Required<InnerVisualPiece>[]); zrUtil.each(outPieceList, function (piece, index) { piece.index = index; piece.text = this.formatValueText(piece.interval); }, this); }, categories(outPieceList) { const thisOption = this.option; zrUtil.each(thisOption.categories, function (cate) { // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。 // 是否改一致。 outPieceList.push({ text: this.formatValueText(cate, true), value: cate }); }, this); // See "Order Rule". normalizeReverse(thisOption, outPieceList); }, pieces(outPieceList) { const thisOption = this.option; zrUtil.each(thisOption.pieces, function (pieceListItem, index) { if (!zrUtil.isObject(pieceListItem)) { pieceListItem = {value: pieceListItem}; } const item: InnerVisualPiece = {text: '', index: index}; if (pieceListItem.label != null) { item.text = pieceListItem.label; } if (pieceListItem.hasOwnProperty('value')) { const value = item.value = pieceListItem.value; item.interval = [value, value]; item.close = [1, 1]; } else { // `min` `max` is legacy option. // `lt` `gt` `lte` `gte` is recommanded. const interval = item.interval = [] as unknown as [number, number]; const close: typeof item.close = item.close = [0, 0]; const closeList = [1, 0, 1] as const; const infinityList = [-Infinity, Infinity]; const useMinMax = []; for (let lg = 0; lg < 2; lg++) { const names = ([['gte', 'gt', 'min'], ['lte', 'lt', 'max']] as const)[lg]; for (let i = 0; i < 3 && interval[lg] == null; i++) { interval[lg] = pieceListItem[names[i]]; close[lg] = closeList[i]; useMinMax[lg] = i === 2; } interval[lg] == null && (interval[lg] = infinityList[lg]); } useMinMax[0] && interval[1] === Infinity && (close[0] = 0); useMinMax[1] && interval[0] === -Infinity && (close[1] = 0); if (__DEV__) { if (interval[0] > interval[1]) { console.warn( 'Piece ' + index + 'is illegal: ' + interval + ' lower bound should not greater then uppper bound.' ); } } if (interval[0] === interval[1] && close[0] && close[1]) { // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}], // we use value to lift the priority when min === max item.value = interval[0]; } } item.visual = VisualMapping.retrieveVisuals(pieceListItem); outPieceList.push(item); }, this); // See "Order Rule". normalizeReverse(thisOption, outPieceList); // Only pieces reformIntervals(outPieceList as Required<InnerVisualPiece>[]); zrUtil.each(outPieceList, function (piece) { const close = piece.close; const edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]]; piece.text = piece.text || this.formatValueText( piece.value != null ? piece.value : piece.interval, false, edgeSymbols ); }, this); } }; function normalizeReverse(thisOption: PiecewiseVisualMapOption, pieceList: InnerVisualPiece[]) { const inverse = thisOption.inverse; if (thisOption.orient === 'vertical' ? !inverse : inverse) { pieceList.reverse(); } } export default PiecewiseModel;
the_stack
import { API, APIEvent, Logger, PlatformAccessory, PlatformConfig, Service, Characteristic, DynamicPlatformPlugin, } from 'homebridge' import { PLUGIN_NAME, PLATFORM_NAME } from './settings' import detectDevices from './utils/detectDevices' import * as remote from './utils/remote' import hasCapability from './utils/hasCapability' import parseKeys from './utils/parseKeys' import { DeviceConfig, SamsungPlatformConfig } from './types/deviceConfig' import { KEYS, APPS } from 'samsung-tv-control' import storage from 'node-persist' import chalk from 'chalk' import path from 'path' const DEVICES_KEY = `${PLATFORM_NAME}_devices` export class SamsungTVHomebridgePlatform implements DynamicPlatformPlugin { public readonly Service: typeof Service = this.api.hap.Service public readonly Characteristic: typeof Characteristic = this.api.hap .Characteristic public readonly tvAccessories: Array<PlatformAccessory> = [] private devices: Array<DeviceConfig> = [] constructor( public readonly log: Logger, public readonly config: PlatformConfig, public readonly api: API, ) { this.log = log this.config = config this.api = api this.Service = api.hap.Service this.Characteristic = api.hap.Characteristic this.log.debug(`Got config`, this.config) // Add devices api.on(APIEvent.DID_FINISH_LAUNCHING, async () => { const dir = path.join(api.user.storagePath(), `.${PLUGIN_NAME}`) this.log.debug(`Using node-persist path:`, dir) await storage.init({ dir, logging: (...args) => this.log.debug(`${PLATFORM_NAME} db -`, ...args), }) let devices = await this.discoverDevices() devices = await this.applyConfig(devices) this.devices = await this.checkDevicePairing(devices) // Register all TV's for (const device of this.devices) { // Log all devices so that the user knows how to configure them this.log.info( chalk`Found device {blue ${device.name}} (${device.modelName}), usn: {green ${device.usn}}`, ) this.log.debug( `${device.name} - (ip: ${device.lastKnownIp}, mac: ${device.mac})`, ) // Register it this.registerTV(device.usn) } // Regularly discover upnp devices and update ip's, locations for registered devices setInterval(async () => { const devices = await this.discoverDevices() this.devices = await this.applyConfig(devices) /** * @todo * add previously not registered devices */ }, 1000 * 60 * 5 /* 5min */) /** * @TODO * Add subscriptions to update getters */ }) } /* * This function is invoked when homebridge restores cached accessories from disk at startup. * It should be used to setup event handlers for characteristics and update respective values. */ configureAccessory(): void { this.log.debug(`Configuring accessory`) } private async discoverDevices() { let existingDevices: Array<DeviceConfig> = await storage.getItem( DEVICES_KEY, ) if (!Array.isArray(existingDevices)) { existingDevices = [] } const devices: Array<DeviceConfig> = [] const samsungTVs = await detectDevices( // this.log, this.config as SamsungPlatformConfig, ) for (const tv of samsungTVs) { const { usn, friendlyName: name, modelName, location: lastKnownLocation, address: lastKnownIp, mac, capabilities, } = tv const device: DeviceConfig = { name, modelName, lastKnownLocation, lastKnownIp, mac, usn, delay: 500, capabilities, } // Check if the tv was in the devices list before // if so, only replace the relevant parts // const existingDevice = devices[usn]; const existingDevice = existingDevices.find((d) => d.usn === usn) if (existingDevice) { this.log.debug( `Rediscovered previously seen device "${device.name}" (${device.modelName}), usn: "${device.usn}"`, ) devices.push({ ...existingDevice, modelName: device.modelName, lastKnownLocation: device.lastKnownLocation, lastKnownIp: device.lastKnownIp, token: device.token, discovered: true, }) } else { this.log.debug( `Discovered new device "${device.name}" (${device.modelName}), usn: "${device.usn}"`, ) devices.push({ ...device, discovered: true }) } } // Add all existing devices that where not discovered for (const existingDevice of existingDevices) { const { usn } = existingDevice const device = devices.find((d) => d.usn === usn) if (!device) { this.log.debug( `Adding not discovered, previously seen device "${existingDevice.name}" (${existingDevice.modelName}), usn: "${existingDevice.usn}"`, ) devices.push(existingDevice) } } // Update devices await storage.updateItem(DEVICES_KEY, devices) return devices } /** * Invokes pairing for all discovered devices. */ private async checkDevicePairing(devices: Array<DeviceConfig>) { for (const device of devices) { // Try pairing if the device was actually discovered and not paired already if (!device.ignore && device.discovered) { try { const token = await remote.getPairing(device, this.log) if (token) { this.log.debug( `Found pairing token "${token}" for "${device.name}" (${device.modelName}), usn: "${device.usn}".`, ) } } catch (err) { this.log.warn( `Did not receive pairing token. Either you did not click "Allow" in time or your TV might not be supported.` + `You might just want to restart homebridge and retry.`, ) } } } return devices } /** * Adds the user modifications to each of devices */ private async applyConfig(devices: Array<DeviceConfig>) { // Get additional options from config const configDevices = (this.config as SamsungPlatformConfig).devices || [] for (const configDevice of configDevices) { // Search for the device in the persistent devices and overwrite the values const { usn } = configDevice const deviceIdx = devices.findIndex((d) => d.usn === usn) if (deviceIdx === -1) { this.log.debug( `Found config for unknown device usn: "${configDevice.usn}"`, configDevice, ) continue } const device = devices[deviceIdx] this.log.debug( `Found config for device "${device.name}" (${device.modelName}), usn: "${device.usn}"`, ) devices[deviceIdx] = { ...device, ...configDevice, } } return devices } private getDevice(usn) { const device = this.devices.find((d) => d.usn === usn) return device as DeviceConfig } private registerTV(usn: string) { const device = this.getDevice(usn) if (!device || device.ignore) { return } // generate a UUID const uuid = this.api.hap.uuid.generate(device.usn) // create the accessory const tvAccessory = new this.api.platformAccessory(device.name, uuid) tvAccessory.context = device this.tvAccessories.push(tvAccessory) // get the name const tvName = device.name // set the accessory category tvAccessory.category = this.api.hap.Categories.TELEVISION // add the tv service const tvService = tvAccessory.addService(this.Service.Television) // set the tv name, manufacturer etc. tvService.setCharacteristic(this.Characteristic.ConfiguredName, tvName) const accessoryService = tvAccessory.getService(this.Service.AccessoryInformation) || new this.Service.AccessoryInformation() accessoryService .setCharacteristic(this.Characteristic.Model, device.modelName) .setCharacteristic( this.Characteristic.Manufacturer, `Samsung Electronics`, ) .setCharacteristic(this.Characteristic.Name, device.name) .setCharacteristic(this.Characteristic.SerialNumber, device.usn) // set sleep discovery characteristic tvService.setCharacteristic( this.Characteristic.SleepDiscoveryMode, this.Characteristic.SleepDiscoveryMode.ALWAYS_DISCOVERABLE, ) // handle on / off events using the Active characteristic tvService .getCharacteristic(this.Characteristic.Active) .on(`get`, async (callback) => { this.log.debug(`${tvName} - GET Active`) try { const isActive = await remote.getActive(this.getDevice(usn)) callback(null, isActive) } catch (err) { callback(err) } }) .on(`set`, async (newValue, callback) => { this.log.debug(`${tvName} - SET Active => setNewValue: ${newValue}`) try { await remote.setActive(this.getDevice(usn), newValue as boolean) tvService.updateCharacteristic( this.Characteristic.Active, newValue ? this.Characteristic.Active.ACTIVE : this.Characteristic.Active.INACTIVE, ) callback(null) } catch (err) { callback(err) } }) // Update the active state every 15 seconds setInterval(async () => { let newState = this.Characteristic.Active.ACTIVE try { const isActive = await remote.getActive(this.getDevice(usn)) if (!isActive) { newState = this.Characteristic.Active.INACTIVE } } catch (err) { newState = this.Characteristic.Active.INACTIVE } // this.log.debug('Polled tv active state', newState); tvService.updateCharacteristic(this.Characteristic.Active, newState) }, 1000 * 15) const canGetBrightness = hasCapability(device, `GetBrightness`) const canSetBrightness = hasCapability(device, `SetBrightness`) if (canGetBrightness) { tvService .getCharacteristic(this.Characteristic.Brightness) .on(`get`, async (callback) => { this.log.debug(`${tvName} - GET Brightness`) try { const brightness = await remote.getBrightness(this.getDevice(usn)) callback(null, brightness) } catch (err) { callback(err) } }) } if (canSetBrightness) { tvService .getCharacteristic(this.Characteristic.Brightness) .on(`set`, async (newValue, callback) => { this.log.debug( `${tvName} - SET Brightness => setNewValue: ${newValue}`, ) try { await remote.setBrightness(this.getDevice(usn), newValue as number) tvService.updateCharacteristic( this.Characteristic.Brightness, newValue, ) callback(null) } catch (err) { callback(err) } }) } // handle remote control input tvService .getCharacteristic(this.Characteristic.RemoteKey) .on(`set`, async (newValue, callback) => { try { switch (newValue) { case this.Characteristic.RemoteKey.REWIND: { this.log.debug(`${tvName} - SET Remote Key Pressed: REWIND`) await remote.rewind(this.getDevice(usn)) break } case this.Characteristic.RemoteKey.FAST_FORWARD: { this.log.debug(`${tvName} - SET Remote Key Pressed: FAST_FORWARD`) await remote.fastForward(this.getDevice(usn)) break } case this.Characteristic.RemoteKey.NEXT_TRACK: { this.log.debug(`${tvName} - SET Remote Key Pressed: NEXT_TRACK`) break } case this.Characteristic.RemoteKey.PREVIOUS_TRACK: { this.log.debug( `${tvName} - SET Remote Key Pressed: PREVIOUS_TRACK`, ) break } case this.Characteristic.RemoteKey.ARROW_UP: { this.log.debug(`${tvName} - SET Remote Key Pressed: ARROW_UP`) await remote.arrowUp(this.getDevice(usn)) break } case this.Characteristic.RemoteKey.ARROW_DOWN: { this.log.debug(`${tvName} - SET Remote Key Pressed: ARROW_DOWN`) await remote.arrowDown(this.getDevice(usn)) break } case this.Characteristic.RemoteKey.ARROW_LEFT: { this.log.debug(`${tvName} - SET Remote Key Pressed: ARROW_LEFT`) await remote.arrowLeft(this.getDevice(usn)) break } case this.Characteristic.RemoteKey.ARROW_RIGHT: { this.log.debug(`${tvName} - SET Remote Key Pressed: ARROW_RIGHT`) await remote.arrowRight(this.getDevice(usn)) break } case this.Characteristic.RemoteKey.SELECT: { this.log.debug(`${tvName} - SET Remote Key Pressed: SELECT`) await remote.select(this.getDevice(usn)) break } case this.Characteristic.RemoteKey.BACK: { this.log.debug(`${tvName} - SET Remote Key Pressed: BACK`) await remote.back(this.getDevice(usn)) break } case this.Characteristic.RemoteKey.EXIT: { this.log.debug(`${tvName} - SET Remote Key Pressed: EXIT`) await remote.exit(this.getDevice(usn)) break } case this.Characteristic.RemoteKey.PLAY_PAUSE: { this.log.debug(`${tvName} - SET Remote Key Pressed: PLAY_PAUSE`) break } case this.Characteristic.RemoteKey.INFORMATION: { this.log.debug(`${tvName} - SET Remote Key Pressed: INFORMATION`) await remote.info(this.getDevice(usn)) break } } } catch (err) { callback(err) return } callback(null) }) /** * Create a speaker service to allow volume control */ const speakerService = tvAccessory.addService( this.Service.TelevisionSpeaker, ) /** * We have these scenarios * 1. GetVolume + SetVolume: * => VolumeControlType.Absolute * => Add Volume Characteristic with get/set * => Also add VolumeSelector * (2.) GetVolume but (no SetVolume) * ...same as 1. because SetVolume can be simulated * by inc./decr. volume step by step * => ~~VolumeControlType.RELATIVE_WITH_CURRENT~~ * => ~~Add Volume Characteristic with getter only~~ * 3. No GetVolume upnp capabilities: * => VolumeControlType.RELATIVE * => Add VolumeSelector Characteristic */ let volumeControlType = this.Characteristic.VolumeControlType.ABSOLUTE const canGetVolume = hasCapability(device, `GetVolume`) if (!canGetVolume) { volumeControlType = this.Characteristic.VolumeControlType.RELATIVE this.log.debug(`${tvName} - VolumeControlType RELATIVE`) } else { this.log.debug(`${tvName} - VolumeControlType ABSOLUTE`) } speakerService .setCharacteristic( this.Characteristic.Active, this.Characteristic.Active.ACTIVE, ) .setCharacteristic( this.Characteristic.VolumeControlType, volumeControlType, ) if (canGetVolume) { speakerService .getCharacteristic(this.Characteristic.Volume) .on(`get`, async (callback) => { this.log.debug(`${tvName} - GET Volume`) try { const volume = await remote.getVolume(this.getDevice(usn)) callback(null, volume) } catch (err) { callback(err) } }) } // When we can get the volume, we can always set the volume // directly or simulate it by multiple volup/downs if (canGetVolume) { speakerService .getCharacteristic(this.Characteristic.Volume) .on(`set`, async (newValue, callback) => { this.log.debug(`${tvName} - SET Volume => setNewValue: ${newValue}`) try { await remote.setVolume(this.getDevice(usn), newValue as number) speakerService .getCharacteristic(this.Characteristic.Mute) .updateValue(false) callback(null) } catch (err) { callback(err) } }) } // VolumeSelector can be used in all scenarios speakerService .getCharacteristic(this.Characteristic.VolumeSelector) .on(`set`, async (newValue, callback) => { this.log.debug( `${tvName} - SET VolumeSelector => setNewValue: ${newValue}`, ) try { if (newValue === this.Characteristic.VolumeSelector.INCREMENT) { await remote.volumeUp(this.getDevice(usn)) } else { await remote.volumeDown(this.getDevice(usn)) } const volume = await remote.getVolume(this.getDevice(usn)) speakerService .getCharacteristic(this.Characteristic.Mute) .updateValue(false) speakerService .getCharacteristic(this.Characteristic.Volume) .updateValue(volume) callback(null) } catch (err) { callback(err) } }) const canGetMute = hasCapability(device, `GetMute`) speakerService .getCharacteristic(this.Characteristic.Mute) .on(`get`, async (callback) => { this.log.debug(`${tvName} - GET Mute`) // When mute cannot be fetched always pretend not to be muted // for now... if (!canGetMute) { callback(null, false) return } try { const muted = await remote.getMute(this.getDevice(usn)) callback(null, muted) } catch (err) { callback(err) } }) .on(`set`, async (value, callback) => { this.log.debug(`${tvName} - SET Mute: ${value}`) try { await remote.setMute(this.getDevice(usn), value as boolean) callback(null) } catch (err) { callback(err) } }) tvService.addLinkedService(speakerService) const inputSources = [ { label: `-`, type: this.Characteristic.InputSourceType.OTHER }, { label: `TV`, type: this.Characteristic.InputSourceType.TUNER, fn: remote.openTV, }, ] const sources = [...inputSources] const { inputs = [] } = device for (const cInput of inputs) { // Opening apps if (APPS[cInput.keys]) { sources.push({ label: cInput.name, type: this.Characteristic.InputSourceType.APPLICATION, fn: async (config: DeviceConfig) => { await remote.openApp(config, APPS[cInput.keys]) }, }) continue } // Sending keys const keys = parseKeys(cInput, device, this.log) const type = keys.length === 1 && /^KEY_HDMI[0-4]?$/.test(keys[0]) ? this.Characteristic.InputSourceType.HDMI : this.Characteristic.InputSourceType.OTHER sources.push({ label: cInput.name, type, fn: async (config: DeviceConfig) => { await remote.sendKeys(config, keys as KEYS[]) }, }) } // Set current input source to 0 = tv tvService.updateCharacteristic(this.Characteristic.ActiveIdentifier, 0) // handle input source changes let resetActiveIdentifierTimer: NodeJS.Timeout tvService .getCharacteristic(this.Characteristic.ActiveIdentifier) .on(`set`, async (newValue, callback) => { // Clear old timeout if not cleared already clearTimeout(resetActiveIdentifierTimer) // the value will be the value you set for the Identifier Characteristic // on the Input Source service that was selected - see input sources below. const inputSource = sources[newValue as any] this.log.debug( `${tvName} - SET Active Identifier => setNewValue: ${newValue} (${inputSource.label})`, ) try { if (typeof inputSource.fn === `function`) { await inputSource.fn(this.getDevice(usn)) } tvService.updateCharacteristic( this.Characteristic.ActiveIdentifier, newValue, ) } catch (err) { callback(err) return } // Switch back to "TV" input source after 3 seconds resetActiveIdentifierTimer = setTimeout(() => { tvService.updateCharacteristic( this.Characteristic.ActiveIdentifier, 0, ) }, 3000) callback(null) }) for (let i = 0; i < sources.length; ++i) { const { label, type } = sources[i] const inputService = tvAccessory.addService( this.Service.InputSource, /* `input-${i}` */ label, label, ) inputService .setCharacteristic(this.Characteristic.Identifier, i) .setCharacteristic(this.Characteristic.ConfiguredName, label) .setCharacteristic( this.Characteristic.IsConfigured, this.Characteristic.IsConfigured.CONFIGURED, ) .setCharacteristic( this.Characteristic.CurrentVisibilityState, this.Characteristic.CurrentVisibilityState.SHOWN, ) .setCharacteristic(this.Characteristic.InputSourceType, type) tvService.addLinkedService(inputService) } /** * Publish as external accessory * Only one TV can exist per bridge, to bypass this limitation, you should * publish your TV as an external accessory. */ this.api.publishExternalAccessories(PLUGIN_NAME, [tvAccessory]) } }
the_stack
// Local Store Schema (v2) // // keys: // encryption key and password hint storage // hint: string // password hint as plain text // key/<ID>: key_agent.Key // encrypted encryption key, plus metadata // // for PBKDF2 // // // items: // encrypted item content and sync metadata // index: OverviewMap // current overview and revision data for all items // lastSynced/<Item ID>: string // last-synced revision of item <Item ID> // revision/<rev ID>: ItemRevision // item overview and content (both encrypted) for // // a particular revision of an item import assert = require('assert'); import asyncutil = require('./base/asyncutil'); import cached = require('./base/cached'); import collectionutil = require('./base/collectionutil'); import event_stream = require('./base/event_stream'); import item_store = require('./item_store'); import key_agent = require('./key_agent'); import key_value_store = require('./base/key_value_store'); // JSON structure that stores the current overview // data and revision IDs for all items in the database interface OverviewMap { [index: string]: ItemIndexEntry; } // JSON structure used to store item revisions // in the database interface ItemRevision { parentRevision: string; overview: ItemOverview; content: item_store.ItemContent; } // JSON structure used to store item overview // data in the database interface ItemOverview { title: string; updatedAt: number; createdAt: number; trashed: boolean; typeName: string; openContents: item_store.ItemOpenContents; locations: string[]; account: string; revision: string; parentRevision: string; } // JSON structure used to store entries in the item // index. This consists of item overview data // plus the last-sync timestamp interface ItemIndexEntry extends ItemOverview { lastSyncedAt?: number; } interface LastSyncEntry { timestamp: number; /** Revision of the item in the local store. */ local: string; /** Revision of the item in the cloud store. */ external: string; } var SCHEMA_VERSION = 3; // prefix for encryption key entries in the encryption key // object store var KEY_ID_PREFIX = 'key/'; export class Store implements item_store.SyncableStore { private database: key_value_store.Database; private name: string; private keyAgent: key_agent.KeyAgent; private keyStore: key_value_store.ObjectStore; private itemStore: key_value_store.ObjectStore; private indexUpdateQueue: collectionutil.BatchedUpdateQueue< item_store.Item >; private itemIndex: cached.Cached<OverviewMap>; onKeysUpdated: event_stream.EventStream<key_agent.Key[]>; onItemUpdated: event_stream.EventStream<item_store.Item>; constructor( database: key_value_store.Database, name: string, keyAgent: key_agent.KeyAgent ) { this.database = database; this.keyAgent = keyAgent; this.name = name; this.onItemUpdated = new event_stream.EventStream<item_store.Item>(); this.onKeysUpdated = new event_stream.EventStream<key_agent.Key[]>(); this.initDatabase(); this.indexUpdateQueue = new collectionutil.BatchedUpdateQueue( (updates: item_store.Item[]) => { return this.updateIndex(updates); } ); this.itemIndex = new cached.Cached<OverviewMap>( () => { return this.readItemIndex(); }, update => { return this.writeItemIndex(update); } ); this.keyAgent.onLock().listen(() => { this.itemIndex.clear(); }); } private resetDatabase( schemaUpdater: key_value_store.DatabaseSchemaModifier ) { schemaUpdater.storeNames().forEach(name => { schemaUpdater.deleteStore(name); }); schemaUpdater.createStore('keys'); schemaUpdater.createStore('items'); } private initDatabase() { this.database.open(this.name, SCHEMA_VERSION, schemaUpdater => { // when opening databases with schema versions prior to the // first public beta release, we just reset the database // and re-sync from the cloud if (schemaUpdater.currentVersion() < 3) { this.resetDatabase(schemaUpdater); } }); this.keyStore = this.database.store('keys'); this.itemStore = this.database.store('items'); } clear() { this.itemIndex.clear(); return this.database.delete().then(() => { this.initDatabase(); }); } unlock(pwd: string): Promise<void> { return item_store.unlockStore(this, this.keyAgent, pwd); } listItemStates(): Promise<item_store.ItemState[]> { return item_store.itemStates(this); } listItems( opts: item_store.ListItemsOptions = {} ): Promise<item_store.Item[]> { return this.itemIndex.get().then(overviewMap => { var items: item_store.Item[] = []; Object.keys(overviewMap).forEach(key => { var overview = overviewMap[key]; var item = this.itemFromOverview(key, overview); if (!item.isTombstone() || opts.includeTombstones) { items.push(item); } }); return items; }); } private getLastSyncEntries(ids: string[]): Promise<LastSyncEntry[]> { return Promise.all( ids.map(id => { return this.itemStore.get<LastSyncEntry>('lastSynced/' + id); }) ); } private updateIndex(updatedItems: item_store.Item[]) { var overviewMap = <OverviewMap>{}; var updatedItemIds = updatedItems.map(item => { return item.uuid; }); return asyncutil .all2([ this.itemIndex.get(), this.getLastSyncEntries(updatedItemIds), ]) .then(result => { overviewMap = <OverviewMap>result[0]; if (!overviewMap) { overviewMap = {}; } var lastSyncTimes = (<LastSyncEntry[]>result[1]).map(entry => { return entry ? entry.timestamp : 0; }); updatedItems.forEach((item, index) => { var entry: ItemIndexEntry = this.overviewFromItem(item); entry.lastSyncedAt = lastSyncTimes[index]; assert(entry.lastSyncedAt !== null); overviewMap[item.uuid] = entry; }); return this.itemIndex.set(overviewMap); }); } private itemFromOverview(uuid: string, overview: ItemOverview) { var item = new item_store.Item(this, uuid); item.title = overview.title; item.updatedAt = new Date(overview.updatedAt); item.createdAt = new Date(overview.createdAt); item.trashed = overview.trashed; item.typeName = overview.typeName; item.openContents = overview.openContents; item.account = overview.account; item.locations = overview.locations; item.revision = overview.revision; item.parentRevision = overview.parentRevision; return item; } private overviewFromItem(item: item_store.Item) { return <ItemOverview>{ title: item.title, updatedAt: item.updatedAt.getTime(), createdAt: item.createdAt.getTime(), trashed: item.trashed, typeName: <string>item.typeName, openContents: item.openContents, locations: item.locations, account: item.account, revision: item.revision, parentRevision: item.parentRevision, }; } loadItem( uuid: string, revision?: string ): Promise<item_store.ItemAndContent> { if (revision) { return asyncutil .all2([ this.overviewKey(), this.itemStore.get<string>('revisions/' + revision), ]) .then(keyAndRevision => { var key = <string>keyAndRevision[0]; var revisionData = <string>keyAndRevision[1]; return this.decrypt<ItemRevision>(key, revisionData); }) .then(revision => { var item = this.itemFromOverview(uuid, revision.overview); assert.equal(item.revision, revision.overview.revision); item.parentRevision = revision.parentRevision; return { item: item, content: revision.content, }; }); } else { return this.itemIndex.get().then(overviewMap => { if (uuid in overviewMap) { return this.loadItem(uuid, overviewMap[uuid].revision); } else { throw new Error('No such item ' + uuid); } }); } } saveItem( item: item_store.Item, source: item_store.ChangeSource ): Promise<void> { if (source !== item_store.ChangeSource.Sync) { // set last-modified time to current time item.updateTimestamps(); } else { // when syncing an item from another store, it // must already have been saved assert(item.createdAt); assert(item.updatedAt); } var key: string; return this.keyForItem(item) .then(_key => { key = _key; return item.getContent(); }) .then(content => { item.updateOverviewFromContent(content); item.parentRevision = item.revision; item.revision = item_store.generateRevisionId({ item: item, content: content, }); var overview = this.overviewFromItem(item); var revision = { parentRevision: item.parentRevision, overview: overview, content: content, }; return this.encrypt(key, revision); }) .then(revisionData => { var indexUpdated = this.indexUpdateQueue.push(item); var revisionSaved = this.itemStore.set( 'revisions/' + item.revision, revisionData ); return asyncutil.eraseResult( Promise.all([indexUpdated, revisionSaved]) ); }) .then(() => { this.onItemUpdated.publish(item); }); } getContent(item: item_store.Item): Promise<item_store.ItemContent> { var key: string; return this.keyForItem(item) .then(_key => { key = _key; return this.itemStore.get<string>('revisions/' + item.revision); }) .then(revisionData => { return this.decrypt<ItemRevision>(key, revisionData); }) .then(revision => { return revision.content; }); } getRawDecryptedData(item: item_store.Item): Promise<string> { return Promise.reject<string>( new Error('getRawDecryptedData() is not implemented') ); } listKeys(): Promise<key_agent.Key[]> { return key_value_store .listKeys(this.keyStore, KEY_ID_PREFIX) .then(keyIds => { var keys: Promise<key_agent.Key>[] = []; keyIds.forEach(id => { keys.push(this.keyStore.get<key_agent.Key>(id)); }); return Promise.all(keys); }); } saveKeys(keys: key_agent.Key[], hint: string): Promise<void> { return key_value_store .listKeys(this.keyStore, KEY_ID_PREFIX) .then(keyIds => { // remove existing keys var removeOps = keyIds.map(id => { return this.keyStore.remove(id); }); return Promise.all(removeOps); }) .then(() => { // save new keys and hint var keysSaved: Promise<void>[] = []; keys.forEach(key => { keysSaved.push( this.keyStore.set(KEY_ID_PREFIX + key.identifier, key) ); }); keysSaved.push(this.keyStore.set('hint', hint)); return Promise.all(keysSaved); }) .then(() => { this.onKeysUpdated.publish(keys); }); } passwordHint(): Promise<string> { return this.keyStore.get<string>('hint'); } getLastSyncedRevision(uuid: string, storeID: string) { return this.itemStore .get<LastSyncEntry>(`lastSynced/${storeID}/${uuid}`) .then(entry => { if (entry) { return entry; } else { return null; } }); } setLastSyncedRevision( item: item_store.Item, storeID: string, revision?: item_store.RevisionPair ) { let key = `lastSynced/${storeID}/${item.uuid}`; let saved: Promise<void>; if (revision) { saved = this.itemStore.set(key, { local: revision.local, external: revision.external, timestamp: item.updatedAt, }); } else { saved = this.itemStore.remove(key); } return saved.then(() => this.indexUpdateQueue.push(item)); } lastSyncRevisions(storeID: string) { let revisions = new Map<string, item_store.RevisionPair>(); let prefix = `lastSynced/${storeID}/`; return this.itemStore .iterate<LastSyncEntry>(prefix, (key, value) => { let uuid = key.slice(prefix.length); revisions.set(uuid, value); }) .then(() => revisions); } // encrypt and write the item overview index. // Use this.itemIndex.set() instead of this method directly. private writeItemIndex(index: OverviewMap) { var key: string; return this.overviewKey() .then(_key => { key = _key; return this.encrypt(key, index); }) .then(encrypted => { return this.itemStore.set('index', encrypted); }); } // fetch and decrypt the item overview index. // Use this.itemIndex.get() instead of this method directly. private readItemIndex() { var key: string; return this.overviewKey() .then(_key => { key = _key; return this.itemStore.get<string>('index'); }) .then(encryptedItemIndex => { if (encryptedItemIndex) { return this.decrypt<OverviewMap>(key, encryptedItemIndex); } else { return Promise.resolve(<OverviewMap>{}); } }); } // returns the key used to encrypt item overview data private overviewKey() { return this.keyAgent.listKeys().then(keyIds => { if (keyIds.length < 1) { throw new Error( 'Unable to fetch overview key. Vault may be locked?' ); } return keyIds[0]; }); } // returns the key used to encrypt content for a given item private keyForItem(item: item_store.Item) { return this.overviewKey(); } private encrypt<T>(key: string, data: T) { var cryptoParams = new key_agent.CryptoParams( key_agent.CryptoAlgorithm.AES128_OpenSSLKey ); return this.keyAgent.encrypt(key, JSON.stringify(data), cryptoParams); } private decrypt<T>(key: string, data: string): Promise<T> { var cryptoParams = new key_agent.CryptoParams( key_agent.CryptoAlgorithm.AES128_OpenSSLKey ); return this.keyAgent .decrypt(key, data, cryptoParams) .then(decrypted => { return <T>JSON.parse(decrypted); }); } }
the_stack
import type { HookContext } from '@feathersjs/feathers'; import { assert } from 'chai'; import { iff } from '../../src'; import { isPromise } from '../../src/common'; let hook: any; let hookBefore: any; let hookAfter: any; let hookFcnSyncCalls: any; let hookFcnAsyncCalls: any; let hookFcnCbCalls: any; let predicateHook: any; let predicateOptions: any; let predicateValue: any; const predicateSync = (hook: any) => { predicateHook = clone(hook); return true; }; const predicateSync2 = (options: any) => (hook: any) => { predicateOptions = clone(options); predicateHook = clone(hook); return true; }; const predicateAsync = (hook: any) => { predicateHook = clone(hook); return new Promise(resolve => resolve(true)); }; const predicateAsync2 = (options: any) => (hook: any) => { predicateOptions = clone(options); predicateHook = clone(hook); return new Promise(resolve => resolve(true)); }; const predicateAsyncFunny = (hook: any) => { predicateHook = clone(hook); return new Promise(resolve => { predicateValue = 'abc'; return resolve(predicateValue); }); }; const hookFcnSync = (hook: HookContext): HookContext => { hookFcnSyncCalls = +1; hook.data.first = hook.data.first.toLowerCase(); return hook; }; const hookFcnAsync = (hook: HookContext) => new Promise<HookContext>(resolve => { hookFcnAsyncCalls = +1; hook.data.first = hook.data.first.toLowerCase(); resolve(hook); }); const hookFcn = (hook: HookContext): HookContext => { hookFcnCbCalls = +1; return hook; }; describe('services iff - sync predicate, sync hook', () => { beforeEach(() => { hookBefore = { type: 'before', method: 'create', data: { first: 'John', last: 'Doe' } }; hookAfter = { type: 'before', method: 'create', data: { first: 'john', last: 'Doe' } }; hook = clone(hookBefore); hookFcnSyncCalls = 0; hookFcnAsyncCalls = 0; }); it('calls sync hook function if truthy non-function', () => { // @ts-ignore iff('a', hookFcnSync)(hook) // @ts-ignore .then((hook: any) => { assert.deepEqual(hook, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.deepEqual(hook, hookAfter); }); }); it('does not call sync hook function if falsey non-function', () => { // @ts-ignore const result = iff('', hookFcnSync)(hook); if (isPromise(result)) { assert.fail(true, false, 'promise unexpectedly returned'); } else { assert.deepEqual(result, hookBefore); assert.equal(hookFcnSyncCalls, 0); assert.deepEqual(hook, hookBefore); } }); it('calls sync hook function if sync predicate truthy', () => { // @ts-ignore iff(() => 'a', hookFcnSync)(hook) // @ts-ignore .then((hook: any) => { assert.deepEqual(hook, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.deepEqual(hook, hookAfter); }); }); it('does not call sync hook function if sync predicate falsey', () => { // @ts-ignore const result = iff(() => '', hookFcnSync)(hook); if (isPromise(result)) { assert.fail(true, false, 'promise unexpectedly returned'); } else { assert.deepEqual(result, hookBefore); assert.equal(hookFcnSyncCalls, 0); assert.deepEqual(hook, hookBefore); } }); }); describe('services iff - sync predicate, async hook', () => { beforeEach(() => { hookBefore = { type: 'before', method: 'create', data: { first: 'John', last: 'Doe' } }; hookAfter = { type: 'before', method: 'create', data: { first: 'john', last: 'Doe' } }; hook = clone(hookBefore); hookFcnSyncCalls = 0; hookFcnAsyncCalls = 0; }); it('calls async hook function if sync predicate truthy', (done: any) => { const result = iff(true, hookFcnAsync)(hook); if (isPromise(result)) { // @ts-ignore result.then((result1: any) => { assert.deepEqual(result1, hookAfter); assert.equal(hookFcnAsyncCalls, 1); assert.deepEqual(hook, hookAfter); done(); }); } else { assert.fail(true, false, 'promise unexpectedly not returned'); } }); it('does not call async hook function if sync predicate falsey', () => { const result = iff(false, hookFcnAsync)(hook); if (isPromise(result)) { assert.fail(true, false, 'promise unexpectedly returned'); } else { assert.deepEqual(result, hookBefore); assert.equal(hookFcnAsyncCalls, 0); assert.deepEqual(hook, hookBefore); } }); it('calls async hook function if sync predicate returns truthy', (done: any) => { const result = iff(() => true, hookFcnAsync)(hook); if (isPromise(result)) { // @ts-ignore result.then((result1: any) => { assert.deepEqual(result1, hookAfter); assert.equal(hookFcnAsyncCalls, 1); assert.deepEqual(hook, hookAfter); done(); }); } else { assert.fail(true, false, 'promise unexpectedly not returned'); } }); }); describe('services iff - async predicate, sync hook', () => { beforeEach(() => { hookBefore = { type: 'before', method: 'create', data: { first: 'John', last: 'Doe' } }; hookAfter = { type: 'before', method: 'create', data: { first: 'john', last: 'Doe' } }; hook = clone(hookBefore); hookFcnSyncCalls = 0; hookFcnAsyncCalls = 0; }); it('calls sync hook function if aync predicate truthy', (done: any) => { const result = iff(() => new Promise(resolve => resolve(true)), hookFcnSync)(hook); if (isPromise(result)) { // @ts-ignore result.then((result1: any) => { assert.deepEqual(result1, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.deepEqual(result1, hookAfter); done(); }); } else { assert.fail(true, false, 'promise unexpectedly not returned'); } }); it('does not call sync hook function if async predicate falsey', (done: any) => { const result = iff(() => new Promise(resolve => resolve(false)), hookFcnSync)(hook); if (isPromise(result)) { // @ts-ignore result.then((result1: any) => { assert.deepEqual(result1, hookBefore); assert.equal(hookFcnSyncCalls, 0); assert.deepEqual(hook, hookBefore); done(); }); } else { assert.fail(true, false, 'promise unexpectedly not returned'); } }); }); describe('services iff - async predicate, async hook', () => { beforeEach(() => { hookBefore = { type: 'before', method: 'create', data: { first: 'John', last: 'Doe' } }; hookAfter = { type: 'before', method: 'create', data: { first: 'john', last: 'Doe' } }; hook = clone(hookBefore); hookFcnSyncCalls = 0; hookFcnAsyncCalls = 0; }); it('calls async hook function if aync predicate truthy', (done: any) => { const result = iff(() => new Promise(resolve => resolve(true)), hookFcnAsync)(hook); if (isPromise(result)) { // @ts-ignore result.then((result1: any) => { assert.deepEqual(result1, hookAfter); assert.equal(hookFcnAsyncCalls, 1); assert.deepEqual(result1, hookAfter); done(); }); } else { assert.fail(true, false, 'promise unexpectedly not returned'); } }); it('does not call async hook function if async predicate falsey', (done: any) => { const result = iff(() => new Promise(resolve => resolve(false)), hookFcnAsync)(hook); if (isPromise(result)) { // @ts-ignore result.then((result1: any) => { assert.deepEqual(result1, hookBefore); assert.equal(hookFcnAsyncCalls, 0); assert.deepEqual(hook, hookBefore); done(); }); } else { assert.fail(true, false, 'promise unexpectedly not returned'); } }); }); describe('services iff - sync predicate', () => { beforeEach(() => { hookBefore = { type: 'before', method: 'create', data: { first: 'John', last: 'Doe' } }; hookAfter = { type: 'before', method: 'create', data: { first: 'john', last: 'Doe' } }; hook = clone(hookBefore); hookFcnSyncCalls = 0; hookFcnAsyncCalls = 0; predicateHook = null; predicateOptions = null; }); it('does not need to access hook', () => { // @ts-ignore iff(() => 'a', hookFcnSync)(hook) // @ts-ignore .then((hook: any) => { assert.deepEqual(hook, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.deepEqual(hook, hookAfter); }); }); it('is passed hook as param', () => { iff(predicateSync, hookFcnSync)(hook) // @ts-ignore .then((hook: any) => { assert.deepEqual(predicateHook, hookBefore); assert.deepEqual(hook, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.deepEqual(hook, hookAfter); }); }); it('a higher order predicate can pass more options', () => { iff(predicateSync2({ z: 'z' }), hookFcnSync)(hook) // @ts-ignore .then((hook: any) => { assert.deepEqual(predicateOptions, { z: 'z' }); assert.deepEqual(predicateHook, hookBefore); assert.deepEqual(hook, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.deepEqual(hook, hookAfter); }); }); }); describe('services iff - async predicate', () => { beforeEach(() => { hookBefore = { type: 'before', method: 'create', data: { first: 'John', last: 'Doe' } }; hookAfter = { type: 'before', method: 'create', data: { first: 'john', last: 'Doe' } }; hook = clone(hookBefore); hookFcnSyncCalls = 0; hookFcnAsyncCalls = 0; predicateHook = null; predicateOptions = null; predicateValue = null; }); it('is passed hook as param', (done: any) => { // @ts-ignore const result = iff(predicateAsync, hookFcnSync)(hook); if (isPromise(result)) { // @ts-ignore result.then((result1: any) => { assert.deepEqual(predicateHook, hookBefore); assert.deepEqual(result1, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.deepEqual(result1, hookAfter); done(); }); } else { assert.fail(true, false, 'promise unexpectedly not returned'); } }); it('is resolved', (done: any) => { // @ts-ignore const result = iff(predicateAsyncFunny, hookFcnSync)(hook); if (isPromise(result)) { // @ts-ignore result.then((result1: any) => { assert.deepEqual(predicateHook, hookBefore); assert.deepEqual(result1, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.deepEqual(result1, hookAfter); assert.equal(predicateValue, 'abc'); done(); }); } else { assert.fail(true, false, 'promise unexpectedly not returned'); } }); it('a higher order predicate can pass more options', (done: any) => { // @ts-ignore const result = iff(predicateAsync2({ y: 'y' }), hookFcnSync)(hook); if (isPromise(result)) { // @ts-ignore result.then((result1: any) => { assert.deepEqual(predicateOptions, { y: 'y' }); assert.deepEqual(predicateHook, hookBefore); assert.deepEqual(result1, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.deepEqual(result1, hookAfter); done(); }); } else { assert.fail(true, false, 'promise unexpectedly not returned'); } }); }); describe('services iff - runs multiple hooks', () => { beforeEach(() => { hookBefore = { type: 'before', method: 'create', data: { first: 'John', last: 'Doe' } }; hookAfter = { type: 'before', method: 'create', data: { first: 'john', last: 'Doe' } }; hook = clone(hookBefore); hookFcnSyncCalls = 0; hookFcnAsyncCalls = 0; }); it('runs successfully', (done: any) => { iff(true, hookFcnSync, hookFcnAsync, hookFcn)(hook) // @ts-ignore .then((hook: any) => { assert.deepEqual(hook, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.equal(hookFcnAsyncCalls, 1); assert.equal(hookFcnCbCalls, 1); assert.deepEqual(hook, hookAfter); done(); }); }); it('runs successfully with the array syntax', (done: any) => { // @ts-ignore iff(true, [hookFcnSync, hookFcnAsync, hookFcn])(hook) // @ts-ignore .then((hook: any) => { assert.deepEqual(hook, hookAfter); assert.equal(hookFcnSyncCalls, 1); assert.equal(hookFcnAsyncCalls, 1); assert.equal(hookFcnCbCalls, 1); assert.deepEqual(hook, hookAfter); done(); }); }); }); // Helpers function clone (obj: any) { return JSON.parse(JSON.stringify(obj)); }
the_stack
import * as canaryLoader from './utils/canary-loader'; const { fn, mock } = jest; const { any, anything, objectContaining, stringContaining } = expect; /* Utils */ const canaryLoggingOn = true; const log = (logger: Handler, ...params: any[]) => { if (canaryLoggingOn) { logger(...params); } }; const addHandler = (handlerList: HandlerList, handlerName: string, handler: Handler) => { handlerList[handlerName] = handlerList[handlerName] || []; handlerList[handlerName].push(handler); }; const callHandlers = (handlerList: HandlerList, handlerName: string, ...params: any[]) => { handlerList[handlerName].forEach((handler) => handler(...params)); } /* Page mocks */ const pageTitle = 'Test page title'; const pageUrl = 'https://www.test-canary-url.com'; const mockPage: MockPage = { title: fn(() => Promise.resolve(pageTitle)), url: fn(() => pageUrl), waitFor: fn(() => { }), on: fn((name, func) => addHandler(mockPage._pageHandlers, name, func)), goto: fn(() => { callHandlers(mockPage._pageHandlers, 'response', { url: () => pageUrl, status: () => 200, }); callHandlers(mockPage._pageHandlers, 'load'); return { status: fn(() => 200), }; }), evaluate: fn((expression) => expression()), _pageHandlers: {}, }; /* CloudWatch Mocks */ const mockLog = { info: fn((...params) => log(console.info, params)), warn: fn((...params) => log(console.warn, params)), error: fn((...params) => log(console.error, params)), }; const awsRegionName = 'me-south-1'; const awsAccountId = '56473829'; const canaryName = 'Test canary name'; const canaryUserAgentString = `:::${awsRegionName}:${awsAccountId}::${canaryName}:`; const mockSynthetics = { getPage: fn(() => mockPage), getCanaryUserAgentString: fn(() => canaryUserAgentString), takeScreenshot: fn(() => { }), }; let mockAwsParameters: {[index: string]: string} = {}; const mockParameterStore = { getParameter: fn((options: {Name: string}, callback) => callback(undefined, { Parameter: { Value: mockAwsParameters[options.Name] } })), }; const mockAWS = { SSM: fn(() => mockParameterStore), }; /* HTTP Mocks */ const buildMockResponse = () => { const mockResponse: MockHttpResponse = { statusCode: 200, on: fn((name, func) => addHandler(mockResponse._responseHandlers, name, func)), setEncoding: fn(() => { }), _responseHandlers: {}, }; return mockResponse; }; const buildExecuteAndCacheMockRequest = (httpPackage: any) => { const end = fn(() => { }); const mockRequest: MockHttpRequest = { on: fn((name, func) => addHandler(mockRequest._requestHandlers, name, func)), write: fn((body) => mockRequest._body = JSON.parse(body)), end, _originalEnd: end, _requestHandlers: {}, }; const mockResponse = buildMockResponse(); httpPackage._mockRequests.push({ request: mockRequest, response: mockResponse, }); // Use timeouts to allow time to register handlers setTimeout(() => { callHandlers(mockRequest._requestHandlers, 'response', mockResponse); setTimeout(() => callHandlers(mockResponse._responseHandlers, 'end')); }); return mockRequest; }; const mockHttps: MockHttpModule = { request: fn(() => buildExecuteAndCacheMockRequest(mockHttps)), get: fn(() => buildExecuteAndCacheMockRequest(mockHttps)), _mockRequests: [], }; const mockHttp: MockHttpModule = { request: fn(() => buildExecuteAndCacheMockRequest(mockHttp)), get: fn(() => buildExecuteAndCacheMockRequest(mockHttp)), _mockRequests: [], }; /* Module Mocks */ mock('SyntheticsLogger', () => mockLog, { virtual: true }); mock('Synthetics', () => mockSynthetics, { virtual: true }); mock('aws-sdk', () => mockAWS, { virtual: true }); mock('http', () => ({ ...mockHttp })); mock('https', () => ({ ...mockHttps })); /* Global mocks */ const responseTimeMillis = 3333; const startTimestamp = 777777777777; global.performance = { getEntriesByType: () => [{ loadEventStart: responseTimeMillis }] as PerformanceNavigationTiming[], timeOrigin: startTimestamp, } as any; beforeEach(() => { mockPage._pageHandlers = {}; mockHttp._mockRequests = []; mockHttps._mockRequests = []; global.beforeExporter = undefined; mockAwsParameters = { '/CloudWatchSynthetics/DynatraceUrl': 'https://tenant-id.live.dynatrace.com', '/CloudWatchSynthetics/DynatraceSyntheticsApiToken': 'TEST-TOKEN-111', }; }); describe('buildAndLoadCanary', () => { it('is a simple canary testing tool that merges the canary with the exporter script ' + 'and exposes the original/non-overriden canary exports for testing purposes', async () => { // GIVEN - an instrumented mock canary // We can use an event to read/write to the canary exports before the exporter runs global.beforeExporter = (_exports) => { _exports.addedValue = 'intercepted'; }; // WHEN - the canary is loaded const canary = await canaryLoader.buildAndLoadCanary('./utils/42-demo-canary.js'); // THEN - The canary is loaded as a module expect(canary).toBeTruthy(); // With a (now-overriden) handler const overridenHandler = canary.handler; expect(overridenHandler).toBeTruthy(); // we can access the original canary/exports/handler const originalCanary = canary._originalExports; const originalHandler = originalCanary.handler; expect(originalHandler).toBeTruthy(); // Which is, indeed, a different handler expect(overridenHandler).not.toBe(originalHandler); // The exports used by the canary were successfully modified by the beforeExporter handler expect(canary.addedValue).toBe('intercepted'); // These changes are not reflected in the cached original exports expect(originalCanary.addedValue).toBeUndefined(); // WHEN - the instrumented canary is executed it executes the original handler expect(originalHandler).toHaveBeenCalledTimes(0); expect(await overridenHandler()).toBe(42); expect(originalHandler).toHaveBeenCalledTimes(1); // WHEN - the original handler is executed we find the same result expect(await overridenHandler()).toBe(await originalHandler()); expect(await originalHandler()).toBe(42); // When all is said and done, we leave the handler in its overridden state, // because the canary might get executed again before the canary module is reloaded // and we can only override the handler when the script is first loaded. expect(canary.handler).toBe(overridenHandler); }); }); describe('dynatrace-canary-exporter', () => { it('overrides the first exported function it finds as the canary entry point', async () => { // GIVEN a canary with multiple exports const handler1 = fn(() => { }); const handler2 = fn(() => { }); global.beforeExporter = (_exports) => { _exports.handler1 = handler1; _exports.handler2 = handler2; }; // WHEN the canary is loaded await canaryLoader.buildAndLoadCanary(); // THEN a warning is logged, because it's not clear which function is the canary entry point expect(mockLog.warn).toHaveBeenCalledTimes(1); }); describe('overrides [http|https].[request|get]', () => { it('to instrument api canaries', async () => { // GIVEN an api canary that makes a single request const canary = await canaryLoader.buildAndLoadCanary('../web-api-canary_API-canary.js'); const canaryRequestCount = 1; // WHEN the canary is executed await canary.handler() // THEN 2 requests should be made: canary request + request for pushing results to Dynatrace const totalRequestCount = canaryRequestCount + 1; expect(mockHttps.request).toHaveBeenCalledTimes(totalRequestCount); expect(mockHttps._mockRequests.length).toBe(totalRequestCount); const canaryRequest = mockHttps._mockRequests[0].request; const canaryResponse = mockHttps._mockRequests[0].response; const resultsRequest = mockHttps._mockRequests[1].request; const resultsResponse = mockHttps._mockRequests[1].response; // The canary request/response should get intercepted/overriden expect(canaryRequest.on).toHaveBeenCalledWith('response', any(Function)); expect(canaryRequest.on).toHaveBeenCalledWith('error', any(Function)); expect(canaryRequest.on).toHaveBeenCalledTimes(2 * 2); // x2 = Assuming the original and interceptor listen to the same events expect(canaryResponse.on).toHaveBeenCalledWith('data', any(Function)); expect(canaryResponse.on).toHaveBeenCalledWith('end', any(Function)); expect(canaryResponse.on).toHaveBeenCalledTimes(2 * 2); // x2 = Assuming the original and interceptor listen to the same events expect(canaryRequest.end).not.toBe(canaryRequest._originalEnd); // But overriden functions should still get called expect(canaryRequest._originalEnd).toHaveBeenCalledTimes(1); // The results request/response should not get intercepted/overriden expect(resultsRequest.on).toHaveBeenCalledWith('response', any(Function)); expect(resultsRequest.on).toHaveBeenCalledWith('error', any(Function)); expect(resultsRequest.on).toHaveBeenCalledTimes(2); expect(resultsResponse.on).toHaveBeenCalledWith('data', any(Function)); expect(resultsResponse.on).toHaveBeenCalledWith('end', any(Function)); expect(resultsResponse.on).toHaveBeenCalledTimes(2); expect(resultsRequest.end).toBe(resultsRequest._originalEnd); expect(resultsRequest.end).toHaveBeenCalledTimes(1); // The original overriden http package functions should be restored expect(mockHttps.request).toBe(require('https').request); expect(mockHttps.get).toBe(require('https').get); expect(mockHttp.request).toBe(require('http').request); expect(mockHttp.get).toBe(require('http').get); }); }); describe('overrides synthetics.getPage', () => { it('to listen to page events', async () => { // GIVEN a web page canary const canary = await canaryLoader.buildAndLoadCanary('../web-page-canary_heartbeat-monitoring.js');; // WHEN the canary is executed await canary.handler(); // THEN synthetics.getPage is overriden to intercept page events expect(mockPage.on).toHaveBeenCalledWith('response', any(Function)); expect(mockPage.on).toHaveBeenCalledWith('load', any(Function)); expect(mockPage.on).toHaveBeenCalledTimes(2); }); it('and generate step results', async () => { // GIVEN a web page canary const canary = await canaryLoader.buildAndLoadCanary('../web-page-canary_heartbeat-monitoring.js');; // WHEN the canary is executed await canary.handler(); // THEN a requested should be posted to Dynatrace expect(mockHttps.request).toHaveBeenCalledWith({ host: anything(), path: anything(), port: anything(), method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': stringContaining('Api-Token'), }, }); // With the expected results const result = mockHttps._mockRequests[0].request._body; // Correct monitor definition expect(result.syntheticEngineName).toBe('AWS CloudWatch Synthetics'); expect(result.tests).toEqual([objectContaining({ title: canaryName, enabled: true, deleted: false, locations: [{ id: awsRegionName, enabled: true, }], steps: [{ id: 1, title: pageTitle, }], scheduleIntervalInSeconds: any(Number), })]); // Timestamp is realistic expect(result.messageTimestamp).toBeLessThan(Date.now()); expect(result.messageTimestamp + 1000).toBeGreaterThan(Date.now()); // Correct monitor results expect(result.testResults).toEqual([objectContaining({ totalStepCount: 1, locationResults: [objectContaining({ id: awsRegionName, success: true, stepResults: [{ id: 1, startTimestamp, responseTimeMillis, }], })], })]); // Timestamp is realistic expect(result.testResults[0].locationResults[0].startTimestamp).toBeLessThan(Date.now()); expect(result.testResults[0].locationResults[0].startTimestamp + 1000).toBeGreaterThan(Date.now()); }); }); describe('sanitizes/standardizes provided tenant and host URLs', () => { const thirdPartyResultsApiPath = '/api/v1/synthetic/ext/tests'; const protocol = 'https'; it('SaaS tenant without slash', async () => { // GIVEN a dynatrace SaaS tenant url that is only a protocal and host const host = 'tenant-id.live.dynatrace.com'; const tenantUrl = `${protocol}://${host}`; // That ends WITHOUT a slash mockAwsParameters = { '/CloudWatchSynthetics/DynatraceUrl': tenantUrl }; // WHEN the canary is loaded and executed const canary = await canaryLoader.buildAndLoadCanary('../web-page-canary_heartbeat-monitoring.js') await canary.handler(); // THEN in the configured request: expect(mockHttps.request).toHaveBeenCalledWith(objectContaining({ // The tenant host name should match the request's host host: host, // The path is simply the api path path: thirdPartyResultsApiPath, // The port is left blank resulting in the default protocol port being used port: '', })); }); it('SaaS tenant with slash', async () => { // GIVEN a dynatrace SaaS tenant url that is only a protocal and host const host = 'tenant-id.live.dynatrace.com'; const tenantUrl = `${protocol}://${host}/`; // That ends WITH a slash mockAwsParameters = { '/CloudWatchSynthetics/DynatraceUrl': tenantUrl }; // WHEN the canary is loaded and executed const canary = await canaryLoader.buildAndLoadCanary('../web-page-canary_heartbeat-monitoring.js') await canary.handler(); // THEN the request configuration is the same as a tenant URL that doesn't end with a slash (see above): expect(mockHttps.request).toHaveBeenCalledWith(objectContaining({ host: host, path: thirdPartyResultsApiPath, port: '', })); }); it('SaaS tenant without protocol', async () => { // GIVEN a dynatrace SaaS tenant url that is only a host (WITHOUT a protocol) const host = 'tenant-id.live.dynatrace.com'; mockAwsParameters = { '/CloudWatchSynthetics/DynatraceUrl': host }; // WHEN the canary is loaded and executed const canary = await canaryLoader.buildAndLoadCanary('../web-page-canary_heartbeat-monitoring.js') await canary.handler(); // THEN the request configuration is the same as a tenant URL that does have a protocol, (see above) // because the https protocol is redundant when using the https package: expect(mockHttps.request).toHaveBeenCalledWith(objectContaining({ host: host, path: thirdPartyResultsApiPath, port: '', })); }); it('Managed tenant with additional path', async () => { // GIVEN a dynatrace Managed tenant url with both a host and additional path const host = 'sample.dynatrace-managed.com'; const tenantPath = '/e/00000000-0000-0000-0000-000000000000'; const tenantUrl = `${protocol}://${host}${tenantPath}`; mockAwsParameters = { '/CloudWatchSynthetics/DynatraceUrl': tenantUrl }; // WHEN the canary is loaded and executed const canary = await canaryLoader.buildAndLoadCanary('../web-page-canary_heartbeat-monitoring.js') await canary.handler(); // THEN the additional tenant path is appended to the third-party api path expect(mockHttps.request).toHaveBeenCalledWith(objectContaining({ host: host, path: tenantPath + thirdPartyResultsApiPath, port: '', })); }); it('Managed tenant with additional path and slash', async () => { // GIVEN a dynatrace Managed tenant url with both a host and additional path const host = 'sample.dynatrace-managed.com'; const tenantPath = '/e/00000000-0000-0000-0000-000000000000'; const tenantUrl = `${protocol}://${host}${tenantPath}/`; // That ends WITH a slash mockAwsParameters = { '/CloudWatchSynthetics/DynatraceUrl': tenantUrl }; // WHEN the canary is loaded and executed const canary = await canaryLoader.buildAndLoadCanary('../web-page-canary_heartbeat-monitoring.js') await canary.handler(); // THEN the request configuration is the same as a tenant URL that doesn't end with a slash (see above): expect(mockHttps.request).toHaveBeenCalledWith(objectContaining({ host: host, path: tenantPath + thirdPartyResultsApiPath, port: '', })); }); it('Managed ActiveGate with custom port', async () => { // GIVEN a Managed ActiveGate url with a custom HTTPS port const host = 'sample.dynatrace-managed.com'; const tenantPath = '/e/00000000-0000-0000-0000-000000000000'; const port = '9999'; const tenantUrl = `${protocol}://${host}:${port}${tenantPath}`; mockAwsParameters = { '/CloudWatchSynthetics/DynatraceUrl': tenantUrl }; // WHEN the canary is loaded and executed const canary = await canaryLoader.buildAndLoadCanary('../web-page-canary_heartbeat-monitoring.js') await canary.handler(); // THEN the additional tenant path is appended to the third-party api path expect(mockHttps.request).toHaveBeenCalledWith(objectContaining({ host: host, path: tenantPath + thirdPartyResultsApiPath, port: port, })); }); }); });
the_stack
import { ContractArtifacts, TestContractArtifacts, createERC20DepositTransaction, createETHDepositTransaction, getChallengeRegisteredEvent, getChannelId, Transactions, computeNewOutcome, } from '@statechannels/nitro-protocol'; import { Address, BN, fromNitroSignedState, makeAddress, PrivateKey, SignedState, State, toNitroSignedState, toNitroState, unreachable, } from '@statechannels/wallet-core'; import {constants, Contract, Event, providers, Wallet} from 'ethers'; import {NonceManager} from '@ethersproject/experimental'; import PQueue from 'p-queue'; import {Logger} from 'pino'; import _ from 'lodash'; const MAGIC_ADDRESS_INDICATING_ETH = constants.AddressZero; import {Bytes32} from '../type-aliases'; import {createLogger} from '../logger'; import {defaultTestWalletConfig} from '../config'; import { AllowanceMode, AllocationUpdatedArg, ChainEventSubscriberInterface, ChainRequest, ChainServiceArgs, ChainServiceInterface, FundChannelArg, HoldingUpdatedArg, } from './types'; import {EventTracker} from './event-tracker'; const Deposited = 'Deposited' as const; const AllocationUpdated = 'AllocationUpdated' as const; const ChallengeRegistered = 'ChallengeRegistered' as const; const Concluded = 'Concluded' as const; type DepositedEvent = {type: 'Deposited'; ethersEvent: Event} & HoldingUpdatedArg; type AllocationUpdatedEvent = { type: typeof AllocationUpdated; ethersEvent: Event; } & AllocationUpdatedArg; export class ChainService implements ChainServiceInterface { private logger: Logger; private readonly ethWallet: NonceManager; private provider: providers.JsonRpcProvider; private allowanceMode: AllowanceMode; private channelToEventTrackers: Map<Bytes32, EventTracker[]> = new Map(); // For convenience, can also use addressToContract map private nitroAdjudicator: Contract; private readonly blockConfirmations: number; private transactionQueue = new PQueue({concurrency: 1}); private finalizingChannels: {finalizesAtS: number; channelId: Bytes32}[] = []; constructor({ provider, pk, // TODO require pk to be defined and remove if (!pk) throw (below) pollingInterval, logger, blockConfirmations, allowanceMode, }: Partial<ChainServiceArgs>) { if (!pk) throw new Error('ChainService: Private key not provided'); this.provider = new providers.JsonRpcProvider(provider); this.ethWallet = new NonceManager(new Wallet(pk, this.provider)); this.blockConfirmations = blockConfirmations ?? 5; this.logger = logger ? logger.child({module: 'ChainService'}) : createLogger(defaultTestWalletConfig()); this.allowanceMode = allowanceMode || 'MaxUint'; if (provider && (provider.includes('0.0.0.0') || provider.includes('localhost'))) { pollingInterval = pollingInterval ?? 50; } if (pollingInterval) this.provider.pollingInterval = pollingInterval; /* eslint-disable no-process-env, */ const nitroAdjudicatorAddress = makeAddress( process.env.NITRO_ADJUDICATOR_ADDRESS || constants.AddressZero ); this.nitroAdjudicator = new Contract( nitroAdjudicatorAddress, ContractArtifacts.NitroAdjudicatorArtifact.abi, this.ethWallet ); this.nitroAdjudicator.on(ChallengeRegistered, (...args) => { const event = getChallengeRegisteredEvent(args); this.addFinalizingChannel({channelId: event.channelId, finalizesAtS: event.finalizesAt}); const {channelId, challengeStates, finalizesAt} = event; this.channelToEventTrackers.get(event.channelId)?.map(subscriber => subscriber.challengeRegistered({ channelId, challengeStates: challengeStates.map(s => fromNitroSignedState(s)), finalizesAt, }) ); }); this.nitroAdjudicator.on(Concluded, (channelId, finalizesAtS) => { this.addFinalizingChannel({channelId, finalizesAtS}); }); // this sets up listeners for the "asset holding part" of the nitro adjudicator this.listenForAssetEvents(this.nitroAdjudicator); this.provider.on('block', async (blockTag: providers.BlockTag) => this.checkFinalizingChannels(await this.provider.getBlock(blockTag)) ); } /** * Create and send transactions for the chain requests. * @param chainRequests A collection of chain requests * @returns A collection of transaction responses for the submitted chain requests. */ public async handleChainRequests( chainRequests: ChainRequest[] ): Promise<providers.TransactionResponse[]> { // Bail early so we don't add chatter to the logs if (chainRequests.length === 0) { return []; } const responses: providers.TransactionResponse[] = []; this.logger.trace({chainRequests}, 'Handling chain requests'); for (const chainRequest of chainRequests) { let response; switch (chainRequest.type) { case 'Challenge': response = await this.challenge(chainRequest.challengeStates, chainRequest.privateKey); break; case 'ConcludeAndWithdraw': response = await this.concludeAndWithdraw(chainRequest.finalizationProof); break; case 'FundChannel': response = await this.fundChannel(chainRequest); break; case 'Withdraw': response = await this.withdraw(chainRequest.state); break; default: unreachable(chainRequest); } responses.push(response); } return responses; } public async checkChainId(networkChainId: number): Promise<void> { const rpcChainId = (await this.provider.getNetwork()).chainId; if (rpcChainId !== networkChainId) throw Error( `ChainId mismatch: ${networkChainId} is required but provider reports ${rpcChainId}` ); } // Only used for unit tests destructor(): void { this.logger.trace('Starting destroy'); this.channelToEventTrackers.clear(); this.provider.polling = false; this.provider.removeAllListeners(); this.nitroAdjudicator.removeAllListeners(); this.logger.trace('Completed destroy'); } private async sendTransaction( transactionRequest: providers.TransactionRequest ): Promise<providers.TransactionResponse> { return this.transactionQueue.add(async () => { try { this.logger.debug({...transactionRequest}, 'Submitting transaction to the blockchain'); return await this.ethWallet.sendTransaction(transactionRequest); } catch (err) { // https://github.com/ethers-io/ethers.js/issues/972 this.ethWallet.incrementTransactionCount(-1); this.logger.error({err}, 'Transaction submission failed'); throw err; } }); } async fundChannel(arg: FundChannelArg): Promise<providers.TransactionResponse> { this.logger.info({...arg}, 'fundChannel: entry'); let depositRequest; if (arg.asset === MAGIC_ADDRESS_INDICATING_ETH) { depositRequest = { to: this.nitroAdjudicator.address, value: arg.amount, ...createETHDepositTransaction(arg.channelId, arg.expectedHeld, arg.amount), }; } else { await this.increaseAllowance(arg.asset, arg.amount); depositRequest = { to: this.nitroAdjudicator.address, ...createERC20DepositTransaction(arg.asset, arg.channelId, arg.expectedHeld, arg.amount), }; } const tx = await this.sendTransaction(depositRequest); this.logger.info( { channelId: arg.channelId, nitroAdjudicatorAddress: this.nitroAdjudicator.address, tx: tx.hash, }, 'Finished funding channel' ); return tx; } async concludeAndWithdraw( finalizationProof: SignedState[] ): Promise<providers.TransactionResponse> { if (!finalizationProof.length) throw new Error('ChainService: concludeAndWithdraw was called with an empty array?'); const channelId = getChannelId({ ...finalizationProof[0], participants: finalizationProof[0].participants.map(p => p.signingAddress), }); this.logger.info({channelId}, 'concludeAndWithdraw: entry'); const transactionRequest = { ...Transactions.createConcludeAndTransferAllAssetsTransaction( finalizationProof.flatMap(toNitroSignedState) ), to: this.nitroAdjudicator.address, }; const captureExpectedErrors = async (reason: any) => { if (reason.error?.message.includes('Channel finalized')) { this.logger.warn( {channelId, determinedBy: 'Revert reason'}, 'Transaction to conclude channel failed: channel is already finalized' ); throw new Error('Conclude failed'); } const [, finalizesAt] = await this.nitroAdjudicator.unpackStatus(channelId); const {timestamp: latestBlockTimestamp} = await this.provider.getBlock( this.provider.getBlockNumber() ); // Check if the channel has been finalized in the past if (latestBlockTimestamp >= Number(finalizesAt)) { this.logger.warn( {channelId, determinedBy: 'Javascript check'}, 'Transaction to conclude channel failed: channel is already finalized' ); throw new Error('Conclude failed'); } throw reason; }; const transactionResponse = this.sendTransaction(transactionRequest).catch( captureExpectedErrors ); transactionResponse .then(receipt => { if (receipt) return receipt.wait(); return; }) .catch(captureExpectedErrors); return transactionResponse; } async challenge( challengeStates: SignedState[], privateKey: PrivateKey ): Promise<providers.TransactionResponse> { this.logger.info({challengeStates}, 'challenge: entry'); if (!challengeStates.length) { throw new Error('Must challenge with at least one state'); } const challengeTransactionRequest = { ...Transactions.createChallengeTransaction( challengeStates.flatMap(toNitroSignedState), privateKey ), to: this.nitroAdjudicator.address, }; return this.sendTransaction(challengeTransactionRequest); } async withdraw(state: State): Promise<providers.TransactionResponse> { this.logger.info('withdraw: entry'); const lastState = toNitroState(state); const transactionRequest = { ...Transactions.createTransferAllAssetsTransaction(lastState), to: this.nitroAdjudicator.address, }; return this.sendTransaction(transactionRequest); } // TODO add another public method for transferring from an channel that has already been concluded *and* pushed // i.e. one that calls NitroAdjudicator.transfer. We could call the new method "withdraw" to match the other methods in this class // The new method will uses the latest outcome that we know exists ON CHAIN, which can be "newer" than the latest OFF CHAIN outcome. // Choices: // - the chain service stores the latest outcome in it's own DB table // - the wallet.store stores them // - nothing is stored, and the chain service searches through historic transaction data that it pulls from the provider (seems riskier, but we may need to do this in case we are offline for a time, anyway) registerChannel( channelId: Bytes32, assets: Address[], subscriber: ChainEventSubscriberInterface ): void { this.logger.info({channelId}, 'registerChannel: entry'); const eventTracker = new EventTracker(subscriber, this.logger); this.channelToEventTrackers.set(channelId, [ ...(this.channelToEventTrackers.get(channelId) ?? []), eventTracker, ]); // Fetch the current contract holding, and emit as an event for (const asset of assets) { this.getInitialHoldings(asset, channelId, eventTracker); } // This method is async so it will continue to run after the method has been exited // That's ok since we're just registering some things and/or dispatching some events this.registerFinalizationStatus(channelId); } unregisterChannel(channelId: Bytes32): void { this.logger.info({channelId}, 'unregisterChannel: entry'); this.channelToEventTrackers.set(channelId, []); } private async checkFinalizingChannels(block: providers.Block): Promise<void> { const finalizingChannel = this.finalizingChannels.shift(); if (!finalizingChannel) return; if (finalizingChannel.finalizesAtS > block.timestamp) { this.addFinalizingChannel(finalizingChannel); return; } const {channelId} = finalizingChannel; const [, finalizesAt] = await this.nitroAdjudicator.unpackStatus(channelId); if (finalizesAt === finalizingChannel.finalizesAtS) { // Should we wait for 6 blocks before emitting the finalized event? // Will the wallet sign new states or deposit into the channel based on this event? // The answer is likely no. // So we probably want to emit this event as soon as possible. this.channelToEventTrackers.get(channelId)?.map(subscriber => subscriber.channelFinalized({ channelId, blockNumber: block.number, blockTimestamp: block.timestamp, finalizedAt: finalizingChannel.finalizesAtS, }) ); // Chain storage has a new finalizesAt timestamp } else if (finalizesAt) { this.addFinalizingChannel({channelId, finalizesAtS: finalizesAt}); } this.checkFinalizingChannels(block); } private addFinalizingChannel(arg: {channelId: string; finalizesAtS: number}) { const {channelId, finalizesAtS} = arg; // Only add the finalizing channel if its not already there if (!this.finalizingChannels.some(c => c.channelId === channelId)) { this.finalizingChannels = [ ...this.finalizingChannels, {channelId, finalizesAtS: finalizesAtS}, ]; this.finalizingChannels.sort((a, b) => a.finalizesAtS - b.finalizesAtS); } } private async registerFinalizationStatus(channelId: string): Promise<void> { const finalizesAtS = await this.getFinalizedAt(channelId); if (finalizesAtS !== 0) { this.addFinalizingChannel({channelId, finalizesAtS}); } } private async getFinalizedAt(channelId: string): Promise<number> { const [, finalizesAt] = await this.nitroAdjudicator.unpackStatus(channelId); return finalizesAt; } private async getInitialHoldings( asset: Address, channelId: string, eventTracker: EventTracker ): Promise<void> { // If the destructor has been called we want to abort right away // We use this.provider.polling since we know the destructor sets that to false if (!this.provider.polling) return; const currentBlock = await this.provider.getBlockNumber(); const confirmedBlock = currentBlock - this.blockConfirmations; const currentHolding = BN.from(await this.nitroAdjudicator.holdings(asset, channelId)); let confirmedHolding = BN.from(0); try { // https://docs.ethers.io/v5/api/contract/contract/#Contract--metaclass // provider can lose track of the latest block, force it to reload const overrides = { blockTag: confirmedBlock, }; confirmedHolding = BN.from(await this.nitroAdjudicator.holdings(asset, channelId, overrides)); this.logger.debug( `Successfully read confirmedHoldings (${confirmedHolding}), from block ${confirmedBlock}.` ); } catch (e) { // We should have e.code="CALL_EXCEPTION", but given currentHolding query succeeded, // the cause of exception is obvious this.logger.error( `Error caught while trying to query confirmed holding in block ${confirmedBlock}. ` + `This is likely because the channel is new and is safe to ignore. The error is ${JSON.stringify( e )}` ); } this.logger.debug( `getConfirmedHoldings: from block ${confirmedBlock}, confirmed holding ${confirmedHolding}, current holding ${currentHolding}.` ); /** * Report confirmed holding immediately. * * TODO: below can result in duplicate notifications to subscribers. Consider the following: * 1. Funds are deposited on block 0, generating a deposit event D. * 2. Events are defined as confirmed when the 5th block is mined after a transaction. * 3. A channel is registered with the chain service at block 5. * 4. We check for confirmed events: * D is confirmed, so holdingUpdated is called with the block number 0 and the correct log index. * 5. We check for confirmed holdings: * Holdings in block 5 are confirmed, so holdingUpdated is called with block number of 0 and the DEFAULT log index. * 6. Subscribers are notified of the holdings twice. */ eventTracker.holdingUpdated( { channelId: channelId, asset, amount: confirmedHolding, }, confirmedBlock ); // We're unsure if the same events are also played by contract observer callback, // but need to play it regardless, so subscribers won't miss anything. // See EventTracker documentation const ethersEvents = (await this.nitroAdjudicator.queryFilter({}, confirmedBlock)).sort( e => e.blockNumber ); for (const ethersEvent of ethersEvents) { await this.waitForConfirmations(ethersEvent); this.onAssetEvent(ethersEvent); } } private async waitForConfirmations(event: Event): Promise<void> { // `tx.wait(n)` resolves after n blocks are mined that include the given transaction `tx` // See https://docs.ethers.io/v5/api/providers/types/#providers-TransactionResponse await (await event.getTransaction()).wait(this.blockConfirmations + 1); this.logger.debug( {tx: event.transactionHash}, 'Finished waiting for confirmations; considering transaction finalized' ); } private listenForAssetEvents(adjudicatorContract: Contract): void { // Listen to all contract events adjudicatorContract.on({}, async (ethersEvent: Event) => { this.logger.trace( {address: adjudicatorContract.address, event: ethersEvent}, 'Asset event being handled' ); await this.waitForConfirmations(ethersEvent); this.onAssetEvent(ethersEvent); }); } private async onAssetEvent(ethersEvent: Event): Promise<void> { switch (ethersEvent.event) { case Deposited: { const depositedEvent = await this.getDepositedEvent(ethersEvent); this.channelToEventTrackers.get(depositedEvent.channelId)?.forEach(eventTracker => { eventTracker.holdingUpdated( depositedEvent, depositedEvent.ethersEvent.blockNumber, depositedEvent.ethersEvent.logIndex ); }); } break; case AllocationUpdated: { const AllocationUpdatedEvent = await this.getAllocationUpdatedEvent(ethersEvent); this.channelToEventTrackers .get(AllocationUpdatedEvent.channelId) ?.forEach(eventTracker => { eventTracker.allocationUpdated( AllocationUpdatedEvent, AllocationUpdatedEvent.ethersEvent.blockNumber, AllocationUpdatedEvent.ethersEvent.logIndex ); }); } break; default: this.logger.error(`Unexpected event ${ethersEvent}`); } } private async increaseAllowance(tokenAddress: Address, amount: string): Promise<void> { const tokenContract = new Contract( tokenAddress, TestContractArtifacts.TokenArtifact.abi, this.ethWallet ); switch (this.allowanceMode) { case 'PerDeposit': { const increaseAllowance = tokenContract.interface.encodeFunctionData('increaseAllowance', [ this.nitroAdjudicator.address, amount, ]); const increaseAllowanceRequest = { data: increaseAllowance, to: tokenAddress, }; const tx = await this.sendTransaction(increaseAllowanceRequest); this.logger.info( {tx: tx.hash}, 'Transaction to increase asset holder token allowance successfully submitted' ); break; } case 'MaxUint': { const currentAllowance = await tokenContract.allowance( await this.ethWallet.getAddress(), this.nitroAdjudicator.address ); // Half of MaxUint256 is the threshold for bumping up the allowance if (BN.gt(BN.div(constants.MaxUint256, 2), currentAllowance)) { const approveAllowance = tokenContract.interface.encodeFunctionData('approve', [ this.nitroAdjudicator.address, constants.MaxUint256, ]); const approveAllowanceRequest = { data: approveAllowance, to: tokenContract.address, }; const tx = await this.sendTransaction(approveAllowanceRequest); this.logger.info( {tx: tx.hash}, 'Transaction to approve maximum amount of asset holder spending successfully submitted' ); break; } } } } private async getDepositedEvent(event: Event): Promise<DepositedEvent> { if (!event.args) { throw new Error('Deposited event must have args'); } const [destination, asset, _amountDeposited, destinationHoldings] = event.args; return { type: Deposited, channelId: destination, asset, amount: BN.from(destinationHoldings), ethersEvent: event, }; } private async getAllocationUpdatedEvent(event: Event): Promise<AllocationUpdatedEvent> { if (!event.args) { throw new Error('AllocationUpdated event must have args'); } const [channelId, assetIndex, initialHoldings] = event.args; const tx = await this.provider.getTransaction(event.transactionHash); const {newOutcome, newHoldings, externalPayouts, internalPayouts} = computeNewOutcome( this.nitroAdjudicator.address, {channelId, assetIndex, initialHoldings}, tx ); return { type: AllocationUpdated, channelId: channelId, asset: makeAddress(newOutcome[assetIndex].asset), newHoldings: BN.from(newHoldings), externalPayouts: externalPayouts, internalPayouts: internalPayouts, newAssetOutcome: newOutcome[assetIndex], ethersEvent: event, }; } /** * * @param appDefinition Address of state channels app * * Rejects with 'Bytecode missing' if there is no contract deployed at `appDefinition`. */ public async fetchBytecode(appDefinition: string): Promise<string> { const result = await this.provider.getCode(appDefinition); if (result === '0x') throw new Error('Bytecode missing'); return result; } }
the_stack
import * as Gio from "@gi-types/gio"; import * as GObject from "@gi-types/gobject"; import * as GLib from "@gi-types/glib"; export const ACCESS_POINT_BSSID: string; export const ACCESS_POINT_FLAGS: string; export const ACCESS_POINT_FREQUENCY: string; export const ACCESS_POINT_HW_ADDRESS: string; export const ACCESS_POINT_LAST_SEEN: string; export const ACCESS_POINT_MAX_BITRATE: string; export const ACCESS_POINT_MODE: string; export const ACCESS_POINT_RSN_FLAGS: string; export const ACCESS_POINT_SSID: string; export const ACCESS_POINT_STRENGTH: string; export const ACCESS_POINT_WPA_FLAGS: string; export const ACTIVE_CONNECTION_CONNECTION: string; export const ACTIVE_CONNECTION_DEFAULT: string; export const ACTIVE_CONNECTION_DEFAULT6: string; export const ACTIVE_CONNECTION_DEVICES: string; export const ACTIVE_CONNECTION_DHCP4_CONFIG: string; export const ACTIVE_CONNECTION_DHCP6_CONFIG: string; export const ACTIVE_CONNECTION_ID: string; export const ACTIVE_CONNECTION_IP4_CONFIG: string; export const ACTIVE_CONNECTION_IP6_CONFIG: string; export const ACTIVE_CONNECTION_MASTER: string; export const ACTIVE_CONNECTION_SPECIFIC_OBJECT_PATH: string; export const ACTIVE_CONNECTION_STATE: string; export const ACTIVE_CONNECTION_STATE_FLAGS: string; export const ACTIVE_CONNECTION_TYPE: string; export const ACTIVE_CONNECTION_UUID: string; export const ACTIVE_CONNECTION_VPN: string; export const BRIDGE_VLAN_VID_MAX: number; export const BRIDGE_VLAN_VID_MIN: number; export const CHECKPOINT_CREATED: string; export const CHECKPOINT_DEVICES: string; export const CHECKPOINT_ROLLBACK_TIMEOUT: string; export const CLIENT_ACTIVATING_CONNECTION: string; export const CLIENT_ACTIVE_CONNECTIONS: string; export const CLIENT_ACTIVE_CONNECTION_ADDED: string; export const CLIENT_ACTIVE_CONNECTION_REMOVED: string; export const CLIENT_ALL_DEVICES: string; export const CLIENT_ANY_DEVICE_ADDED: string; export const CLIENT_ANY_DEVICE_REMOVED: string; export const CLIENT_CAN_MODIFY: string; export const CLIENT_CAPABILITIES: string; export const CLIENT_CHECKPOINTS: string; export const CLIENT_CONNECTIONS: string; export const CLIENT_CONNECTION_ADDED: string; export const CLIENT_CONNECTION_REMOVED: string; export const CLIENT_CONNECTIVITY: string; export const CLIENT_CONNECTIVITY_CHECK_AVAILABLE: string; export const CLIENT_CONNECTIVITY_CHECK_ENABLED: string; export const CLIENT_CONNECTIVITY_CHECK_URI: string; export const CLIENT_DBUS_CONNECTION: string; export const CLIENT_DBUS_NAME_OWNER: string; export const CLIENT_DEVICES: string; export const CLIENT_DEVICE_ADDED: string; export const CLIENT_DEVICE_REMOVED: string; export const CLIENT_DNS_CONFIGURATION: string; export const CLIENT_DNS_MODE: string; export const CLIENT_DNS_RC_MANAGER: string; export const CLIENT_HOSTNAME: string; export const CLIENT_INSTANCE_FLAGS: string; export const CLIENT_METERED: string; export const CLIENT_NETWORKING_ENABLED: string; export const CLIENT_NM_RUNNING: string; export const CLIENT_PERMISSIONS_STATE: string; export const CLIENT_PERMISSION_CHANGED: string; export const CLIENT_PRIMARY_CONNECTION: string; export const CLIENT_STARTUP: string; export const CLIENT_STATE: string; export const CLIENT_VERSION: string; export const CLIENT_WIMAX_ENABLED: string; export const CLIENT_WIMAX_HARDWARE_ENABLED: string; export const CLIENT_WIRELESS_ENABLED: string; export const CLIENT_WIRELESS_HARDWARE_ENABLED: string; export const CLIENT_WWAN_ENABLED: string; export const CLIENT_WWAN_HARDWARE_ENABLED: string; export const CONNECTION_CHANGED: string; export const CONNECTION_NORMALIZE_PARAM_IP6_CONFIG_METHOD: string; export const CONNECTION_SECRETS_CLEARED: string; export const CONNECTION_SECRETS_UPDATED: string; export const DBUS_INTERFACE: string; export const DBUS_INTERFACE_DNS_MANAGER: string; export const DBUS_INTERFACE_SETTINGS: string; export const DBUS_INTERFACE_SETTINGS_CONNECTION: string; export const DBUS_INTERFACE_SETTINGS_CONNECTION_SECRETS: string; export const DBUS_INTERFACE_VPN: string; export const DBUS_INTERFACE_VPN_CONNECTION: string; export const DBUS_INVALID_VPN_CONNECTION: string; export const DBUS_NO_ACTIVE_VPN_CONNECTION: string; export const DBUS_NO_VPN_CONNECTIONS: string; export const DBUS_PATH: string; export const DBUS_PATH_AGENT_MANAGER: string; export const DBUS_PATH_DNS_MANAGER: string; export const DBUS_PATH_SECRET_AGENT: string; export const DBUS_PATH_SETTINGS: string; export const DBUS_PATH_SETTINGS_CONNECTION: string; export const DBUS_PATH_VPN: string; export const DBUS_PATH_VPN_CONNECTION: string; export const DBUS_SERVICE: string; export const DBUS_VPN_ALREADY_STARTED: string; export const DBUS_VPN_ALREADY_STOPPED: string; export const DBUS_VPN_BAD_ARGUMENTS: string; export const DBUS_VPN_ERROR_PREFIX: string; export const DBUS_VPN_INTERACTIVE_NOT_SUPPORTED: string; export const DBUS_VPN_SIGNAL_CONNECT_FAILED: string; export const DBUS_VPN_SIGNAL_IP4_CONFIG: string; export const DBUS_VPN_SIGNAL_IP_CONFIG_BAD: string; export const DBUS_VPN_SIGNAL_LAUNCH_FAILED: string; export const DBUS_VPN_SIGNAL_LOGIN_BANNER: string; export const DBUS_VPN_SIGNAL_LOGIN_FAILED: string; export const DBUS_VPN_SIGNAL_STATE_CHANGE: string; export const DBUS_VPN_SIGNAL_VPN_CONFIG_BAD: string; export const DBUS_VPN_STARTING_IN_PROGRESS: string; export const DBUS_VPN_STOPPING_IN_PROGRESS: string; export const DBUS_VPN_WRONG_STATE: string; export const DEVICE_6LOWPAN_HW_ADDRESS: string; export const DEVICE_6LOWPAN_PARENT: string; export const DEVICE_ACTIVE_CONNECTION: string; export const DEVICE_ADSL_CARRIER: string; export const DEVICE_AUTOCONNECT: string; export const DEVICE_AVAILABLE_CONNECTIONS: string; export const DEVICE_BOND_CARRIER: string; export const DEVICE_BOND_HW_ADDRESS: string; export const DEVICE_BOND_SLAVES: string; export const DEVICE_BRIDGE_CARRIER: string; export const DEVICE_BRIDGE_HW_ADDRESS: string; export const DEVICE_BRIDGE_SLAVES: string; export const DEVICE_BT_CAPABILITIES: string; export const DEVICE_BT_HW_ADDRESS: string; export const DEVICE_BT_NAME: string; export const DEVICE_CAPABILITIES: string; export const DEVICE_DEVICE_TYPE: string; export const DEVICE_DHCP4_CONFIG: string; export const DEVICE_DHCP6_CONFIG: string; export const DEVICE_DRIVER: string; export const DEVICE_DRIVER_VERSION: string; export const DEVICE_DUMMY_HW_ADDRESS: string; export const DEVICE_ETHERNET_CARRIER: string; export const DEVICE_ETHERNET_HW_ADDRESS: string; export const DEVICE_ETHERNET_PERMANENT_HW_ADDRESS: string; export const DEVICE_ETHERNET_S390_SUBCHANNELS: string; export const DEVICE_ETHERNET_SPEED: string; export const DEVICE_FIRMWARE_MISSING: string; export const DEVICE_FIRMWARE_VERSION: string; export const DEVICE_GENERIC_HW_ADDRESS: string; export const DEVICE_GENERIC_TYPE_DESCRIPTION: string; export const DEVICE_HW_ADDRESS: string; export const DEVICE_INFINIBAND_CARRIER: string; export const DEVICE_INFINIBAND_HW_ADDRESS: string; export const DEVICE_INTERFACE: string; export const DEVICE_INTERFACE_FLAGS: string; export const DEVICE_IP4_CONFIG: string; export const DEVICE_IP4_CONNECTIVITY: string; export const DEVICE_IP6_CONFIG: string; export const DEVICE_IP6_CONNECTIVITY: string; export const DEVICE_IP_INTERFACE: string; export const DEVICE_IP_TUNNEL_ENCAPSULATION_LIMIT: string; export const DEVICE_IP_TUNNEL_FLAGS: string; export const DEVICE_IP_TUNNEL_FLOW_LABEL: string; export const DEVICE_IP_TUNNEL_INPUT_KEY: string; export const DEVICE_IP_TUNNEL_LOCAL: string; export const DEVICE_IP_TUNNEL_MODE: string; export const DEVICE_IP_TUNNEL_OUTPUT_KEY: string; export const DEVICE_IP_TUNNEL_PARENT: string; export const DEVICE_IP_TUNNEL_PATH_MTU_DISCOVERY: string; export const DEVICE_IP_TUNNEL_REMOTE: string; export const DEVICE_IP_TUNNEL_TOS: string; export const DEVICE_IP_TUNNEL_TTL: string; export const DEVICE_LLDP_NEIGHBORS: string; export const DEVICE_MACSEC_CIPHER_SUITE: string; export const DEVICE_MACSEC_ENCODING_SA: string; export const DEVICE_MACSEC_ENCRYPT: string; export const DEVICE_MACSEC_ES: string; export const DEVICE_MACSEC_HW_ADDRESS: string; export const DEVICE_MACSEC_ICV_LENGTH: string; export const DEVICE_MACSEC_INCLUDE_SCI: string; export const DEVICE_MACSEC_PARENT: string; export const DEVICE_MACSEC_PROTECT: string; export const DEVICE_MACSEC_REPLAY_PROTECT: string; export const DEVICE_MACSEC_SCB: string; export const DEVICE_MACSEC_SCI: string; export const DEVICE_MACSEC_VALIDATION: string; export const DEVICE_MACSEC_WINDOW: string; export const DEVICE_MACVLAN_HW_ADDRESS: string; export const DEVICE_MACVLAN_MODE: string; export const DEVICE_MACVLAN_NO_PROMISC: string; export const DEVICE_MACVLAN_PARENT: string; export const DEVICE_MACVLAN_TAP: string; export const DEVICE_MANAGED: string; export const DEVICE_METERED: string; export const DEVICE_MODEM_APN: string; export const DEVICE_MODEM_CURRENT_CAPABILITIES: string; export const DEVICE_MODEM_DEVICE_ID: string; export const DEVICE_MODEM_MODEM_CAPABILITIES: string; export const DEVICE_MODEM_OPERATOR_CODE: string; export const DEVICE_MTU: string; export const DEVICE_NM_PLUGIN_MISSING: string; export const DEVICE_OLPC_MESH_ACTIVE_CHANNEL: string; export const DEVICE_OLPC_MESH_COMPANION: string; export const DEVICE_OLPC_MESH_HW_ADDRESS: string; export const DEVICE_OVS_BRIDGE_SLAVES: string; export const DEVICE_OVS_PORT_SLAVES: string; export const DEVICE_PATH: string; export const DEVICE_PHYSICAL_PORT_ID: string; export const DEVICE_PRODUCT: string; export const DEVICE_REAL: string; export const DEVICE_STATE: string; export const DEVICE_STATE_REASON: string; export const DEVICE_TEAM_CARRIER: string; export const DEVICE_TEAM_CONFIG: string; export const DEVICE_TEAM_HW_ADDRESS: string; export const DEVICE_TEAM_SLAVES: string; export const DEVICE_TUN_GROUP: string; export const DEVICE_TUN_HW_ADDRESS: string; export const DEVICE_TUN_MODE: string; export const DEVICE_TUN_MULTI_QUEUE: string; export const DEVICE_TUN_NO_PI: string; export const DEVICE_TUN_OWNER: string; export const DEVICE_TUN_VNET_HDR: string; export const DEVICE_UDI: string; export const DEVICE_VENDOR: string; export const DEVICE_VLAN_CARRIER: string; export const DEVICE_VLAN_HW_ADDRESS: string; export const DEVICE_VLAN_PARENT: string; export const DEVICE_VLAN_VLAN_ID: string; export const DEVICE_VRF_TABLE: string; export const DEVICE_VXLAN_AGEING: string; export const DEVICE_VXLAN_CARRIER: string; export const DEVICE_VXLAN_DST_PORT: string; export const DEVICE_VXLAN_GROUP: string; export const DEVICE_VXLAN_HW_ADDRESS: string; export const DEVICE_VXLAN_ID: string; export const DEVICE_VXLAN_L2MISS: string; export const DEVICE_VXLAN_L3MISS: string; export const DEVICE_VXLAN_LEARNING: string; export const DEVICE_VXLAN_LIMIT: string; export const DEVICE_VXLAN_LOCAL: string; export const DEVICE_VXLAN_PARENT: string; export const DEVICE_VXLAN_PROXY: string; export const DEVICE_VXLAN_RSC: string; export const DEVICE_VXLAN_SRC_PORT_MAX: string; export const DEVICE_VXLAN_SRC_PORT_MIN: string; export const DEVICE_VXLAN_TOS: string; export const DEVICE_VXLAN_TTL: string; export const DEVICE_WIFI_ACCESS_POINTS: string; export const DEVICE_WIFI_ACTIVE_ACCESS_POINT: string; export const DEVICE_WIFI_BITRATE: string; export const DEVICE_WIFI_CAPABILITIES: string; export const DEVICE_WIFI_HW_ADDRESS: string; export const DEVICE_WIFI_LAST_SCAN: string; export const DEVICE_WIFI_MODE: string; export const DEVICE_WIFI_P2P_HW_ADDRESS: string; export const DEVICE_WIFI_P2P_PEERS: string; export const DEVICE_WIFI_P2P_WFDIES: string; export const DEVICE_WIFI_PERMANENT_HW_ADDRESS: string; export const DEVICE_WIMAX_ACTIVE_NSP: string; export const DEVICE_WIMAX_BSID: string; export const DEVICE_WIMAX_CENTER_FREQUENCY: string; export const DEVICE_WIMAX_CINR: string; export const DEVICE_WIMAX_HW_ADDRESS: string; export const DEVICE_WIMAX_NSPS: string; export const DEVICE_WIMAX_RSSI: string; export const DEVICE_WIMAX_TX_POWER: string; export const DEVICE_WIREGUARD_FWMARK: string; export const DEVICE_WIREGUARD_LISTEN_PORT: string; export const DEVICE_WIREGUARD_PUBLIC_KEY: string; export const DEVICE_WPAN_HW_ADDRESS: string; export const DHCP_CONFIG_FAMILY: string; export const DHCP_CONFIG_OPTIONS: string; export const ETHTOOL_OPTNAME_COALESCE_ADAPTIVE_RX: string; export const ETHTOOL_OPTNAME_COALESCE_ADAPTIVE_TX: string; export const ETHTOOL_OPTNAME_COALESCE_PKT_RATE_HIGH: string; export const ETHTOOL_OPTNAME_COALESCE_PKT_RATE_LOW: string; export const ETHTOOL_OPTNAME_COALESCE_RX_FRAMES: string; export const ETHTOOL_OPTNAME_COALESCE_RX_FRAMES_HIGH: string; export const ETHTOOL_OPTNAME_COALESCE_RX_FRAMES_IRQ: string; export const ETHTOOL_OPTNAME_COALESCE_RX_FRAMES_LOW: string; export const ETHTOOL_OPTNAME_COALESCE_RX_USECS: string; export const ETHTOOL_OPTNAME_COALESCE_RX_USECS_HIGH: string; export const ETHTOOL_OPTNAME_COALESCE_RX_USECS_IRQ: string; export const ETHTOOL_OPTNAME_COALESCE_RX_USECS_LOW: string; export const ETHTOOL_OPTNAME_COALESCE_SAMPLE_INTERVAL: string; export const ETHTOOL_OPTNAME_COALESCE_STATS_BLOCK_USECS: string; export const ETHTOOL_OPTNAME_COALESCE_TX_FRAMES: string; export const ETHTOOL_OPTNAME_COALESCE_TX_FRAMES_HIGH: string; export const ETHTOOL_OPTNAME_COALESCE_TX_FRAMES_IRQ: string; export const ETHTOOL_OPTNAME_COALESCE_TX_FRAMES_LOW: string; export const ETHTOOL_OPTNAME_COALESCE_TX_USECS: string; export const ETHTOOL_OPTNAME_COALESCE_TX_USECS_HIGH: string; export const ETHTOOL_OPTNAME_COALESCE_TX_USECS_IRQ: string; export const ETHTOOL_OPTNAME_COALESCE_TX_USECS_LOW: string; export const ETHTOOL_OPTNAME_FEATURE_ESP_HW_OFFLOAD: string; export const ETHTOOL_OPTNAME_FEATURE_ESP_TX_CSUM_HW_OFFLOAD: string; export const ETHTOOL_OPTNAME_FEATURE_FCOE_MTU: string; export const ETHTOOL_OPTNAME_FEATURE_GRO: string; export const ETHTOOL_OPTNAME_FEATURE_GSO: string; export const ETHTOOL_OPTNAME_FEATURE_HIGHDMA: string; export const ETHTOOL_OPTNAME_FEATURE_HW_TC_OFFLOAD: string; export const ETHTOOL_OPTNAME_FEATURE_L2_FWD_OFFLOAD: string; export const ETHTOOL_OPTNAME_FEATURE_LOOPBACK: string; export const ETHTOOL_OPTNAME_FEATURE_LRO: string; export const ETHTOOL_OPTNAME_FEATURE_NTUPLE: string; export const ETHTOOL_OPTNAME_FEATURE_RX: string; export const ETHTOOL_OPTNAME_FEATURE_RXHASH: string; export const ETHTOOL_OPTNAME_FEATURE_RXVLAN: string; export const ETHTOOL_OPTNAME_FEATURE_RX_ALL: string; export const ETHTOOL_OPTNAME_FEATURE_RX_FCS: string; export const ETHTOOL_OPTNAME_FEATURE_RX_GRO_HW: string; export const ETHTOOL_OPTNAME_FEATURE_RX_UDP_TUNNEL_PORT_OFFLOAD: string; export const ETHTOOL_OPTNAME_FEATURE_RX_VLAN_FILTER: string; export const ETHTOOL_OPTNAME_FEATURE_RX_VLAN_STAG_FILTER: string; export const ETHTOOL_OPTNAME_FEATURE_RX_VLAN_STAG_HW_PARSE: string; export const ETHTOOL_OPTNAME_FEATURE_SG: string; export const ETHTOOL_OPTNAME_FEATURE_TLS_HW_RECORD: string; export const ETHTOOL_OPTNAME_FEATURE_TLS_HW_TX_OFFLOAD: string; export const ETHTOOL_OPTNAME_FEATURE_TSO: string; export const ETHTOOL_OPTNAME_FEATURE_TX: string; export const ETHTOOL_OPTNAME_FEATURE_TXVLAN: string; export const ETHTOOL_OPTNAME_FEATURE_TX_CHECKSUM_FCOE_CRC: string; export const ETHTOOL_OPTNAME_FEATURE_TX_CHECKSUM_IPV4: string; export const ETHTOOL_OPTNAME_FEATURE_TX_CHECKSUM_IPV6: string; export const ETHTOOL_OPTNAME_FEATURE_TX_CHECKSUM_IP_GENERIC: string; export const ETHTOOL_OPTNAME_FEATURE_TX_CHECKSUM_SCTP: string; export const ETHTOOL_OPTNAME_FEATURE_TX_ESP_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_FCOE_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_GRE_CSUM_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_GRE_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_GSO_PARTIAL: string; export const ETHTOOL_OPTNAME_FEATURE_TX_GSO_ROBUST: string; export const ETHTOOL_OPTNAME_FEATURE_TX_IPXIP4_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_IPXIP6_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_NOCACHE_COPY: string; export const ETHTOOL_OPTNAME_FEATURE_TX_SCATTER_GATHER: string; export const ETHTOOL_OPTNAME_FEATURE_TX_SCATTER_GATHER_FRAGLIST: string; export const ETHTOOL_OPTNAME_FEATURE_TX_SCTP_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_TCP6_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_TCP_ECN_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_TCP_MANGLEID_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_TCP_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_UDP_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_UDP_TNL_CSUM_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_UDP_TNL_SEGMENTATION: string; export const ETHTOOL_OPTNAME_FEATURE_TX_VLAN_STAG_HW_INSERT: string; export const ETHTOOL_OPTNAME_RING_RX: string; export const ETHTOOL_OPTNAME_RING_RX_JUMBO: string; export const ETHTOOL_OPTNAME_RING_RX_MINI: string; export const ETHTOOL_OPTNAME_RING_TX: string; export const IP_ADDRESS_ATTRIBUTE_LABEL: string; export const IP_CONFIG_ADDRESSES: string; export const IP_CONFIG_DOMAINS: string; export const IP_CONFIG_FAMILY: string; export const IP_CONFIG_GATEWAY: string; export const IP_CONFIG_NAMESERVERS: string; export const IP_CONFIG_ROUTES: string; export const IP_CONFIG_SEARCHES: string; export const IP_CONFIG_WINS_SERVERS: string; export const IP_ROUTE_ATTRIBUTE_CWND: string; export const IP_ROUTE_ATTRIBUTE_FROM: string; export const IP_ROUTE_ATTRIBUTE_INITCWND: string; export const IP_ROUTE_ATTRIBUTE_INITRWND: string; export const IP_ROUTE_ATTRIBUTE_LOCK_CWND: string; export const IP_ROUTE_ATTRIBUTE_LOCK_INITCWND: string; export const IP_ROUTE_ATTRIBUTE_LOCK_INITRWND: string; export const IP_ROUTE_ATTRIBUTE_LOCK_MTU: string; export const IP_ROUTE_ATTRIBUTE_LOCK_WINDOW: string; export const IP_ROUTE_ATTRIBUTE_MTU: string; export const IP_ROUTE_ATTRIBUTE_ONLINK: string; export const IP_ROUTE_ATTRIBUTE_SCOPE: string; export const IP_ROUTE_ATTRIBUTE_SRC: string; export const IP_ROUTE_ATTRIBUTE_TABLE: string; export const IP_ROUTE_ATTRIBUTE_TOS: string; export const IP_ROUTE_ATTRIBUTE_TYPE: string; export const IP_ROUTE_ATTRIBUTE_WINDOW: string; export const LLDP_ATTR_CHASSIS_ID: string; export const LLDP_ATTR_CHASSIS_ID_TYPE: string; export const LLDP_ATTR_DESTINATION: string; export const LLDP_ATTR_IEEE_802_1_PPVID: string; export const LLDP_ATTR_IEEE_802_1_PPVIDS: string; export const LLDP_ATTR_IEEE_802_1_PPVID_FLAGS: string; export const LLDP_ATTR_IEEE_802_1_PVID: string; export const LLDP_ATTR_IEEE_802_1_VID: string; export const LLDP_ATTR_IEEE_802_1_VLANS: string; export const LLDP_ATTR_IEEE_802_1_VLAN_NAME: string; export const LLDP_ATTR_IEEE_802_3_MAC_PHY_CONF: string; export const LLDP_ATTR_IEEE_802_3_MAX_FRAME_SIZE: string; export const LLDP_ATTR_IEEE_802_3_POWER_VIA_MDI: string; export const LLDP_ATTR_MANAGEMENT_ADDRESSES: string; export const LLDP_ATTR_MUD_URL: string; export const LLDP_ATTR_PORT_DESCRIPTION: string; export const LLDP_ATTR_PORT_ID: string; export const LLDP_ATTR_PORT_ID_TYPE: string; export const LLDP_ATTR_RAW: string; export const LLDP_ATTR_SYSTEM_CAPABILITIES: string; export const LLDP_ATTR_SYSTEM_DESCRIPTION: string; export const LLDP_ATTR_SYSTEM_NAME: string; export const LLDP_DEST_NEAREST_BRIDGE: string; export const LLDP_DEST_NEAREST_CUSTOMER_BRIDGE: string; export const LLDP_DEST_NEAREST_NON_TPMR_BRIDGE: string; export const MAJOR_VERSION: number; export const MICRO_VERSION: number; export const MINOR_VERSION: number; export const OBJECT_PATH: string; export const REMOTE_CONNECTION_DBUS_CONNECTION: string; export const REMOTE_CONNECTION_FILENAME: string; export const REMOTE_CONNECTION_FLAGS: string; export const REMOTE_CONNECTION_PATH: string; export const REMOTE_CONNECTION_UNSAVED: string; export const REMOTE_CONNECTION_VISIBLE: string; export const SECRET_AGENT_OLD_AUTO_REGISTER: string; export const SECRET_AGENT_OLD_CAPABILITIES: string; export const SECRET_AGENT_OLD_DBUS_CONNECTION: string; export const SECRET_AGENT_OLD_IDENTIFIER: string; export const SECRET_AGENT_OLD_REGISTERED: string; export const SETTING_6LOWPAN_PARENT: string; export const SETTING_6LOWPAN_SETTING_NAME: string; export const SETTING_802_1X_ALTSUBJECT_MATCHES: string; export const SETTING_802_1X_ANONYMOUS_IDENTITY: string; export const SETTING_802_1X_AUTH_TIMEOUT: string; export const SETTING_802_1X_CA_CERT: string; export const SETTING_802_1X_CA_CERT_PASSWORD: string; export const SETTING_802_1X_CA_CERT_PASSWORD_FLAGS: string; export const SETTING_802_1X_CA_PATH: string; export const SETTING_802_1X_CERT_SCHEME_PREFIX_PATH: string; export const SETTING_802_1X_CERT_SCHEME_PREFIX_PKCS11: string; export const SETTING_802_1X_CLIENT_CERT: string; export const SETTING_802_1X_CLIENT_CERT_PASSWORD: string; export const SETTING_802_1X_CLIENT_CERT_PASSWORD_FLAGS: string; export const SETTING_802_1X_DOMAIN_MATCH: string; export const SETTING_802_1X_DOMAIN_SUFFIX_MATCH: string; export const SETTING_802_1X_EAP: string; export const SETTING_802_1X_IDENTITY: string; export const SETTING_802_1X_OPTIONAL: string; export const SETTING_802_1X_PAC_FILE: string; export const SETTING_802_1X_PASSWORD: string; export const SETTING_802_1X_PASSWORD_FLAGS: string; export const SETTING_802_1X_PASSWORD_RAW: string; export const SETTING_802_1X_PASSWORD_RAW_FLAGS: string; export const SETTING_802_1X_PHASE1_AUTH_FLAGS: string; export const SETTING_802_1X_PHASE1_FAST_PROVISIONING: string; export const SETTING_802_1X_PHASE1_PEAPLABEL: string; export const SETTING_802_1X_PHASE1_PEAPVER: string; export const SETTING_802_1X_PHASE2_ALTSUBJECT_MATCHES: string; export const SETTING_802_1X_PHASE2_AUTH: string; export const SETTING_802_1X_PHASE2_AUTHEAP: string; export const SETTING_802_1X_PHASE2_CA_CERT: string; export const SETTING_802_1X_PHASE2_CA_CERT_PASSWORD: string; export const SETTING_802_1X_PHASE2_CA_CERT_PASSWORD_FLAGS: string; export const SETTING_802_1X_PHASE2_CA_PATH: string; export const SETTING_802_1X_PHASE2_CLIENT_CERT: string; export const SETTING_802_1X_PHASE2_CLIENT_CERT_PASSWORD: string; export const SETTING_802_1X_PHASE2_CLIENT_CERT_PASSWORD_FLAGS: string; export const SETTING_802_1X_PHASE2_DOMAIN_MATCH: string; export const SETTING_802_1X_PHASE2_DOMAIN_SUFFIX_MATCH: string; export const SETTING_802_1X_PHASE2_PRIVATE_KEY: string; export const SETTING_802_1X_PHASE2_PRIVATE_KEY_PASSWORD: string; export const SETTING_802_1X_PHASE2_PRIVATE_KEY_PASSWORD_FLAGS: string; export const SETTING_802_1X_PHASE2_SUBJECT_MATCH: string; export const SETTING_802_1X_PIN: string; export const SETTING_802_1X_PIN_FLAGS: string; export const SETTING_802_1X_PRIVATE_KEY: string; export const SETTING_802_1X_PRIVATE_KEY_PASSWORD: string; export const SETTING_802_1X_PRIVATE_KEY_PASSWORD_FLAGS: string; export const SETTING_802_1X_SETTING_NAME: string; export const SETTING_802_1X_SUBJECT_MATCH: string; export const SETTING_802_1X_SYSTEM_CA_CERTS: string; export const SETTING_ADSL_ENCAPSULATION: string; export const SETTING_ADSL_ENCAPSULATION_LLC: string; export const SETTING_ADSL_ENCAPSULATION_VCMUX: string; export const SETTING_ADSL_PASSWORD: string; export const SETTING_ADSL_PASSWORD_FLAGS: string; export const SETTING_ADSL_PROTOCOL: string; export const SETTING_ADSL_PROTOCOL_IPOATM: string; export const SETTING_ADSL_PROTOCOL_PPPOA: string; export const SETTING_ADSL_PROTOCOL_PPPOE: string; export const SETTING_ADSL_SETTING_NAME: string; export const SETTING_ADSL_USERNAME: string; export const SETTING_ADSL_VCI: string; export const SETTING_ADSL_VPI: string; export const SETTING_BLUETOOTH_BDADDR: string; export const SETTING_BLUETOOTH_SETTING_NAME: string; export const SETTING_BLUETOOTH_TYPE: string; export const SETTING_BLUETOOTH_TYPE_DUN: string; export const SETTING_BLUETOOTH_TYPE_NAP: string; export const SETTING_BLUETOOTH_TYPE_PANU: string; export const SETTING_BOND_OPTIONS: string; export const SETTING_BOND_OPTION_ACTIVE_SLAVE: string; export const SETTING_BOND_OPTION_AD_ACTOR_SYSTEM: string; export const SETTING_BOND_OPTION_AD_ACTOR_SYS_PRIO: string; export const SETTING_BOND_OPTION_AD_SELECT: string; export const SETTING_BOND_OPTION_AD_USER_PORT_KEY: string; export const SETTING_BOND_OPTION_ALL_SLAVES_ACTIVE: string; export const SETTING_BOND_OPTION_ARP_ALL_TARGETS: string; export const SETTING_BOND_OPTION_ARP_INTERVAL: string; export const SETTING_BOND_OPTION_ARP_IP_TARGET: string; export const SETTING_BOND_OPTION_ARP_VALIDATE: string; export const SETTING_BOND_OPTION_DOWNDELAY: string; export const SETTING_BOND_OPTION_FAIL_OVER_MAC: string; export const SETTING_BOND_OPTION_LACP_RATE: string; export const SETTING_BOND_OPTION_LP_INTERVAL: string; export const SETTING_BOND_OPTION_MIIMON: string; export const SETTING_BOND_OPTION_MIN_LINKS: string; export const SETTING_BOND_OPTION_MODE: string; export const SETTING_BOND_OPTION_NUM_GRAT_ARP: string; export const SETTING_BOND_OPTION_NUM_UNSOL_NA: string; export const SETTING_BOND_OPTION_PACKETS_PER_SLAVE: string; export const SETTING_BOND_OPTION_PRIMARY: string; export const SETTING_BOND_OPTION_PRIMARY_RESELECT: string; export const SETTING_BOND_OPTION_RESEND_IGMP: string; export const SETTING_BOND_OPTION_TLB_DYNAMIC_LB: string; export const SETTING_BOND_OPTION_UPDELAY: string; export const SETTING_BOND_OPTION_USE_CARRIER: string; export const SETTING_BOND_OPTION_XMIT_HASH_POLICY: string; export const SETTING_BOND_SETTING_NAME: string; export const SETTING_BRIDGE_AGEING_TIME: string; export const SETTING_BRIDGE_FORWARD_DELAY: string; export const SETTING_BRIDGE_GROUP_ADDRESS: string; export const SETTING_BRIDGE_GROUP_FORWARD_MASK: string; export const SETTING_BRIDGE_HELLO_TIME: string; export const SETTING_BRIDGE_MAC_ADDRESS: string; export const SETTING_BRIDGE_MAX_AGE: string; export const SETTING_BRIDGE_MULTICAST_HASH_MAX: string; export const SETTING_BRIDGE_MULTICAST_LAST_MEMBER_COUNT: string; export const SETTING_BRIDGE_MULTICAST_LAST_MEMBER_INTERVAL: string; export const SETTING_BRIDGE_MULTICAST_MEMBERSHIP_INTERVAL: string; export const SETTING_BRIDGE_MULTICAST_QUERIER: string; export const SETTING_BRIDGE_MULTICAST_QUERIER_INTERVAL: string; export const SETTING_BRIDGE_MULTICAST_QUERY_INTERVAL: string; export const SETTING_BRIDGE_MULTICAST_QUERY_RESPONSE_INTERVAL: string; export const SETTING_BRIDGE_MULTICAST_QUERY_USE_IFADDR: string; export const SETTING_BRIDGE_MULTICAST_ROUTER: string; export const SETTING_BRIDGE_MULTICAST_SNOOPING: string; export const SETTING_BRIDGE_MULTICAST_STARTUP_QUERY_COUNT: string; export const SETTING_BRIDGE_MULTICAST_STARTUP_QUERY_INTERVAL: string; export const SETTING_BRIDGE_PORT_HAIRPIN_MODE: string; export const SETTING_BRIDGE_PORT_PATH_COST: string; export const SETTING_BRIDGE_PORT_PRIORITY: string; export const SETTING_BRIDGE_PORT_SETTING_NAME: string; export const SETTING_BRIDGE_PORT_VLANS: string; export const SETTING_BRIDGE_PRIORITY: string; export const SETTING_BRIDGE_SETTING_NAME: string; export const SETTING_BRIDGE_STP: string; export const SETTING_BRIDGE_VLANS: string; export const SETTING_BRIDGE_VLAN_DEFAULT_PVID: string; export const SETTING_BRIDGE_VLAN_FILTERING: string; export const SETTING_BRIDGE_VLAN_PROTOCOL: string; export const SETTING_BRIDGE_VLAN_STATS_ENABLED: string; export const SETTING_CDMA_MTU: string; export const SETTING_CDMA_NUMBER: string; export const SETTING_CDMA_PASSWORD: string; export const SETTING_CDMA_PASSWORD_FLAGS: string; export const SETTING_CDMA_SETTING_NAME: string; export const SETTING_CDMA_USERNAME: string; export const SETTING_CONNECTION_AUTH_RETRIES: string; export const SETTING_CONNECTION_AUTOCONNECT: string; export const SETTING_CONNECTION_AUTOCONNECT_PRIORITY: string; export const SETTING_CONNECTION_AUTOCONNECT_PRIORITY_DEFAULT: number; export const SETTING_CONNECTION_AUTOCONNECT_PRIORITY_MAX: number; export const SETTING_CONNECTION_AUTOCONNECT_PRIORITY_MIN: number; export const SETTING_CONNECTION_AUTOCONNECT_RETRIES: string; export const SETTING_CONNECTION_AUTOCONNECT_SLAVES: string; export const SETTING_CONNECTION_GATEWAY_PING_TIMEOUT: string; export const SETTING_CONNECTION_ID: string; export const SETTING_CONNECTION_INTERFACE_NAME: string; export const SETTING_CONNECTION_LLDP: string; export const SETTING_CONNECTION_LLMNR: string; export const SETTING_CONNECTION_MASTER: string; export const SETTING_CONNECTION_MDNS: string; export const SETTING_CONNECTION_METERED: string; export const SETTING_CONNECTION_MUD_URL: string; export const SETTING_CONNECTION_MULTI_CONNECT: string; export const SETTING_CONNECTION_PERMISSIONS: string; export const SETTING_CONNECTION_READ_ONLY: string; export const SETTING_CONNECTION_SECONDARIES: string; export const SETTING_CONNECTION_SETTING_NAME: string; export const SETTING_CONNECTION_SLAVE_TYPE: string; export const SETTING_CONNECTION_STABLE_ID: string; export const SETTING_CONNECTION_TIMESTAMP: string; export const SETTING_CONNECTION_TYPE: string; export const SETTING_CONNECTION_UUID: string; export const SETTING_CONNECTION_WAIT_DEVICE_TIMEOUT: string; export const SETTING_CONNECTION_ZONE: string; export const SETTING_DCB_APP_FCOE_FLAGS: string; export const SETTING_DCB_APP_FCOE_MODE: string; export const SETTING_DCB_APP_FCOE_PRIORITY: string; export const SETTING_DCB_APP_FIP_FLAGS: string; export const SETTING_DCB_APP_FIP_PRIORITY: string; export const SETTING_DCB_APP_ISCSI_FLAGS: string; export const SETTING_DCB_APP_ISCSI_PRIORITY: string; export const SETTING_DCB_FCOE_MODE_FABRIC: string; export const SETTING_DCB_FCOE_MODE_VN2VN: string; export const SETTING_DCB_PRIORITY_BANDWIDTH: string; export const SETTING_DCB_PRIORITY_FLOW_CONTROL: string; export const SETTING_DCB_PRIORITY_FLOW_CONTROL_FLAGS: string; export const SETTING_DCB_PRIORITY_GROUP_BANDWIDTH: string; export const SETTING_DCB_PRIORITY_GROUP_FLAGS: string; export const SETTING_DCB_PRIORITY_GROUP_ID: string; export const SETTING_DCB_PRIORITY_STRICT_BANDWIDTH: string; export const SETTING_DCB_PRIORITY_TRAFFIC_CLASS: string; export const SETTING_DCB_SETTING_NAME: string; export const SETTING_DNS_OPTION_ATTEMPTS: string; export const SETTING_DNS_OPTION_DEBUG: string; export const SETTING_DNS_OPTION_EDNS0: string; export const SETTING_DNS_OPTION_INET6: string; export const SETTING_DNS_OPTION_IP6_BYTESTRING: string; export const SETTING_DNS_OPTION_IP6_DOTINT: string; export const SETTING_DNS_OPTION_NDOTS: string; export const SETTING_DNS_OPTION_NO_CHECK_NAMES: string; export const SETTING_DNS_OPTION_NO_IP6_DOTINT: string; export const SETTING_DNS_OPTION_NO_RELOAD: string; export const SETTING_DNS_OPTION_NO_TLD_QUERY: string; export const SETTING_DNS_OPTION_ROTATE: string; export const SETTING_DNS_OPTION_SINGLE_REQUEST: string; export const SETTING_DNS_OPTION_SINGLE_REQUEST_REOPEN: string; export const SETTING_DNS_OPTION_TIMEOUT: string; export const SETTING_DNS_OPTION_TRUST_AD: string; export const SETTING_DNS_OPTION_USE_VC: string; export const SETTING_DUMMY_SETTING_NAME: string; export const SETTING_ETHTOOL_SETTING_NAME: string; export const SETTING_GENERIC_SETTING_NAME: string; export const SETTING_GSM_APN: string; export const SETTING_GSM_AUTO_CONFIG: string; export const SETTING_GSM_DEVICE_ID: string; export const SETTING_GSM_HOME_ONLY: string; export const SETTING_GSM_MTU: string; export const SETTING_GSM_NETWORK_ID: string; export const SETTING_GSM_NUMBER: string; export const SETTING_GSM_PASSWORD: string; export const SETTING_GSM_PASSWORD_FLAGS: string; export const SETTING_GSM_PIN: string; export const SETTING_GSM_PIN_FLAGS: string; export const SETTING_GSM_SETTING_NAME: string; export const SETTING_GSM_SIM_ID: string; export const SETTING_GSM_SIM_OPERATOR_ID: string; export const SETTING_GSM_USERNAME: string; export const SETTING_INFINIBAND_MAC_ADDRESS: string; export const SETTING_INFINIBAND_MTU: string; export const SETTING_INFINIBAND_PARENT: string; export const SETTING_INFINIBAND_P_KEY: string; export const SETTING_INFINIBAND_SETTING_NAME: string; export const SETTING_INFINIBAND_TRANSPORT_MODE: string; export const SETTING_IP4_CONFIG_DHCP_CLIENT_ID: string; export const SETTING_IP4_CONFIG_DHCP_FQDN: string; export const SETTING_IP4_CONFIG_DHCP_VENDOR_CLASS_IDENTIFIER: string; export const SETTING_IP4_CONFIG_METHOD_AUTO: string; export const SETTING_IP4_CONFIG_METHOD_DISABLED: string; export const SETTING_IP4_CONFIG_METHOD_LINK_LOCAL: string; export const SETTING_IP4_CONFIG_METHOD_MANUAL: string; export const SETTING_IP4_CONFIG_METHOD_SHARED: string; export const SETTING_IP4_CONFIG_SETTING_NAME: string; export const SETTING_IP6_CONFIG_ADDR_GEN_MODE: string; export const SETTING_IP6_CONFIG_DHCP_DUID: string; export const SETTING_IP6_CONFIG_IP6_PRIVACY: string; export const SETTING_IP6_CONFIG_METHOD_AUTO: string; export const SETTING_IP6_CONFIG_METHOD_DHCP: string; export const SETTING_IP6_CONFIG_METHOD_DISABLED: string; export const SETTING_IP6_CONFIG_METHOD_IGNORE: string; export const SETTING_IP6_CONFIG_METHOD_LINK_LOCAL: string; export const SETTING_IP6_CONFIG_METHOD_MANUAL: string; export const SETTING_IP6_CONFIG_METHOD_SHARED: string; export const SETTING_IP6_CONFIG_RA_TIMEOUT: string; export const SETTING_IP6_CONFIG_SETTING_NAME: string; export const SETTING_IP6_CONFIG_TOKEN: string; export const SETTING_IP_CONFIG_ADDRESSES: string; export const SETTING_IP_CONFIG_DAD_TIMEOUT: string; export const SETTING_IP_CONFIG_DAD_TIMEOUT_MAX: number; export const SETTING_IP_CONFIG_DHCP_HOSTNAME: string; export const SETTING_IP_CONFIG_DHCP_HOSTNAME_FLAGS: string; export const SETTING_IP_CONFIG_DHCP_IAID: string; export const SETTING_IP_CONFIG_DHCP_REJECT_SERVERS: string; export const SETTING_IP_CONFIG_DHCP_SEND_HOSTNAME: string; export const SETTING_IP_CONFIG_DHCP_TIMEOUT: string; export const SETTING_IP_CONFIG_DNS: string; export const SETTING_IP_CONFIG_DNS_OPTIONS: string; export const SETTING_IP_CONFIG_DNS_PRIORITY: string; export const SETTING_IP_CONFIG_DNS_SEARCH: string; export const SETTING_IP_CONFIG_GATEWAY: string; export const SETTING_IP_CONFIG_IGNORE_AUTO_DNS: string; export const SETTING_IP_CONFIG_IGNORE_AUTO_ROUTES: string; export const SETTING_IP_CONFIG_MAY_FAIL: string; export const SETTING_IP_CONFIG_METHOD: string; export const SETTING_IP_CONFIG_NEVER_DEFAULT: string; export const SETTING_IP_CONFIG_ROUTES: string; export const SETTING_IP_CONFIG_ROUTE_METRIC: string; export const SETTING_IP_CONFIG_ROUTE_TABLE: string; export const SETTING_IP_CONFIG_ROUTING_RULES: string; export const SETTING_IP_TUNNEL_ENCAPSULATION_LIMIT: string; export const SETTING_IP_TUNNEL_FLAGS: string; export const SETTING_IP_TUNNEL_FLOW_LABEL: string; export const SETTING_IP_TUNNEL_INPUT_KEY: string; export const SETTING_IP_TUNNEL_LOCAL: string; export const SETTING_IP_TUNNEL_MODE: string; export const SETTING_IP_TUNNEL_MTU: string; export const SETTING_IP_TUNNEL_OUTPUT_KEY: string; export const SETTING_IP_TUNNEL_PARENT: string; export const SETTING_IP_TUNNEL_PATH_MTU_DISCOVERY: string; export const SETTING_IP_TUNNEL_REMOTE: string; export const SETTING_IP_TUNNEL_SETTING_NAME: string; export const SETTING_IP_TUNNEL_TOS: string; export const SETTING_IP_TUNNEL_TTL: string; export const SETTING_MACSEC_ENCRYPT: string; export const SETTING_MACSEC_MKA_CAK: string; export const SETTING_MACSEC_MKA_CAK_FLAGS: string; export const SETTING_MACSEC_MKA_CAK_LENGTH: number; export const SETTING_MACSEC_MKA_CKN: string; export const SETTING_MACSEC_MKA_CKN_LENGTH: number; export const SETTING_MACSEC_MODE: string; export const SETTING_MACSEC_PARENT: string; export const SETTING_MACSEC_PORT: string; export const SETTING_MACSEC_SEND_SCI: string; export const SETTING_MACSEC_SETTING_NAME: string; export const SETTING_MACSEC_VALIDATION: string; export const SETTING_MACVLAN_MODE: string; export const SETTING_MACVLAN_PARENT: string; export const SETTING_MACVLAN_PROMISCUOUS: string; export const SETTING_MACVLAN_SETTING_NAME: string; export const SETTING_MACVLAN_TAP: string; export const SETTING_MATCH_DRIVER: string; export const SETTING_MATCH_INTERFACE_NAME: string; export const SETTING_MATCH_KERNEL_COMMAND_LINE: string; export const SETTING_MATCH_PATH: string; export const SETTING_MATCH_SETTING_NAME: string; export const SETTING_NAME: string; export const SETTING_OLPC_MESH_CHANNEL: string; export const SETTING_OLPC_MESH_DHCP_ANYCAST_ADDRESS: string; export const SETTING_OLPC_MESH_SETTING_NAME: string; export const SETTING_OLPC_MESH_SSID: string; export const SETTING_OVS_BRIDGE_DATAPATH_TYPE: string; export const SETTING_OVS_BRIDGE_FAIL_MODE: string; export const SETTING_OVS_BRIDGE_MCAST_SNOOPING_ENABLE: string; export const SETTING_OVS_BRIDGE_RSTP_ENABLE: string; export const SETTING_OVS_BRIDGE_SETTING_NAME: string; export const SETTING_OVS_BRIDGE_STP_ENABLE: string; export const SETTING_OVS_DPDK_DEVARGS: string; export const SETTING_OVS_DPDK_SETTING_NAME: string; export const SETTING_OVS_INTERFACE_SETTING_NAME: string; export const SETTING_OVS_INTERFACE_TYPE: string; export const SETTING_OVS_PATCH_PEER: string; export const SETTING_OVS_PATCH_SETTING_NAME: string; export const SETTING_OVS_PORT_BOND_DOWNDELAY: string; export const SETTING_OVS_PORT_BOND_MODE: string; export const SETTING_OVS_PORT_BOND_UPDELAY: string; export const SETTING_OVS_PORT_LACP: string; export const SETTING_OVS_PORT_SETTING_NAME: string; export const SETTING_OVS_PORT_TAG: string; export const SETTING_OVS_PORT_VLAN_MODE: string; export const SETTING_PARAM_FUZZY_IGNORE: number; export const SETTING_PARAM_REQUIRED: number; export const SETTING_PARAM_SECRET: number; export const SETTING_PPPOE_PARENT: string; export const SETTING_PPPOE_PASSWORD: string; export const SETTING_PPPOE_PASSWORD_FLAGS: string; export const SETTING_PPPOE_SERVICE: string; export const SETTING_PPPOE_SETTING_NAME: string; export const SETTING_PPPOE_USERNAME: string; export const SETTING_PPP_BAUD: string; export const SETTING_PPP_CRTSCTS: string; export const SETTING_PPP_LCP_ECHO_FAILURE: string; export const SETTING_PPP_LCP_ECHO_INTERVAL: string; export const SETTING_PPP_MPPE_STATEFUL: string; export const SETTING_PPP_MRU: string; export const SETTING_PPP_MTU: string; export const SETTING_PPP_NOAUTH: string; export const SETTING_PPP_NOBSDCOMP: string; export const SETTING_PPP_NODEFLATE: string; export const SETTING_PPP_NO_VJ_COMP: string; export const SETTING_PPP_REFUSE_CHAP: string; export const SETTING_PPP_REFUSE_EAP: string; export const SETTING_PPP_REFUSE_MSCHAP: string; export const SETTING_PPP_REFUSE_MSCHAPV2: string; export const SETTING_PPP_REFUSE_PAP: string; export const SETTING_PPP_REQUIRE_MPPE: string; export const SETTING_PPP_REQUIRE_MPPE_128: string; export const SETTING_PPP_SETTING_NAME: string; export const SETTING_PROXY_BROWSER_ONLY: string; export const SETTING_PROXY_METHOD: string; export const SETTING_PROXY_PAC_SCRIPT: string; export const SETTING_PROXY_PAC_URL: string; export const SETTING_PROXY_SETTING_NAME: string; export const SETTING_SERIAL_BAUD: string; export const SETTING_SERIAL_BITS: string; export const SETTING_SERIAL_PARITY: string; export const SETTING_SERIAL_SEND_DELAY: string; export const SETTING_SERIAL_SETTING_NAME: string; export const SETTING_SERIAL_STOPBITS: string; export const SETTING_SRIOV_AUTOPROBE_DRIVERS: string; export const SETTING_SRIOV_SETTING_NAME: string; export const SETTING_SRIOV_TOTAL_VFS: string; export const SETTING_SRIOV_VFS: string; export const SETTING_TC_CONFIG_QDISCS: string; export const SETTING_TC_CONFIG_SETTING_NAME: string; export const SETTING_TC_CONFIG_TFILTERS: string; export const SETTING_TEAM_CONFIG: string; export const SETTING_TEAM_LINK_WATCHERS: string; export const SETTING_TEAM_MCAST_REJOIN_COUNT: string; export const SETTING_TEAM_MCAST_REJOIN_INTERVAL: string; export const SETTING_TEAM_NOTIFY_MCAST_COUNT_ACTIVEBACKUP_DEFAULT: number; export const SETTING_TEAM_NOTIFY_PEERS_COUNT: string; export const SETTING_TEAM_NOTIFY_PEERS_COUNT_ACTIVEBACKUP_DEFAULT: number; export const SETTING_TEAM_NOTIFY_PEERS_INTERVAL: string; export const SETTING_TEAM_PORT_CONFIG: string; export const SETTING_TEAM_PORT_LACP_KEY: string; export const SETTING_TEAM_PORT_LACP_PRIO: string; export const SETTING_TEAM_PORT_LACP_PRIO_DEFAULT: number; export const SETTING_TEAM_PORT_LINK_WATCHERS: string; export const SETTING_TEAM_PORT_PRIO: string; export const SETTING_TEAM_PORT_QUEUE_ID: string; export const SETTING_TEAM_PORT_QUEUE_ID_DEFAULT: number; export const SETTING_TEAM_PORT_SETTING_NAME: string; export const SETTING_TEAM_PORT_STICKY: string; export const SETTING_TEAM_RUNNER: string; export const SETTING_TEAM_RUNNER_ACTIVE: string; export const SETTING_TEAM_RUNNER_ACTIVEBACKUP: string; export const SETTING_TEAM_RUNNER_AGG_SELECT_POLICY: string; export const SETTING_TEAM_RUNNER_AGG_SELECT_POLICY_BANDWIDTH: string; export const SETTING_TEAM_RUNNER_AGG_SELECT_POLICY_COUNT: string; export const SETTING_TEAM_RUNNER_AGG_SELECT_POLICY_LACP_PRIO: string; export const SETTING_TEAM_RUNNER_AGG_SELECT_POLICY_LACP_PRIO_STABLE: string; export const SETTING_TEAM_RUNNER_AGG_SELECT_POLICY_PORT_CONFIG: string; export const SETTING_TEAM_RUNNER_BROADCAST: string; export const SETTING_TEAM_RUNNER_FAST_RATE: string; export const SETTING_TEAM_RUNNER_HWADDR_POLICY: string; export const SETTING_TEAM_RUNNER_HWADDR_POLICY_BY_ACTIVE: string; export const SETTING_TEAM_RUNNER_HWADDR_POLICY_ONLY_ACTIVE: string; export const SETTING_TEAM_RUNNER_HWADDR_POLICY_SAME_ALL: string; export const SETTING_TEAM_RUNNER_LACP: string; export const SETTING_TEAM_RUNNER_LOADBALANCE: string; export const SETTING_TEAM_RUNNER_MIN_PORTS: string; export const SETTING_TEAM_RUNNER_RANDOM: string; export const SETTING_TEAM_RUNNER_ROUNDROBIN: string; export const SETTING_TEAM_RUNNER_SYS_PRIO: string; export const SETTING_TEAM_RUNNER_SYS_PRIO_DEFAULT: number; export const SETTING_TEAM_RUNNER_TX_BALANCER: string; export const SETTING_TEAM_RUNNER_TX_BALANCER_INTERVAL: string; export const SETTING_TEAM_RUNNER_TX_BALANCER_INTERVAL_DEFAULT: number; export const SETTING_TEAM_RUNNER_TX_HASH: string; export const SETTING_TEAM_SETTING_NAME: string; export const SETTING_TUN_GROUP: string; export const SETTING_TUN_MODE: string; export const SETTING_TUN_MULTI_QUEUE: string; export const SETTING_TUN_OWNER: string; export const SETTING_TUN_PI: string; export const SETTING_TUN_SETTING_NAME: string; export const SETTING_TUN_VNET_HDR: string; export const SETTING_USER_DATA: string; export const SETTING_USER_SETTING_NAME: string; export const SETTING_VLAN_EGRESS_PRIORITY_MAP: string; export const SETTING_VLAN_FLAGS: string; export const SETTING_VLAN_ID: string; export const SETTING_VLAN_INGRESS_PRIORITY_MAP: string; export const SETTING_VLAN_PARENT: string; export const SETTING_VLAN_SETTING_NAME: string; export const SETTING_VPN_DATA: string; export const SETTING_VPN_PERSISTENT: string; export const SETTING_VPN_SECRETS: string; export const SETTING_VPN_SERVICE_TYPE: string; export const SETTING_VPN_SETTING_NAME: string; export const SETTING_VPN_TIMEOUT: string; export const SETTING_VPN_USER_NAME: string; export const SETTING_VRF_SETTING_NAME: string; export const SETTING_VRF_TABLE: string; export const SETTING_VXLAN_AGEING: string; export const SETTING_VXLAN_DESTINATION_PORT: string; export const SETTING_VXLAN_ID: string; export const SETTING_VXLAN_L2_MISS: string; export const SETTING_VXLAN_L3_MISS: string; export const SETTING_VXLAN_LEARNING: string; export const SETTING_VXLAN_LIMIT: string; export const SETTING_VXLAN_LOCAL: string; export const SETTING_VXLAN_PARENT: string; export const SETTING_VXLAN_PROXY: string; export const SETTING_VXLAN_REMOTE: string; export const SETTING_VXLAN_RSC: string; export const SETTING_VXLAN_SETTING_NAME: string; export const SETTING_VXLAN_SOURCE_PORT_MAX: string; export const SETTING_VXLAN_SOURCE_PORT_MIN: string; export const SETTING_VXLAN_TOS: string; export const SETTING_VXLAN_TTL: string; export const SETTING_WIFI_P2P_PEER: string; export const SETTING_WIFI_P2P_SETTING_NAME: string; export const SETTING_WIFI_P2P_WFD_IES: string; export const SETTING_WIFI_P2P_WPS_METHOD: string; export const SETTING_WIMAX_MAC_ADDRESS: string; export const SETTING_WIMAX_NETWORK_NAME: string; export const SETTING_WIMAX_SETTING_NAME: string; export const SETTING_WIRED_AUTO_NEGOTIATE: string; export const SETTING_WIRED_CLONED_MAC_ADDRESS: string; export const SETTING_WIRED_DUPLEX: string; export const SETTING_WIRED_GENERATE_MAC_ADDRESS_MASK: string; export const SETTING_WIRED_MAC_ADDRESS: string; export const SETTING_WIRED_MAC_ADDRESS_BLACKLIST: string; export const SETTING_WIRED_MTU: string; export const SETTING_WIRED_PORT: string; export const SETTING_WIRED_S390_NETTYPE: string; export const SETTING_WIRED_S390_OPTIONS: string; export const SETTING_WIRED_S390_SUBCHANNELS: string; export const SETTING_WIRED_SETTING_NAME: string; export const SETTING_WIRED_SPEED: string; export const SETTING_WIRED_WAKE_ON_LAN: string; export const SETTING_WIRED_WAKE_ON_LAN_PASSWORD: string; export const SETTING_WIREGUARD_FWMARK: string; export const SETTING_WIREGUARD_IP4_AUTO_DEFAULT_ROUTE: string; export const SETTING_WIREGUARD_IP6_AUTO_DEFAULT_ROUTE: string; export const SETTING_WIREGUARD_LISTEN_PORT: string; export const SETTING_WIREGUARD_MTU: string; export const SETTING_WIREGUARD_PEERS: string; export const SETTING_WIREGUARD_PEER_ROUTES: string; export const SETTING_WIREGUARD_PRIVATE_KEY: string; export const SETTING_WIREGUARD_PRIVATE_KEY_FLAGS: string; export const SETTING_WIREGUARD_SETTING_NAME: string; export const SETTING_WIRELESS_AP_ISOLATION: string; export const SETTING_WIRELESS_BAND: string; export const SETTING_WIRELESS_BSSID: string; export const SETTING_WIRELESS_CHANNEL: string; export const SETTING_WIRELESS_CLONED_MAC_ADDRESS: string; export const SETTING_WIRELESS_GENERATE_MAC_ADDRESS_MASK: string; export const SETTING_WIRELESS_HIDDEN: string; export const SETTING_WIRELESS_MAC_ADDRESS: string; export const SETTING_WIRELESS_MAC_ADDRESS_BLACKLIST: string; export const SETTING_WIRELESS_MAC_ADDRESS_RANDOMIZATION: string; export const SETTING_WIRELESS_MODE: string; export const SETTING_WIRELESS_MODE_ADHOC: string; export const SETTING_WIRELESS_MODE_AP: string; export const SETTING_WIRELESS_MODE_INFRA: string; export const SETTING_WIRELESS_MODE_MESH: string; export const SETTING_WIRELESS_MTU: string; export const SETTING_WIRELESS_POWERSAVE: string; export const SETTING_WIRELESS_RATE: string; export const SETTING_WIRELESS_SECURITY_AUTH_ALG: string; export const SETTING_WIRELESS_SECURITY_FILS: string; export const SETTING_WIRELESS_SECURITY_GROUP: string; export const SETTING_WIRELESS_SECURITY_KEY_MGMT: string; export const SETTING_WIRELESS_SECURITY_LEAP_PASSWORD: string; export const SETTING_WIRELESS_SECURITY_LEAP_PASSWORD_FLAGS: string; export const SETTING_WIRELESS_SECURITY_LEAP_USERNAME: string; export const SETTING_WIRELESS_SECURITY_PAIRWISE: string; export const SETTING_WIRELESS_SECURITY_PMF: string; export const SETTING_WIRELESS_SECURITY_PROTO: string; export const SETTING_WIRELESS_SECURITY_PSK: string; export const SETTING_WIRELESS_SECURITY_PSK_FLAGS: string; export const SETTING_WIRELESS_SECURITY_SETTING_NAME: string; export const SETTING_WIRELESS_SECURITY_WEP_KEY0: string; export const SETTING_WIRELESS_SECURITY_WEP_KEY1: string; export const SETTING_WIRELESS_SECURITY_WEP_KEY2: string; export const SETTING_WIRELESS_SECURITY_WEP_KEY3: string; export const SETTING_WIRELESS_SECURITY_WEP_KEY_FLAGS: string; export const SETTING_WIRELESS_SECURITY_WEP_KEY_TYPE: string; export const SETTING_WIRELESS_SECURITY_WEP_TX_KEYIDX: string; export const SETTING_WIRELESS_SECURITY_WPS_METHOD: string; export const SETTING_WIRELESS_SEEN_BSSIDS: string; export const SETTING_WIRELESS_SETTING_NAME: string; export const SETTING_WIRELESS_SSID: string; export const SETTING_WIRELESS_TX_POWER: string; export const SETTING_WIRELESS_WAKE_ON_WLAN: string; export const SETTING_WPAN_CHANNEL: string; export const SETTING_WPAN_CHANNEL_DEFAULT: number; export const SETTING_WPAN_MAC_ADDRESS: string; export const SETTING_WPAN_PAGE: string; export const SETTING_WPAN_PAGE_DEFAULT: number; export const SETTING_WPAN_PAN_ID: string; export const SETTING_WPAN_SETTING_NAME: string; export const SETTING_WPAN_SHORT_ADDRESS: string; export const SRIOV_VF_ATTRIBUTE_MAC: string; export const SRIOV_VF_ATTRIBUTE_MAX_TX_RATE: string; export const SRIOV_VF_ATTRIBUTE_MIN_TX_RATE: string; export const SRIOV_VF_ATTRIBUTE_SPOOF_CHECK: string; export const SRIOV_VF_ATTRIBUTE_TRUST: string; export const TEAM_LINK_WATCHER_ARP_PING: string; export const TEAM_LINK_WATCHER_ETHTOOL: string; export const TEAM_LINK_WATCHER_NSNA_PING: string; export const UTILS_HWADDR_LEN_MAX: number; export const VLAN_FLAGS_ALL: number; export const VPN_CONNECTION_BANNER: string; export const VPN_CONNECTION_VPN_STATE: string; export const VPN_DBUS_PLUGIN_INTERFACE: string; export const VPN_DBUS_PLUGIN_PATH: string; export const VPN_EDITOR_PLUGIN_DESCRIPTION: string; export const VPN_EDITOR_PLUGIN_NAME: string; export const VPN_EDITOR_PLUGIN_SERVICE: string; export const VPN_PLUGIN_CAN_PERSIST: string; export const VPN_PLUGIN_CONFIG_BANNER: string; export const VPN_PLUGIN_CONFIG_EXT_GATEWAY: string; export const VPN_PLUGIN_CONFIG_HAS_IP4: string; export const VPN_PLUGIN_CONFIG_HAS_IP6: string; export const VPN_PLUGIN_CONFIG_MTU: string; export const VPN_PLUGIN_CONFIG_PROXY_PAC: string; export const VPN_PLUGIN_CONFIG_TUNDEV: string; export const VPN_PLUGIN_INFO_FILENAME: string; export const VPN_PLUGIN_INFO_KEYFILE: string; export const VPN_PLUGIN_INFO_KF_GROUP_CONNECTION: string; export const VPN_PLUGIN_INFO_KF_GROUP_GNOME: string; export const VPN_PLUGIN_INFO_KF_GROUP_LIBNM: string; export const VPN_PLUGIN_INFO_NAME: string; export const VPN_PLUGIN_IP4_CONFIG_ADDRESS: string; export const VPN_PLUGIN_IP4_CONFIG_DNS: string; export const VPN_PLUGIN_IP4_CONFIG_DOMAIN: string; export const VPN_PLUGIN_IP4_CONFIG_DOMAINS: string; export const VPN_PLUGIN_IP4_CONFIG_INT_GATEWAY: string; export const VPN_PLUGIN_IP4_CONFIG_MSS: string; export const VPN_PLUGIN_IP4_CONFIG_NBNS: string; export const VPN_PLUGIN_IP4_CONFIG_NEVER_DEFAULT: string; export const VPN_PLUGIN_IP4_CONFIG_PREFIX: string; export const VPN_PLUGIN_IP4_CONFIG_PRESERVE_ROUTES: string; export const VPN_PLUGIN_IP4_CONFIG_PTP: string; export const VPN_PLUGIN_IP4_CONFIG_ROUTES: string; export const VPN_PLUGIN_IP6_CONFIG_ADDRESS: string; export const VPN_PLUGIN_IP6_CONFIG_DNS: string; export const VPN_PLUGIN_IP6_CONFIG_DOMAIN: string; export const VPN_PLUGIN_IP6_CONFIG_DOMAINS: string; export const VPN_PLUGIN_IP6_CONFIG_INT_GATEWAY: string; export const VPN_PLUGIN_IP6_CONFIG_MSS: string; export const VPN_PLUGIN_IP6_CONFIG_NEVER_DEFAULT: string; export const VPN_PLUGIN_IP6_CONFIG_PREFIX: string; export const VPN_PLUGIN_IP6_CONFIG_PRESERVE_ROUTES: string; export const VPN_PLUGIN_IP6_CONFIG_PTP: string; export const VPN_PLUGIN_IP6_CONFIG_ROUTES: string; export const VPN_PLUGIN_OLD_DBUS_SERVICE_NAME: string; export const VPN_PLUGIN_OLD_STATE: string; export const VPN_SERVICE_PLUGIN_DBUS_SERVICE_NAME: string; export const VPN_SERVICE_PLUGIN_DBUS_WATCH_PEER: string; export const VPN_SERVICE_PLUGIN_STATE: string; export const WIFI_P2P_PEER_FLAGS: string; export const WIFI_P2P_PEER_HW_ADDRESS: string; export const WIFI_P2P_PEER_LAST_SEEN: string; export const WIFI_P2P_PEER_MANUFACTURER: string; export const WIFI_P2P_PEER_MODEL: string; export const WIFI_P2P_PEER_MODEL_NUMBER: string; export const WIFI_P2P_PEER_NAME: string; export const WIFI_P2P_PEER_SERIAL: string; export const WIFI_P2P_PEER_STRENGTH: string; export const WIFI_P2P_PEER_WFD_IES: string; export const WIMAX_NSP_NAME: string; export const WIMAX_NSP_NETWORK_TYPE: string; export const WIMAX_NSP_SIGNAL_QUALITY: string; export const WIREGUARD_PEER_ATTR_ALLOWED_IPS: string; export const WIREGUARD_PEER_ATTR_ENDPOINT: string; export const WIREGUARD_PEER_ATTR_PERSISTENT_KEEPALIVE: string; export const WIREGUARD_PEER_ATTR_PRESHARED_KEY: string; export const WIREGUARD_PEER_ATTR_PRESHARED_KEY_FLAGS: string; export const WIREGUARD_PEER_ATTR_PUBLIC_KEY: string; export const WIREGUARD_PUBLIC_KEY_LEN: number; export const WIREGUARD_SYMMETRIC_KEY_LEN: number; export function agent_manager_error_quark(): GLib.Quark; export function bridge_vlan_from_str(str: string): BridgeVlan; export function client_error_quark(): GLib.Quark; export function connection_error_quark(): GLib.Quark; export function crypto_error_quark(): GLib.Quark; export function device_error_quark(): GLib.Quark; export function ethtool_optname_is_coalesce(optname?: string | null): boolean; export function ethtool_optname_is_feature(optname?: string | null): boolean; export function ethtool_optname_is_ring(optname?: string | null): boolean; export function ip_route_attribute_validate(name: string, value: GLib.Variant, family: number): [boolean, boolean]; export function ip_route_get_variant_attribute_spec(): VariantAttributeSpec; export function ip_routing_rule_from_string( str: string, to_string_flags: IPRoutingRuleAsStringFlags, extra_args?: GLib.HashTable<any, any> | null ): IPRoutingRule; export function manager_error_quark(): GLib.Quark; export function secret_agent_error_quark(): GLib.Quark; export function settings_error_quark(): GLib.Quark; export function sriov_vf_attribute_validate(name: string, value: GLib.Variant): [boolean, boolean]; export function utils_ap_mode_security_valid(type: UtilsSecurityType, wifi_caps: DeviceWifiCapabilities): boolean; export function utils_base64secret_decode( base64_key: string, required_key_len: number, out_key?: number | null ): boolean; export function utils_bin2hexstr(src: Uint8Array | string, final_len: number): string; export function utils_bond_mode_int_to_string(mode: number): string; export function utils_bond_mode_string_to_int(mode: string): number; export function utils_check_virtual_device_compatibility( virtual_type: GObject.GType, other_type: GObject.GType ): boolean; export function utils_enum_from_str(type: GObject.GType, str: string): [boolean, number | null, string | null]; export function utils_enum_get_values(type: GObject.GType, from: number, to: number): string[]; export function utils_enum_to_str(type: GObject.GType, value: number): string; export function utils_escape_ssid(ssid: Uint8Array | string): string; export function utils_file_is_certificate(filename: string): boolean; export function utils_file_is_pkcs12(filename: string): boolean; export function utils_file_is_private_key(filename: string): [boolean, boolean]; export function utils_file_search_in_paths( progname: string, try_first: string | null, paths: string | null, file_test_flags: GLib.FileTest, predicate: UtilsFileSearchInPathsPredicate ): string; export function utils_format_variant_attributes( attributes: GLib.HashTable<any, any>, attr_separator: number, key_value_separator: number ): string; export function utils_get_timestamp_msec(): number; export function utils_hexstr2bin(hex: string): GLib.Bytes; export function utils_hwaddr_atoba(asc: string, length: number): Uint8Array; export function utils_hwaddr_aton(asc: string, buffer: Uint8Array | string): number; export function utils_hwaddr_canonical(asc: string, length: number): string; export function utils_hwaddr_len(type: number): number; export function utils_hwaddr_matches( hwaddr1: any | null, hwaddr1_len: number, hwaddr2: any | null, hwaddr2_len: number ): boolean; export function utils_hwaddr_ntoa(addr: Uint8Array | string): string; export function utils_hwaddr_valid(asc: string, length: number): boolean; export function utils_iface_valid_name(name?: string | null): boolean; export function utils_ip4_addresses_from_variant(value: GLib.Variant): [IPAddress[], string | null]; export function utils_ip4_addresses_to_variant(addresses: IPAddress[], gateway?: string | null): GLib.Variant; export function utils_ip4_dns_from_variant(value: GLib.Variant): string; export function utils_ip4_dns_to_variant(dns: string): GLib.Variant; export function utils_ip4_get_default_prefix(ip: number): number; export function utils_ip4_netmask_to_prefix(netmask: number): number; export function utils_ip4_prefix_to_netmask(prefix: number): number; export function utils_ip4_routes_from_variant(value: GLib.Variant): IPRoute[]; export function utils_ip4_routes_to_variant(routes: IPRoute[]): GLib.Variant; export function utils_ip6_addresses_from_variant(value: GLib.Variant): [IPAddress[], string | null]; export function utils_ip6_addresses_to_variant(addresses: IPAddress[], gateway?: string | null): GLib.Variant; export function utils_ip6_dns_from_variant(value: GLib.Variant): string; export function utils_ip6_dns_to_variant(dns: string): GLib.Variant; export function utils_ip6_routes_from_variant(value: GLib.Variant): IPRoute[]; export function utils_ip6_routes_to_variant(routes: IPRoute[]): GLib.Variant; export function utils_ip_addresses_from_variant(value: GLib.Variant, family: number): IPAddress[]; export function utils_ip_addresses_to_variant(addresses: IPAddress[]): GLib.Variant; export function utils_ip_routes_from_variant(value: GLib.Variant, family: number): IPRoute[]; export function utils_ip_routes_to_variant(routes: IPRoute[]): GLib.Variant; export function utils_ipaddr_valid(family: number, ip: string): boolean; export function utils_is_empty_ssid(ssid: Uint8Array | string): boolean; export function utils_is_json_object(str: string): boolean; export function utils_is_uuid(str?: string | null): boolean; export function utils_is_valid_iface_name(name?: string | null): boolean; export function utils_parse_variant_attributes( string: string, attr_separator: number, key_value_separator: number, ignore_unknown: boolean, spec: VariantAttributeSpec ): GLib.HashTable<string, GLib.Variant>; export function utils_same_ssid( ssid1: Uint8Array | string, ssid2: Uint8Array | string, ignore_trailing_null: boolean ): boolean; export function utils_security_valid( type: UtilsSecurityType, wifi_caps: DeviceWifiCapabilities, have_ap: boolean, adhoc: boolean, ap_flags: __80211ApFlags, ap_wpa: __80211ApSecurityFlags, ap_rsn: __80211ApSecurityFlags ): boolean; export function utils_sriov_vf_from_str(str: string): SriovVF; export function utils_sriov_vf_to_str(vf: SriovVF, omit_index: boolean): string; export function utils_ssid_to_utf8(ssid: Uint8Array | string): string; export function utils_tc_action_from_str(str: string): TCAction; export function utils_tc_action_to_str(action: TCAction): string; export function utils_tc_qdisc_from_str(str: string): TCQdisc; export function utils_tc_qdisc_to_str(qdisc: TCQdisc): string; export function utils_tc_tfilter_from_str(str: string): TCTfilter; export function utils_tc_tfilter_to_str(tfilter: TCTfilter): string; export function utils_uuid_generate(): string; export function utils_version(): number; export function utils_wep_key_valid(key: string, wep_type: WepKeyType): boolean; export function utils_wifi_2ghz_freqs(): number; export function utils_wifi_5ghz_freqs(): number; export function utils_wifi_channel_to_freq(channel: number, band: string): number; export function utils_wifi_find_next_channel(channel: number, direction: number, band: string): number; export function utils_wifi_freq_to_channel(freq: number): number; export function utils_wifi_is_channel_valid(channel: number, band: string): boolean; export function utils_wifi_strength_bars(strength: number): string; export function utils_wpa_psk_valid(psk: string): boolean; export function vpn_editor_plugin_load(plugin_name: string, check_service: string): VpnEditorPlugin; export function vpn_editor_plugin_load_from_file( plugin_name: string, check_service: string, check_owner: number, check_file: UtilsCheckFilePredicate ): VpnEditorPlugin; export function vpn_plugin_error_quark(): GLib.Quark; export type SecretAgentOldDeleteSecretsFunc = ( agent: SecretAgentOld, connection: Connection, error: GLib.Error ) => void; export type SecretAgentOldGetSecretsFunc = ( agent: SecretAgentOld, connection: Connection, secrets: GLib.Variant, error: GLib.Error ) => void; export type SecretAgentOldSaveSecretsFunc = (agent: SecretAgentOld, connection: Connection, error: GLib.Error) => void; export type SettingClearSecretsWithFlagsFn = (setting: Setting, secret: string, flags: SettingSecretFlags) => boolean; export type SettingValueIterFn = (setting: Setting, key: string, value: any, flags: GObject.ParamFlags) => void; export type UtilsCheckFilePredicate = (filename: string, stat?: any | null) => boolean; export type UtilsFileSearchInPathsPredicate = (filename: string) => boolean; export type UtilsPredicateStr = (str: string) => boolean; export type VpnIterFunc = (key: string, value: string) => void; export type _ConnectionForEachSecretFunc = (flags: SettingSecretFlags) => boolean; export namespace __80211Mode { export const $gtype: GObject.GType<__80211Mode>; } export enum __80211Mode { UNKNOWN = 0, ADHOC = 1, INFRA = 2, AP = 3, MESH = 4, } export namespace ActiveConnectionState { export const $gtype: GObject.GType<ActiveConnectionState>; } export enum ActiveConnectionState { UNKNOWN = 0, ACTIVATING = 1, ACTIVATED = 2, DEACTIVATING = 3, DEACTIVATED = 4, } export namespace ActiveConnectionStateReason { export const $gtype: GObject.GType<ActiveConnectionStateReason>; } export enum ActiveConnectionStateReason { UNKNOWN = 0, NONE = 1, USER_DISCONNECTED = 2, DEVICE_DISCONNECTED = 3, SERVICE_STOPPED = 4, IP_CONFIG_INVALID = 5, CONNECT_TIMEOUT = 6, SERVICE_START_TIMEOUT = 7, SERVICE_START_FAILED = 8, NO_SECRETS = 9, LOGIN_FAILED = 10, CONNECTION_REMOVED = 11, DEPENDENCY_FAILED = 12, DEVICE_REALIZE_FAILED = 13, DEVICE_REMOVED = 14, } export class AgentManagerError extends GLib.Error { static $gtype: GObject.GType<AgentManagerError>; constructor(options: { message: string; code: number }); constructor(copy: AgentManagerError); // Properties static FAILED: number; static PERMISSIONDENIED: number; static INVALIDIDENTIFIER: number; static NOTREGISTERED: number; static NOSECRETS: number; static USERCANCELED: number; // Members static quark(): GLib.Quark; } export namespace Capability { export const $gtype: GObject.GType<Capability>; } export enum Capability { TEAM = 1, OVS = 2, } export class ClientError extends GLib.Error { static $gtype: GObject.GType<ClientError>; constructor(options: { message: string; code: number }); constructor(copy: ClientError); // Properties static FAILED: number; static MANAGER_NOT_RUNNING: number; static OBJECT_CREATION_FAILED: number; // Members static quark(): GLib.Quark; } export namespace ClientPermission { export const $gtype: GObject.GType<ClientPermission>; } export enum ClientPermission { NONE = 0, ENABLE_DISABLE_NETWORK = 1, ENABLE_DISABLE_WIFI = 2, ENABLE_DISABLE_WWAN = 3, ENABLE_DISABLE_WIMAX = 4, SLEEP_WAKE = 5, NETWORK_CONTROL = 6, WIFI_SHARE_PROTECTED = 7, WIFI_SHARE_OPEN = 8, SETTINGS_MODIFY_SYSTEM = 9, SETTINGS_MODIFY_OWN = 10, SETTINGS_MODIFY_HOSTNAME = 11, SETTINGS_MODIFY_GLOBAL_DNS = 12, RELOAD = 13, CHECKPOINT_ROLLBACK = 14, ENABLE_DISABLE_STATISTICS = 15, ENABLE_DISABLE_CONNECTIVITY_CHECK = 16, WIFI_SCAN = 17, LAST = 17, } export namespace ClientPermissionResult { export const $gtype: GObject.GType<ClientPermissionResult>; } export enum ClientPermissionResult { UNKNOWN = 0, YES = 1, AUTH = 2, NO = 3, } export class ConnectionError extends GLib.Error { static $gtype: GObject.GType<ConnectionError>; constructor(options: { message: string; code: number }); constructor(copy: ConnectionError); // Properties static FAILED: number; static SETTINGNOTFOUND: number; static PROPERTYNOTFOUND: number; static PROPERTYNOTSECRET: number; static MISSINGSETTING: number; static INVALIDSETTING: number; static MISSINGPROPERTY: number; static INVALIDPROPERTY: number; // Members static quark(): GLib.Quark; } export namespace ConnectionMultiConnect { export const $gtype: GObject.GType<ConnectionMultiConnect>; } export enum ConnectionMultiConnect { DEFAULT = 0, SINGLE = 1, MANUAL_MULTIPLE = 2, MULTIPLE = 3, } export namespace ConnectivityState { export const $gtype: GObject.GType<ConnectivityState>; } export enum ConnectivityState { UNKNOWN = 0, NONE = 1, PORTAL = 2, LIMITED = 3, FULL = 4, } export class CryptoError extends GLib.Error { static $gtype: GObject.GType<CryptoError>; constructor(options: { message: string; code: number }); constructor(copy: CryptoError); // Properties static FAILED: number; static INVALID_DATA: number; static INVALID_PASSWORD: number; static UNKNOWN_CIPHER: number; static DECRYPTION_FAILED: number; static ENCRYPTION_FAILED: number; // Members static quark(): GLib.Quark; } export class DeviceError extends GLib.Error { static $gtype: GObject.GType<DeviceError>; constructor(options: { message: string; code: number }); constructor(copy: DeviceError); // Properties static FAILED: number; static CREATIONFAILED: number; static INVALIDCONNECTION: number; static INCOMPATIBLECONNECTION: number; static NOTACTIVE: number; static NOTSOFTWARE: number; static NOTALLOWED: number; static SPECIFICOBJECTNOTFOUND: number; static VERSIONIDMISMATCH: number; static MISSINGDEPENDENCIES: number; static INVALIDARGUMENT: number; // Members static quark(): GLib.Quark; } export namespace DeviceState { export const $gtype: GObject.GType<DeviceState>; } export enum DeviceState { UNKNOWN = 0, UNMANAGED = 10, UNAVAILABLE = 20, DISCONNECTED = 30, PREPARE = 40, CONFIG = 50, NEED_AUTH = 60, IP_CONFIG = 70, IP_CHECK = 80, SECONDARIES = 90, ACTIVATED = 100, DEACTIVATING = 110, FAILED = 120, } export namespace DeviceStateReason { export const $gtype: GObject.GType<DeviceStateReason>; } export enum DeviceStateReason { NONE = 0, UNKNOWN = 1, NOW_MANAGED = 2, NOW_UNMANAGED = 3, CONFIG_FAILED = 4, IP_CONFIG_UNAVAILABLE = 5, IP_CONFIG_EXPIRED = 6, NO_SECRETS = 7, SUPPLICANT_DISCONNECT = 8, SUPPLICANT_CONFIG_FAILED = 9, SUPPLICANT_FAILED = 10, SUPPLICANT_TIMEOUT = 11, PPP_START_FAILED = 12, PPP_DISCONNECT = 13, PPP_FAILED = 14, DHCP_START_FAILED = 15, DHCP_ERROR = 16, DHCP_FAILED = 17, SHARED_START_FAILED = 18, SHARED_FAILED = 19, AUTOIP_START_FAILED = 20, AUTOIP_ERROR = 21, AUTOIP_FAILED = 22, MODEM_BUSY = 23, MODEM_NO_DIAL_TONE = 24, MODEM_NO_CARRIER = 25, MODEM_DIAL_TIMEOUT = 26, MODEM_DIAL_FAILED = 27, MODEM_INIT_FAILED = 28, GSM_APN_FAILED = 29, GSM_REGISTRATION_NOT_SEARCHING = 30, GSM_REGISTRATION_DENIED = 31, GSM_REGISTRATION_TIMEOUT = 32, GSM_REGISTRATION_FAILED = 33, GSM_PIN_CHECK_FAILED = 34, FIRMWARE_MISSING = 35, REMOVED = 36, SLEEPING = 37, CONNECTION_REMOVED = 38, USER_REQUESTED = 39, CARRIER = 40, CONNECTION_ASSUMED = 41, SUPPLICANT_AVAILABLE = 42, MODEM_NOT_FOUND = 43, BT_FAILED = 44, GSM_SIM_NOT_INSERTED = 45, GSM_SIM_PIN_REQUIRED = 46, GSM_SIM_PUK_REQUIRED = 47, GSM_SIM_WRONG = 48, INFINIBAND_MODE = 49, DEPENDENCY_FAILED = 50, BR2684_FAILED = 51, MODEM_MANAGER_UNAVAILABLE = 52, SSID_NOT_FOUND = 53, SECONDARY_CONNECTION_FAILED = 54, DCB_FCOE_FAILED = 55, TEAMD_CONTROL_FAILED = 56, MODEM_FAILED = 57, MODEM_AVAILABLE = 58, SIM_PIN_INCORRECT = 59, NEW_ACTIVATION = 60, PARENT_CHANGED = 61, PARENT_MANAGED_CHANGED = 62, OVSDB_FAILED = 63, IP_ADDRESS_DUPLICATE = 64, IP_METHOD_UNSUPPORTED = 65, SRIOV_CONFIGURATION_FAILED = 66, PEER_NOT_FOUND = 67, } export namespace DeviceType { export const $gtype: GObject.GType<DeviceType>; } export enum DeviceType { UNKNOWN = 0, ETHERNET = 1, WIFI = 2, UNUSED1 = 3, UNUSED2 = 4, BT = 5, OLPC_MESH = 6, WIMAX = 7, MODEM = 8, INFINIBAND = 9, BOND = 10, VLAN = 11, ADSL = 12, BRIDGE = 13, GENERIC = 14, TEAM = 15, TUN = 16, IP_TUNNEL = 17, MACVLAN = 18, VXLAN = 19, VETH = 20, MACSEC = 21, DUMMY = 22, PPP = 23, OVS_INTERFACE = 24, OVS_PORT = 25, OVS_BRIDGE = 26, WPAN = 27, "6LOWPAN" = 28, WIREGUARD = 29, WIFI_P2P = 30, VRF = 31, } export namespace IPTunnelMode { export const $gtype: GObject.GType<IPTunnelMode>; } export enum IPTunnelMode { UNKNOWN = 0, IPIP = 1, GRE = 2, SIT = 3, ISATAP = 4, VTI = 5, IP6IP6 = 6, IPIP6 = 7, IP6GRE = 8, VTI6 = 9, GRETAP = 10, IP6GRETAP = 11, } export class ManagerError extends GLib.Error { static $gtype: GObject.GType<ManagerError>; constructor(options: { message: string; code: number }); constructor(copy: ManagerError); // Properties static FAILED: number; static PERMISSIONDENIED: number; static UNKNOWNCONNECTION: number; static UNKNOWNDEVICE: number; static CONNECTIONNOTAVAILABLE: number; static CONNECTIONNOTACTIVE: number; static CONNECTIONALREADYACTIVE: number; static DEPENDENCYFAILED: number; static ALREADYASLEEPORAWAKE: number; static ALREADYENABLEDORDISABLED: number; static UNKNOWNLOGLEVEL: number; static UNKNOWNLOGDOMAIN: number; static INVALIDARGUMENTS: number; static MISSINGPLUGIN: number; // Members static quark(): GLib.Quark; } export namespace Metered { export const $gtype: GObject.GType<Metered>; } export enum Metered { UNKNOWN = 0, YES = 1, NO = 2, GUESS_YES = 3, GUESS_NO = 4, } export namespace RollbackResult { export const $gtype: GObject.GType<RollbackResult>; } export enum RollbackResult { OK = 0, ERR_NO_DEVICE = 1, ERR_DEVICE_UNMANAGED = 2, ERR_FAILED = 3, } export class SecretAgentError extends GLib.Error { static $gtype: GObject.GType<SecretAgentError>; constructor(options: { message: string; code: number }); constructor(copy: SecretAgentError); // Properties static FAILED: number; static PERMISSIONDENIED: number; static INVALIDCONNECTION: number; static USERCANCELED: number; static AGENTCANCELED: number; static NOSECRETS: number; // Members static quark(): GLib.Quark; } export namespace Setting8021xCKFormat { export const $gtype: GObject.GType<Setting8021xCKFormat>; } export enum Setting8021xCKFormat { UNKNOWN = 0, X509 = 1, RAW_KEY = 2, PKCS12 = 3, } export namespace Setting8021xCKScheme { export const $gtype: GObject.GType<Setting8021xCKScheme>; } export enum Setting8021xCKScheme { UNKNOWN = 0, BLOB = 1, PATH = 2, PKCS11 = 3, } export namespace SettingCompareFlags { export const $gtype: GObject.GType<SettingCompareFlags>; } export enum SettingCompareFlags { EXACT = 0, FUZZY = 1, IGNORE_ID = 2, IGNORE_SECRETS = 4, IGNORE_AGENT_OWNED_SECRETS = 8, IGNORE_NOT_SAVED_SECRETS = 16, DIFF_RESULT_WITH_DEFAULT = 32, DIFF_RESULT_NO_DEFAULT = 64, IGNORE_TIMESTAMP = 128, } export namespace SettingConnectionAutoconnectSlaves { export const $gtype: GObject.GType<SettingConnectionAutoconnectSlaves>; } export enum SettingConnectionAutoconnectSlaves { DEFAULT = -1, NO = 0, YES = 1, } export namespace SettingConnectionLldp { export const $gtype: GObject.GType<SettingConnectionLldp>; } export enum SettingConnectionLldp { DEFAULT = -1, DISABLE = 0, ENABLE_RX = 1, } export namespace SettingConnectionLlmnr { export const $gtype: GObject.GType<SettingConnectionLlmnr>; } export enum SettingConnectionLlmnr { DEFAULT = -1, NO = 0, RESOLVE = 1, YES = 2, } export namespace SettingConnectionMdns { export const $gtype: GObject.GType<SettingConnectionMdns>; } export enum SettingConnectionMdns { DEFAULT = -1, NO = 0, RESOLVE = 1, YES = 2, } export namespace SettingDiffResult { export const $gtype: GObject.GType<SettingDiffResult>; } export enum SettingDiffResult { UNKNOWN = 0, IN_A = 1, IN_B = 2, IN_A_DEFAULT = 4, IN_B_DEFAULT = 8, } export namespace SettingIP6ConfigAddrGenMode { export const $gtype: GObject.GType<SettingIP6ConfigAddrGenMode>; } export enum SettingIP6ConfigAddrGenMode { EUI64 = 0, STABLE_PRIVACY = 1, } export namespace SettingIP6ConfigPrivacy { export const $gtype: GObject.GType<SettingIP6ConfigPrivacy>; } export enum SettingIP6ConfigPrivacy { UNKNOWN = -1, DISABLED = 0, PREFER_PUBLIC_ADDR = 1, PREFER_TEMP_ADDR = 2, } export namespace SettingMacRandomization { export const $gtype: GObject.GType<SettingMacRandomization>; } export enum SettingMacRandomization { DEFAULT = 0, NEVER = 1, ALWAYS = 2, } export namespace SettingMacsecMode { export const $gtype: GObject.GType<SettingMacsecMode>; } export enum SettingMacsecMode { PSK = 0, EAP = 1, } export namespace SettingMacsecValidation { export const $gtype: GObject.GType<SettingMacsecValidation>; } export enum SettingMacsecValidation { DISABLE = 0, CHECK = 1, STRICT = 2, } export namespace SettingMacvlanMode { export const $gtype: GObject.GType<SettingMacvlanMode>; } export enum SettingMacvlanMode { UNKNOWN = 0, VEPA = 1, BRIDGE = 2, PRIVATE = 3, PASSTHRU = 4, SOURCE = 5, } export namespace SettingProxyMethod { export const $gtype: GObject.GType<SettingProxyMethod>; } export enum SettingProxyMethod { NONE = 0, AUTO = 1, } export namespace SettingSerialParity { export const $gtype: GObject.GType<SettingSerialParity>; } export enum SettingSerialParity { NONE = 0, EVEN = 1, ODD = 2, } export namespace SettingTunMode { export const $gtype: GObject.GType<SettingTunMode>; } export enum SettingTunMode { UNKNOWN = 0, TUN = 1, TAP = 2, } export namespace SettingWirelessPowersave { export const $gtype: GObject.GType<SettingWirelessPowersave>; } export enum SettingWirelessPowersave { DEFAULT = 0, IGNORE = 1, DISABLE = 2, ENABLE = 3, } export namespace SettingWirelessSecurityFils { export const $gtype: GObject.GType<SettingWirelessSecurityFils>; } export enum SettingWirelessSecurityFils { DEFAULT = 0, DISABLE = 1, OPTIONAL = 2, REQUIRED = 3, } export namespace SettingWirelessSecurityPmf { export const $gtype: GObject.GType<SettingWirelessSecurityPmf>; } export enum SettingWirelessSecurityPmf { DEFAULT = 0, DISABLE = 1, OPTIONAL = 2, REQUIRED = 3, } export class SettingsError extends GLib.Error { static $gtype: GObject.GType<SettingsError>; constructor(options: { message: string; code: number }); constructor(copy: SettingsError); // Properties static FAILED: number; static PERMISSIONDENIED: number; static NOTSUPPORTED: number; static INVALIDCONNECTION: number; static READONLYCONNECTION: number; static UUIDEXISTS: number; static INVALIDHOSTNAME: number; static INVALIDARGUMENTS: number; // Members static quark(): GLib.Quark; } export namespace SriovVFVlanProtocol { export const $gtype: GObject.GType<SriovVFVlanProtocol>; } export enum SriovVFVlanProtocol { "1Q" = 0, "1AD" = 1, } export namespace State { export const $gtype: GObject.GType<State>; } export enum State { UNKNOWN = 0, ASLEEP = 10, DISCONNECTED = 20, DISCONNECTING = 30, CONNECTING = 40, CONNECTED_LOCAL = 50, CONNECTED_SITE = 60, CONNECTED_GLOBAL = 70, } export namespace Ternary { export const $gtype: GObject.GType<Ternary>; } export enum Ternary { DEFAULT = -1, FALSE = 0, TRUE = 1, } export namespace UtilsSecurityType { export const $gtype: GObject.GType<UtilsSecurityType>; } export enum UtilsSecurityType { INVALID = 0, NONE = 1, STATIC_WEP = 2, LEAP = 3, DYNAMIC_WEP = 4, WPA_PSK = 5, WPA_ENTERPRISE = 6, WPA2_PSK = 7, WPA2_ENTERPRISE = 8, SAE = 9, OWE = 10, } export namespace VlanPriorityMap { export const $gtype: GObject.GType<VlanPriorityMap>; } export enum VlanPriorityMap { INGRESS_MAP = 0, EGRESS_MAP = 1, } export namespace VpnConnectionState { export const $gtype: GObject.GType<VpnConnectionState>; } export enum VpnConnectionState { UNKNOWN = 0, PREPARE = 1, NEED_AUTH = 2, CONNECT = 3, IP_CONFIG_GET = 4, ACTIVATED = 5, FAILED = 6, DISCONNECTED = 7, } export namespace VpnConnectionStateReason { export const $gtype: GObject.GType<VpnConnectionStateReason>; } export enum VpnConnectionStateReason { VPN_CONNECTION_STATE_REASON_UNKNOWN = 0, VPN_CONNECTION_STATE_REASON_NONE = 1, VPN_CONNECTION_STATE_REASON_USER_DISCONNECTED = 2, ACTIVE_CONNECTION_STATE_REASON_USER_DISCONNECTED = 2, VPN_CONNECTION_STATE_REASON_DEVICE_DISCONNECTED = 3, ACTIVE_CONNECTION_STATE_REASON_DEVICE_DISCONNECTED = 3, VPN_CONNECTION_STATE_REASON_SERVICE_STOPPED = 4, ACTIVE_CONNECTION_STATE_REASON_SERVICE_STOPPED = 4, VPN_CONNECTION_STATE_REASON_IP_CONFIG_INVALID = 5, ACTIVE_CONNECTION_STATE_REASON_IP_CONFIG_INVALID = 5, VPN_CONNECTION_STATE_REASON_CONNECT_TIMEOUT = 6, ACTIVE_CONNECTION_STATE_REASON_CONNECT_TIMEOUT = 6, VPN_CONNECTION_STATE_REASON_SERVICE_START_TIMEOUT = 7, ACTIVE_CONNECTION_STATE_REASON_SERVICE_START_TIMEOUT = 7, VPN_CONNECTION_STATE_REASON_SERVICE_START_FAILED = 8, ACTIVE_CONNECTION_STATE_REASON_SERVICE_START_FAILED = 8, VPN_CONNECTION_STATE_REASON_NO_SECRETS = 9, VPN_CONNECTION_STATE_REASON_LOGIN_FAILED = 10, VPN_CONNECTION_STATE_REASON_CONNECTION_REMOVED = 11, ACTIVE_CONNECTION_STATE_REASON_CONNECTION_REMOVED = 11, } export class VpnPluginError extends GLib.Error { static $gtype: GObject.GType<VpnPluginError>; constructor(options: { message: string; code: number }); constructor(copy: VpnPluginError); // Properties static FAILED: number; static STARTINGINPROGRESS: number; static ALREADYSTARTED: number; static STOPPINGINPROGRESS: number; static ALREADYSTOPPED: number; static WRONGSTATE: number; static BADARGUMENTS: number; static LAUNCHFAILED: number; static INVALIDCONNECTION: number; static INTERACTIVENOTSUPPORTED: number; // Members static quark(): GLib.Quark; } export namespace VpnPluginFailure { export const $gtype: GObject.GType<VpnPluginFailure>; } export enum VpnPluginFailure { LOGIN_FAILED = 0, CONNECT_FAILED = 1, BAD_IP_CONFIG = 2, } export namespace VpnServiceState { export const $gtype: GObject.GType<VpnServiceState>; } export enum VpnServiceState { UNKNOWN = 0, INIT = 1, SHUTDOWN = 2, STARTING = 3, STARTED = 4, STOPPING = 5, STOPPED = 6, } export namespace WepKeyType { export const $gtype: GObject.GType<WepKeyType>; } export enum WepKeyType { UNKNOWN = 0, KEY = 1, PASSPHRASE = 2, } export namespace WimaxNspNetworkType { export const $gtype: GObject.GType<WimaxNspNetworkType>; } export enum WimaxNspNetworkType { UNKNOWN = 0, HOME = 1, PARTNER = 2, ROAMING_PARTNER = 3, } export namespace __80211ApFlags { export const $gtype: GObject.GType<__80211ApFlags>; } export enum __80211ApFlags { NONE = 0, PRIVACY = 1, WPS = 2, WPS_PBC = 4, WPS_PIN = 8, } export namespace __80211ApSecurityFlags { export const $gtype: GObject.GType<__80211ApSecurityFlags>; } export enum __80211ApSecurityFlags { NONE = 0, PAIR_WEP40 = 1, PAIR_WEP104 = 2, PAIR_TKIP = 4, PAIR_CCMP = 8, GROUP_WEP40 = 16, GROUP_WEP104 = 32, GROUP_TKIP = 64, GROUP_CCMP = 128, KEY_MGMT_PSK = 256, KEY_MGMT_802_1X = 512, KEY_MGMT_SAE = 1024, KEY_MGMT_OWE = 2048, KEY_MGMT_OWE_TM = 4096, } export namespace ActivationStateFlags { export const $gtype: GObject.GType<ActivationStateFlags>; } export enum ActivationStateFlags { NONE = 0, IS_MASTER = 1, IS_SLAVE = 2, LAYER2_READY = 4, IP4_READY = 8, IP6_READY = 16, MASTER_HAS_SLAVES = 32, LIFETIME_BOUND_TO_PROFILE_VISIBILITY = 64, EXTERNAL = 128, } export namespace BluetoothCapabilities { export const $gtype: GObject.GType<BluetoothCapabilities>; } export enum BluetoothCapabilities { NONE = 0, DUN = 1, NAP = 2, } export namespace CheckpointCreateFlags { export const $gtype: GObject.GType<CheckpointCreateFlags>; } export enum CheckpointCreateFlags { NONE = 0, DESTROY_ALL = 1, DELETE_NEW_CONNECTIONS = 2, DISCONNECT_NEW_DEVICES = 4, ALLOW_OVERLAPPING = 8, } export namespace ClientInstanceFlags { export const $gtype: GObject.GType<ClientInstanceFlags>; } export enum ClientInstanceFlags { NONE = 0, NO_AUTO_FETCH_PERMISSIONS = 1, } export namespace ConnectionSerializationFlags { export const $gtype: GObject.GType<ConnectionSerializationFlags>; } export enum ConnectionSerializationFlags { ALL = 0, NO_SECRETS = 1, ONLY_SECRETS = 2, WITH_SECRETS_AGENT_OWNED = 4, } export namespace DeviceCapabilities { export const $gtype: GObject.GType<DeviceCapabilities>; } export enum DeviceCapabilities { NONE = 0, NM_SUPPORTED = 1, CARRIER_DETECT = 2, IS_SOFTWARE = 4, SRIOV = 8, } export namespace DeviceInterfaceFlags { export const $gtype: GObject.GType<DeviceInterfaceFlags>; } export enum DeviceInterfaceFlags { UP = 1, LOWER_UP = 2, CARRIER = 65536, } export namespace DeviceModemCapabilities { export const $gtype: GObject.GType<DeviceModemCapabilities>; } export enum DeviceModemCapabilities { NONE = 0, POTS = 1, CDMA_EVDO = 2, GSM_UMTS = 4, LTE = 8, } export namespace DeviceWifiCapabilities { export const $gtype: GObject.GType<DeviceWifiCapabilities>; } export enum DeviceWifiCapabilities { NONE = 0, CIPHER_WEP40 = 1, CIPHER_WEP104 = 2, CIPHER_TKIP = 4, CIPHER_CCMP = 8, WPA = 16, RSN = 32, AP = 64, ADHOC = 128, FREQ_VALID = 256, FREQ_2GHZ = 512, FREQ_5GHZ = 1024, MESH = 4096, IBSS_RSN = 8192, } export namespace DhcpHostnameFlags { export const $gtype: GObject.GType<DhcpHostnameFlags>; } export enum DhcpHostnameFlags { NONE = 0, FQDN_SERV_UPDATE = 1, FQDN_ENCODED = 2, FQDN_NO_UPDATE = 4, FQDN_CLEAR_FLAGS = 8, } export namespace IPAddressCmpFlags { export const $gtype: GObject.GType<IPAddressCmpFlags>; } export enum IPAddressCmpFlags { NONE = 0, WITH_ATTRS = 1, } export namespace IPRoutingRuleAsStringFlags { export const $gtype: GObject.GType<IPRoutingRuleAsStringFlags>; } export enum IPRoutingRuleAsStringFlags { NONE = 0, AF_INET = 1, AF_INET6 = 2, VALIDATE = 4, } export namespace IPTunnelFlags { export const $gtype: GObject.GType<IPTunnelFlags>; } export enum IPTunnelFlags { NONE = 0, IP6_IGN_ENCAP_LIMIT = 1, IP6_USE_ORIG_TCLASS = 2, IP6_USE_ORIG_FLOWLABEL = 4, IP6_MIP6_DEV = 8, IP6_RCV_DSCP_COPY = 16, IP6_USE_ORIG_FWMARK = 32, } export namespace ManagerReloadFlags { export const $gtype: GObject.GType<ManagerReloadFlags>; } export enum ManagerReloadFlags { CONF = 1, DNS_RC = 2, DNS_FULL = 4, } export namespace SecretAgentCapabilities { export const $gtype: GObject.GType<SecretAgentCapabilities>; } export enum SecretAgentCapabilities { NONE = 0, VPN_HINTS = 1, LAST = 1, } export namespace SecretAgentGetSecretsFlags { export const $gtype: GObject.GType<SecretAgentGetSecretsFlags>; } export enum SecretAgentGetSecretsFlags { NONE = 0, ALLOW_INTERACTION = 1, REQUEST_NEW = 2, USER_REQUESTED = 4, WPS_PBC_ACTIVE = 8, ONLY_SYSTEM = 2147483648, NO_ERRORS = 1073741824, } export namespace Setting8021xAuthFlags { export const $gtype: GObject.GType<Setting8021xAuthFlags>; } export enum Setting8021xAuthFlags { NONE = 0, TLS_1_0_DISABLE = 1, TLS_1_1_DISABLE = 2, TLS_1_2_DISABLE = 4, ALL = 7, } export namespace SettingDcbFlags { export const $gtype: GObject.GType<SettingDcbFlags>; } export enum SettingDcbFlags { NONE = 0, ENABLE = 1, ADVERTISE = 2, WILLING = 4, } export namespace SettingSecretFlags { export const $gtype: GObject.GType<SettingSecretFlags>; } export enum SettingSecretFlags { NONE = 0, AGENT_OWNED = 1, NOT_SAVED = 2, NOT_REQUIRED = 4, } export namespace SettingWiredWakeOnLan { export const $gtype: GObject.GType<SettingWiredWakeOnLan>; } export enum SettingWiredWakeOnLan { PHY = 2, UNICAST = 4, MULTICAST = 8, BROADCAST = 16, ARP = 32, MAGIC = 64, DEFAULT = 1, IGNORE = 32768, } export namespace SettingWirelessSecurityWpsMethod { export const $gtype: GObject.GType<SettingWirelessSecurityWpsMethod>; } export enum SettingWirelessSecurityWpsMethod { DEFAULT = 0, DISABLED = 1, AUTO = 2, PBC = 4, PIN = 8, } export namespace SettingWirelessWakeOnWLan { export const $gtype: GObject.GType<SettingWirelessWakeOnWLan>; } export enum SettingWirelessWakeOnWLan { ANY = 2, DISCONNECT = 4, MAGIC = 8, GTK_REKEY_FAILURE = 16, EAP_IDENTITY_REQUEST = 32, "4WAY_HANDSHAKE" = 64, RFKILL_RELEASE = 128, TCP = 256, ALL = 510, DEFAULT = 1, IGNORE = 32768, } export namespace SettingsAddConnection2Flags { export const $gtype: GObject.GType<SettingsAddConnection2Flags>; } export enum SettingsAddConnection2Flags { NONE = 0, TO_DISK = 1, IN_MEMORY = 2, BLOCK_AUTOCONNECT = 32, } export namespace SettingsConnectionFlags { export const $gtype: GObject.GType<SettingsConnectionFlags>; } export enum SettingsConnectionFlags { NONE = 0, UNSAVED = 1, NM_GENERATED = 2, VOLATILE = 4, EXTERNAL = 8, } export namespace SettingsUpdate2Flags { export const $gtype: GObject.GType<SettingsUpdate2Flags>; } export enum SettingsUpdate2Flags { NONE = 0, TO_DISK = 1, IN_MEMORY = 2, IN_MEMORY_DETACHED = 4, IN_MEMORY_ONLY = 8, VOLATILE = 16, BLOCK_AUTOCONNECT = 32, NO_REAPPLY = 64, } export namespace TeamLinkWatcherArpPingFlags { export const $gtype: GObject.GType<TeamLinkWatcherArpPingFlags>; } export enum TeamLinkWatcherArpPingFlags { VALIDATE_ACTIVE = 2, VALIDATE_INACTIVE = 4, SEND_ALWAYS = 8, } export namespace VlanFlags { export const $gtype: GObject.GType<VlanFlags>; } export enum VlanFlags { REORDER_HEADERS = 1, GVRP = 2, LOOSE_BINDING = 4, MVRP = 8, } export namespace VpnEditorPluginCapability { export const $gtype: GObject.GType<VpnEditorPluginCapability>; } export enum VpnEditorPluginCapability { NONE = 0, IMPORT = 1, EXPORT = 2, IPV6 = 4, } export module AccessPoint { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; bssid: string; flags: __80211ApFlags; frequency: number; hw_address: string; hwAddress: string; last_seen: number; lastSeen: number; max_bitrate: number; maxBitrate: number; mode: __80211Mode; rsn_flags: __80211ApSecurityFlags; rsnFlags: __80211ApSecurityFlags; ssid: GLib.Bytes; strength: number; wpa_flags: __80211ApSecurityFlags; wpaFlags: __80211ApSecurityFlags; } } export class AccessPoint extends Object { static $gtype: GObject.GType<AccessPoint>; constructor(properties?: Partial<AccessPoint.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<AccessPoint.ConstructorProperties>, ...args: any[]): void; // Properties bssid: string; flags: __80211ApFlags; frequency: number; hw_address: string; hwAddress: string; last_seen: number; lastSeen: number; max_bitrate: number; maxBitrate: number; mode: __80211Mode; rsn_flags: __80211ApSecurityFlags; rsnFlags: __80211ApSecurityFlags; ssid: GLib.Bytes; strength: number; wpa_flags: __80211ApSecurityFlags; wpaFlags: __80211ApSecurityFlags; // Members connection_valid(connection: Connection): boolean; filter_connections(connections: Connection[]): Connection[]; get_bssid(): string; get_flags(): __80211ApFlags; get_frequency(): number; get_last_seen(): number; get_max_bitrate(): number; get_mode(): __80211Mode; get_rsn_flags(): __80211ApSecurityFlags; get_ssid(): GLib.Bytes; get_strength(): number; get_wpa_flags(): __80211ApSecurityFlags; } export module ActiveConnection { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; connection: RemoteConnection; default: boolean; default6: boolean; devices: Device[]; dhcp4_config: DhcpConfig; dhcp4Config: DhcpConfig; dhcp6_config: DhcpConfig; dhcp6Config: DhcpConfig; id: string; ip4_config: IPConfig; ip4Config: IPConfig; ip6_config: IPConfig; ip6Config: IPConfig; master: Device; specific_object_path: string; specificObjectPath: string; state: ActiveConnectionState; state_flags: number; stateFlags: number; type: string; uuid: string; vpn: boolean; } } export class ActiveConnection extends Object { static $gtype: GObject.GType<ActiveConnection>; constructor(properties?: Partial<ActiveConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ActiveConnection.ConstructorProperties>, ...args: any[]): void; // Properties connection: RemoteConnection; "default": boolean; default6: boolean; devices: Device[]; dhcp4_config: DhcpConfig; dhcp4Config: DhcpConfig; dhcp6_config: DhcpConfig; dhcp6Config: DhcpConfig; id: string; ip4_config: IPConfig; ip4Config: IPConfig; ip6_config: IPConfig; ip6Config: IPConfig; master: Device; specific_object_path: string; specificObjectPath: string; state: ActiveConnectionState; state_flags: number; stateFlags: number; type: string; uuid: string; vpn: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "state-changed", callback: (_source: this, state: number, reason: number) => void): number; connect_after(signal: "state-changed", callback: (_source: this, state: number, reason: number) => void): number; emit(signal: "state-changed", state: number, reason: number): void; // Members get_connection(): RemoteConnection; get_connection_type(): string; get_default(): boolean; get_default6(): boolean; get_devices(): Device[]; get_dhcp4_config(): DhcpConfig; get_dhcp6_config(): DhcpConfig; get_id(): string; get_ip4_config(): IPConfig; get_ip6_config(): IPConfig; get_master(): Device; get_specific_object_path(): string; get_state(): ActiveConnectionState; get_state_flags(): ActivationStateFlags; get_state_reason(): ActiveConnectionStateReason; get_uuid(): string; get_vpn(): boolean; } export module Checkpoint { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; created: number; devices: Device[]; rollback_timeout: number; rollbackTimeout: number; } } export class Checkpoint extends Object { static $gtype: GObject.GType<Checkpoint>; constructor(properties?: Partial<Checkpoint.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Checkpoint.ConstructorProperties>, ...args: any[]): void; // Properties created: number; devices: Device[]; rollback_timeout: number; rollbackTimeout: number; // Members get_created(): number; get_devices(): Device[]; get_rollback_timeout(): number; } export module Client { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; activating_connection: ActiveConnection; activatingConnection: ActiveConnection; active_connections: ActiveConnection[]; activeConnections: ActiveConnection[]; all_devices: Device[]; allDevices: Device[]; can_modify: boolean; canModify: boolean; capabilities: number[]; checkpoints: Checkpoint[]; connections: RemoteConnection[]; connectivity: ConnectivityState; connectivity_check_available: boolean; connectivityCheckAvailable: boolean; connectivity_check_enabled: boolean; connectivityCheckEnabled: boolean; connectivity_check_uri: string; connectivityCheckUri: string; dbus_connection: Gio.DBusConnection; dbusConnection: Gio.DBusConnection; dbus_name_owner: string; dbusNameOwner: string; devices: Device[]; dns_configuration: DnsEntry[]; dnsConfiguration: DnsEntry[]; dns_mode: string; dnsMode: string; dns_rc_manager: string; dnsRcManager: string; hostname: string; instance_flags: number; instanceFlags: number; metered: number; networking_enabled: boolean; networkingEnabled: boolean; nm_running: boolean; nmRunning: boolean; permissions_state: Ternary; permissionsState: Ternary; primary_connection: ActiveConnection; primaryConnection: ActiveConnection; startup: boolean; state: State; version: string; wimax_enabled: boolean; wimaxEnabled: boolean; wimax_hardware_enabled: boolean; wimaxHardwareEnabled: boolean; wireless_enabled: boolean; wirelessEnabled: boolean; wireless_hardware_enabled: boolean; wirelessHardwareEnabled: boolean; wwan_enabled: boolean; wwanEnabled: boolean; wwan_hardware_enabled: boolean; wwanHardwareEnabled: boolean; } } export class Client extends GObject.Object implements Gio.AsyncInitable<Client>, Gio.Initable { static $gtype: GObject.GType<Client>; constructor(properties?: Partial<Client.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Client.ConstructorProperties>, ...args: any[]): void; // Properties activating_connection: ActiveConnection; activatingConnection: ActiveConnection; active_connections: ActiveConnection[]; activeConnections: ActiveConnection[]; all_devices: Device[]; allDevices: Device[]; can_modify: boolean; canModify: boolean; capabilities: number[]; checkpoints: Checkpoint[]; connections: RemoteConnection[]; connectivity: ConnectivityState; connectivity_check_available: boolean; connectivityCheckAvailable: boolean; connectivity_check_enabled: boolean; connectivityCheckEnabled: boolean; connectivity_check_uri: string; connectivityCheckUri: string; dbus_connection: Gio.DBusConnection; dbusConnection: Gio.DBusConnection; dbus_name_owner: string; dbusNameOwner: string; devices: Device[]; dns_configuration: DnsEntry[]; dnsConfiguration: DnsEntry[]; dns_mode: string; dnsMode: string; dns_rc_manager: string; dnsRcManager: string; hostname: string; instance_flags: number; instanceFlags: number; metered: number; networking_enabled: boolean; networkingEnabled: boolean; nm_running: boolean; nmRunning: boolean; permissions_state: Ternary; permissionsState: Ternary; primary_connection: ActiveConnection; primaryConnection: ActiveConnection; startup: boolean; state: State; version: string; wimax_enabled: boolean; wimaxEnabled: boolean; wimax_hardware_enabled: boolean; wimaxHardwareEnabled: boolean; wireless_enabled: boolean; wirelessEnabled: boolean; wireless_hardware_enabled: boolean; wirelessHardwareEnabled: boolean; wwan_enabled: boolean; wwanEnabled: boolean; wwan_hardware_enabled: boolean; wwanHardwareEnabled: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "active-connection-added", callback: (_source: this, active_connection: ActiveConnection) => void ): number; connect_after( signal: "active-connection-added", callback: (_source: this, active_connection: ActiveConnection) => void ): number; emit(signal: "active-connection-added", active_connection: ActiveConnection): void; connect( signal: "active-connection-removed", callback: (_source: this, active_connection: ActiveConnection) => void ): number; connect_after( signal: "active-connection-removed", callback: (_source: this, active_connection: ActiveConnection) => void ): number; emit(signal: "active-connection-removed", active_connection: ActiveConnection): void; connect(signal: "any-device-added", callback: (_source: this, device: Device) => void): number; connect_after(signal: "any-device-added", callback: (_source: this, device: Device) => void): number; emit(signal: "any-device-added", device: Device): void; connect(signal: "any-device-removed", callback: (_source: this, device: Device) => void): number; connect_after(signal: "any-device-removed", callback: (_source: this, device: Device) => void): number; emit(signal: "any-device-removed", device: Device): void; connect(signal: "connection-added", callback: (_source: this, connection: RemoteConnection) => void): number; connect_after(signal: "connection-added", callback: (_source: this, connection: RemoteConnection) => void): number; emit(signal: "connection-added", connection: RemoteConnection): void; connect(signal: "connection-removed", callback: (_source: this, connection: RemoteConnection) => void): number; connect_after( signal: "connection-removed", callback: (_source: this, connection: RemoteConnection) => void ): number; emit(signal: "connection-removed", connection: RemoteConnection): void; connect(signal: "device-added", callback: (_source: this, device: Device) => void): number; connect_after(signal: "device-added", callback: (_source: this, device: Device) => void): number; emit(signal: "device-added", device: Device): void; connect(signal: "device-removed", callback: (_source: this, device: Device) => void): number; connect_after(signal: "device-removed", callback: (_source: this, device: Device) => void): number; emit(signal: "device-removed", device: Device): void; connect( signal: "permission-changed", callback: (_source: this, permission: number, result: number) => void ): number; connect_after( signal: "permission-changed", callback: (_source: this, permission: number, result: number) => void ): number; emit(signal: "permission-changed", permission: number, result: number): void; // Constructors static ["new"](cancellable?: Gio.Cancellable | null): Client; static new_finish(result: Gio.AsyncResult): Client; static new_finish(...args: never[]): never; // Members activate_connection_async( connection?: Connection | null, device?: Device | null, specific_object?: string | null, cancellable?: Gio.Cancellable | null ): Promise<ActiveConnection>; activate_connection_async( connection: Connection | null, device: Device | null, specific_object: string | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; activate_connection_async( connection?: Connection | null, device?: Device | null, specific_object?: string | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<ActiveConnection> | void; activate_connection_finish(result: Gio.AsyncResult): ActiveConnection; add_and_activate_connection2( partial: Connection | null, device: Device, specific_object: string | null, options: GLib.Variant, cancellable?: Gio.Cancellable | null ): Promise<ActiveConnection>; add_and_activate_connection2( partial: Connection | null, device: Device, specific_object: string | null, options: GLib.Variant, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; add_and_activate_connection2( partial: Connection | null, device: Device, specific_object: string | null, options: GLib.Variant, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<ActiveConnection> | void; add_and_activate_connection2_finish(result: Gio.AsyncResult, out_result?: GLib.Variant | null): ActiveConnection; add_and_activate_connection_async( partial: Connection | null, device: Device, specific_object?: string | null, cancellable?: Gio.Cancellable | null ): Promise<ActiveConnection>; add_and_activate_connection_async( partial: Connection | null, device: Device, specific_object: string | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; add_and_activate_connection_async( partial: Connection | null, device: Device, specific_object?: string | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<ActiveConnection> | void; add_and_activate_connection_finish(result: Gio.AsyncResult): ActiveConnection; add_connection2( settings: GLib.Variant, flags: SettingsAddConnection2Flags, args: GLib.Variant | null, ignore_out_result: boolean, cancellable?: Gio.Cancellable | null ): Promise<[RemoteConnection, GLib.Variant | null]>; add_connection2( settings: GLib.Variant, flags: SettingsAddConnection2Flags, args: GLib.Variant | null, ignore_out_result: boolean, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; add_connection2( settings: GLib.Variant, flags: SettingsAddConnection2Flags, args: GLib.Variant | null, ignore_out_result: boolean, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<[RemoteConnection, GLib.Variant | null]> | void; add_connection2_finish(result: Gio.AsyncResult): [RemoteConnection, GLib.Variant | null]; add_connection_async( connection: Connection, save_to_disk: boolean, cancellable?: Gio.Cancellable | null ): Promise<RemoteConnection>; add_connection_async( connection: Connection, save_to_disk: boolean, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; add_connection_async( connection: Connection, save_to_disk: boolean, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<RemoteConnection> | void; add_connection_finish(result: Gio.AsyncResult): RemoteConnection; check_connectivity(cancellable?: Gio.Cancellable | null): ConnectivityState; check_connectivity_async(cancellable?: Gio.Cancellable | null): Promise<ConnectivityState>; check_connectivity_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; check_connectivity_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<ConnectivityState> | void; check_connectivity_finish(result: Gio.AsyncResult): ConnectivityState; checkpoint_adjust_rollback_timeout( checkpoint_path: string, add_timeout: number, cancellable?: Gio.Cancellable | null ): Promise<boolean>; checkpoint_adjust_rollback_timeout( checkpoint_path: string, add_timeout: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; checkpoint_adjust_rollback_timeout( checkpoint_path: string, add_timeout: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; checkpoint_adjust_rollback_timeout_finish(result: Gio.AsyncResult): boolean; checkpoint_create( devices: Device[], rollback_timeout: number, flags: CheckpointCreateFlags, cancellable?: Gio.Cancellable | null ): Promise<Checkpoint>; checkpoint_create( devices: Device[], rollback_timeout: number, flags: CheckpointCreateFlags, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; checkpoint_create( devices: Device[], rollback_timeout: number, flags: CheckpointCreateFlags, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<Checkpoint> | void; checkpoint_create_finish(result: Gio.AsyncResult): Checkpoint; checkpoint_destroy(checkpoint_path: string, cancellable?: Gio.Cancellable | null): Promise<boolean>; checkpoint_destroy( checkpoint_path: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; checkpoint_destroy( checkpoint_path: string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; checkpoint_destroy_finish(result: Gio.AsyncResult): boolean; checkpoint_rollback( checkpoint_path: string, cancellable?: Gio.Cancellable | null ): Promise<GLib.HashTable<string, number>>; checkpoint_rollback( checkpoint_path: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; checkpoint_rollback( checkpoint_path: string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<GLib.HashTable<string, number>> | void; checkpoint_rollback_finish(result: Gio.AsyncResult): GLib.HashTable<string, number>; connectivity_check_get_available(): boolean; connectivity_check_get_enabled(): boolean; connectivity_check_get_uri(): string; connectivity_check_set_enabled(enabled: boolean): void; dbus_call( object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType | null, timeout_msec: number, cancellable?: Gio.Cancellable | null ): Promise<GLib.Variant>; dbus_call( object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType | null, timeout_msec: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; dbus_call( object_path: string, interface_name: string, method_name: string, parameters: GLib.Variant | null, reply_type: GLib.VariantType | null, timeout_msec: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<GLib.Variant> | void; dbus_call_finish(result: Gio.AsyncResult): GLib.Variant; dbus_set_property( object_path: string, interface_name: string, property_name: string, value: GLib.Variant, timeout_msec: number, cancellable?: Gio.Cancellable | null ): Promise<boolean>; dbus_set_property( object_path: string, interface_name: string, property_name: string, value: GLib.Variant, timeout_msec: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; dbus_set_property( object_path: string, interface_name: string, property_name: string, value: GLib.Variant, timeout_msec: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; dbus_set_property_finish(result: Gio.AsyncResult): boolean; deactivate_connection(active: ActiveConnection, cancellable?: Gio.Cancellable | null): boolean; deactivate_connection_async(active: ActiveConnection, cancellable?: Gio.Cancellable | null): Promise<boolean>; deactivate_connection_async( active: ActiveConnection, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; deactivate_connection_async( active: ActiveConnection, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; deactivate_connection_finish(result: Gio.AsyncResult): boolean; get_activating_connection(): ActiveConnection; get_active_connections(): ActiveConnection[]; get_all_devices(): Device[]; get_capabilities(): number[]; get_checkpoints(): Checkpoint[]; get_connection_by_id(id: string): RemoteConnection; get_connection_by_path(path: string): RemoteConnection; get_connection_by_uuid(uuid: string): RemoteConnection; get_connections(): RemoteConnection[]; get_connectivity(): ConnectivityState; get_context_busy_watcher<T = GObject.Object>(): T; get_dbus_connection(): Gio.DBusConnection; get_dbus_name_owner(): string; get_device_by_iface(iface: string): Device; get_device_by_path(object_path: string): Device; get_devices(): Device[]; get_dns_configuration(): DnsEntry[]; get_dns_mode(): string; get_dns_rc_manager(): string; get_instance_flags(): ClientInstanceFlags; get_logging(level?: string | null, domains?: string | null): boolean; get_main_context(): GLib.MainContext; get_metered(): Metered; get_nm_running(): boolean; get_object_by_path(dbus_path: string): Object; get_permission_result(permission: ClientPermission): ClientPermissionResult; get_permissions_state(): Ternary; get_primary_connection(): ActiveConnection; get_startup(): boolean; get_state(): State; get_version(): string; load_connections(filenames: string[], cancellable?: Gio.Cancellable | null): [boolean, string]; load_connections_async(filenames: string[], cancellable?: Gio.Cancellable | null): Promise<[string[]]>; load_connections_async( filenames: string[], cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; load_connections_async( filenames: string[], cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<[string[]]> | void; load_connections_finish(result: Gio.AsyncResult): [boolean, string[]]; networking_get_enabled(): boolean; networking_set_enabled(enabled: boolean): boolean; reload(flags: ManagerReloadFlags, cancellable?: Gio.Cancellable | null): Promise<boolean>; reload( flags: ManagerReloadFlags, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; reload( flags: ManagerReloadFlags, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; reload_connections(cancellable?: Gio.Cancellable | null): boolean; reload_connections_async(cancellable?: Gio.Cancellable | null): Promise<boolean>; reload_connections_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; reload_connections_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; reload_connections_finish(result: Gio.AsyncResult): boolean; reload_finish(result: Gio.AsyncResult): boolean; save_hostname(hostname?: string | null, cancellable?: Gio.Cancellable | null): boolean; save_hostname_async(hostname?: string | null, cancellable?: Gio.Cancellable | null): Promise<boolean>; save_hostname_async( hostname: string | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; save_hostname_async( hostname?: string | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; save_hostname_finish(result: Gio.AsyncResult): boolean; set_logging(level?: string | null, domains?: string | null): boolean; wimax_get_enabled(): boolean; wimax_hardware_get_enabled(): boolean; wimax_set_enabled(enabled: boolean): void; wireless_get_enabled(): boolean; wireless_hardware_get_enabled(): boolean; wireless_set_enabled(enabled: boolean): void; wwan_get_enabled(): boolean; wwan_hardware_get_enabled(): boolean; wwan_set_enabled(enabled: boolean): void; static new_async(cancellable?: Gio.Cancellable | null): Promise<Client>; static new_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<Client> | null): void; static new_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<Client> | null ): Promise<Client> | void; // Implemented Members init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_finish(res: Gio.AsyncResult): boolean; new_finish(res: Gio.AsyncResult): Client; vfunc_init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; vfunc_init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; vfunc_init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_init_finish(res: Gio.AsyncResult): boolean; init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module Device { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; active_connection: ActiveConnection; activeConnection: ActiveConnection; autoconnect: boolean; available_connections: RemoteConnection[]; availableConnections: RemoteConnection[]; capabilities: DeviceCapabilities; device_type: DeviceType; deviceType: DeviceType; dhcp4_config: DhcpConfig; dhcp4Config: DhcpConfig; dhcp6_config: DhcpConfig; dhcp6Config: DhcpConfig; driver: string; driver_version: string; driverVersion: string; firmware_missing: boolean; firmwareMissing: boolean; firmware_version: string; firmwareVersion: string; hw_address: string; hwAddress: string; interface: string; interface_flags: number; interfaceFlags: number; ip_interface: string; ipInterface: string; ip4_config: IPConfig; ip4Config: IPConfig; ip4_connectivity: ConnectivityState; ip4Connectivity: ConnectivityState; ip6_config: IPConfig; ip6Config: IPConfig; ip6_connectivity: ConnectivityState; ip6Connectivity: ConnectivityState; lldp_neighbors: any[]; lldpNeighbors: any[]; managed: boolean; metered: number; mtu: number; nm_plugin_missing: boolean; nmPluginMissing: boolean; path: string; physical_port_id: string; physicalPortId: string; product: string; real: boolean; state: DeviceState; state_reason: number; stateReason: number; udi: string; vendor: string; } } export abstract class Device extends Object { static $gtype: GObject.GType<Device>; constructor(properties?: Partial<Device.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Device.ConstructorProperties>, ...args: any[]): void; // Properties active_connection: ActiveConnection; activeConnection: ActiveConnection; autoconnect: boolean; available_connections: RemoteConnection[]; availableConnections: RemoteConnection[]; capabilities: DeviceCapabilities; device_type: DeviceType; deviceType: DeviceType; dhcp4_config: DhcpConfig; dhcp4Config: DhcpConfig; dhcp6_config: DhcpConfig; dhcp6Config: DhcpConfig; driver: string; driver_version: string; driverVersion: string; firmware_missing: boolean; firmwareMissing: boolean; firmware_version: string; firmwareVersion: string; hw_address: string; hwAddress: string; "interface": string; interface_flags: number; interfaceFlags: number; ip_interface: string; ipInterface: string; ip4_config: IPConfig; ip4Config: IPConfig; ip4_connectivity: ConnectivityState; ip4Connectivity: ConnectivityState; ip6_config: IPConfig; ip6Config: IPConfig; ip6_connectivity: ConnectivityState; ip6Connectivity: ConnectivityState; lldp_neighbors: any[]; lldpNeighbors: any[]; managed: boolean; metered: number; mtu: number; nm_plugin_missing: boolean; nmPluginMissing: boolean; path: string; physical_port_id: string; physicalPortId: string; product: string; real: boolean; state: DeviceState; state_reason: number; stateReason: number; udi: string; vendor: string; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect( signal: "state-changed", callback: (_source: this, new_state: number, old_state: number, reason: number) => void ): number; connect_after( signal: "state-changed", callback: (_source: this, new_state: number, old_state: number, reason: number) => void ): number; emit(signal: "state-changed", new_state: number, old_state: number, reason: number): void; // Members connection_compatible(connection: Connection): boolean; connection_valid(connection: Connection): boolean; ["delete"](cancellable?: Gio.Cancellable | null): boolean; delete_async(cancellable?: Gio.Cancellable | null): Promise<boolean>; delete_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; delete_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; delete_finish(result: Gio.AsyncResult): boolean; disconnect(cancellable?: Gio.Cancellable | null): boolean; disconnect(...args: never[]): never; disconnect_async(cancellable?: Gio.Cancellable | null): Promise<boolean>; disconnect_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; disconnect_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; disconnect_finish(result: Gio.AsyncResult): boolean; filter_connections(connections: Connection[]): Connection[]; get_active_connection(): ActiveConnection; get_applied_connection(flags: number, cancellable?: Gio.Cancellable | null): [Connection, number | null]; get_applied_connection_async( flags: number, cancellable?: Gio.Cancellable | null ): Promise<[Connection, number | null]>; get_applied_connection_async( flags: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; get_applied_connection_async( flags: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<[Connection, number | null]> | void; get_applied_connection_finish(result: Gio.AsyncResult): [Connection, number | null]; get_autoconnect(): boolean; get_available_connections(): RemoteConnection[]; get_capabilities(): DeviceCapabilities; get_connectivity(addr_family: number): ConnectivityState; get_description(): string; get_device_type(): DeviceType; get_dhcp4_config(): DhcpConfig; get_dhcp6_config(): DhcpConfig; get_driver(): string; get_driver_version(): string; get_firmware_missing(): boolean; get_firmware_version(): string; get_hw_address(): string; get_iface(): string; get_interface_flags(): DeviceInterfaceFlags; get_ip4_config(): IPConfig; get_ip6_config(): IPConfig; get_ip_iface(): string; get_lldp_neighbors(): LldpNeighbor[]; get_managed(): boolean; get_metered(): Metered; get_mtu(): number; get_nm_plugin_missing(): boolean; get_path(): string; get_physical_port_id(): string; get_product(): string; get_setting_type(): GObject.GType; get_state(): DeviceState; get_state_reason(): DeviceStateReason; get_type_description(): string; get_udi(): string; get_vendor(): string; is_real(): boolean; is_software(): boolean; reapply( connection: Connection | null, version_id: number, flags: number, cancellable?: Gio.Cancellable | null ): boolean; reapply_async( connection: Connection | null, version_id: number, flags: number, cancellable?: Gio.Cancellable | null ): Promise<boolean>; reapply_async( connection: Connection | null, version_id: number, flags: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; reapply_async( connection: Connection | null, version_id: number, flags: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; reapply_finish(result: Gio.AsyncResult): boolean; set_autoconnect(autoconnect: boolean): void; set_managed(managed: boolean): void; static disambiguate_names(devices: Device[]): string[]; } export module Device6Lowpan { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; } } export class Device6Lowpan extends Device { static $gtype: GObject.GType<Device6Lowpan>; constructor(properties?: Partial<Device6Lowpan.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Device6Lowpan.ConstructorProperties>, ...args: any[]): void; // Members get_parent(): Device; } export module DeviceAdsl { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; carrier: boolean; } } export class DeviceAdsl extends Device { static $gtype: GObject.GType<DeviceAdsl>; constructor(properties?: Partial<DeviceAdsl.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceAdsl.ConstructorProperties>, ...args: any[]): void; // Properties carrier: boolean; // Members get_carrier(): boolean; } export module DeviceBond { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; carrier: boolean; slaves: Device[]; } } export class DeviceBond extends Device { static $gtype: GObject.GType<DeviceBond>; constructor(properties?: Partial<DeviceBond.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceBond.ConstructorProperties>, ...args: any[]): void; // Properties carrier: boolean; slaves: Device[]; // Members get_carrier(): boolean; get_slaves(): Device[]; } export module DeviceBridge { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; carrier: boolean; slaves: Device[]; } } export class DeviceBridge extends Device { static $gtype: GObject.GType<DeviceBridge>; constructor(properties?: Partial<DeviceBridge.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceBridge.ConstructorProperties>, ...args: any[]): void; // Properties carrier: boolean; slaves: Device[]; // Members get_carrier(): boolean; get_slaves(): Device[]; } export module DeviceBt { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; bt_capabilities: BluetoothCapabilities; btCapabilities: BluetoothCapabilities; name: string; } } export class DeviceBt extends Device { static $gtype: GObject.GType<DeviceBt>; constructor(properties?: Partial<DeviceBt.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceBt.ConstructorProperties>, ...args: any[]): void; // Properties bt_capabilities: BluetoothCapabilities; btCapabilities: BluetoothCapabilities; name: string; // Members get_capabilities(): BluetoothCapabilities; get_capabilities(...args: never[]): never; get_name(): string; } export module DeviceDummy { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; } } export class DeviceDummy extends Device { static $gtype: GObject.GType<DeviceDummy>; constructor(properties?: Partial<DeviceDummy.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceDummy.ConstructorProperties>, ...args: any[]): void; } export module DeviceEthernet { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; carrier: boolean; perm_hw_address: string; permHwAddress: string; s390_subchannels: string[]; s390Subchannels: string[]; speed: number; } } export class DeviceEthernet extends Device { static $gtype: GObject.GType<DeviceEthernet>; constructor(properties?: Partial<DeviceEthernet.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceEthernet.ConstructorProperties>, ...args: any[]): void; // Properties carrier: boolean; perm_hw_address: string; permHwAddress: string; s390_subchannels: string[]; s390Subchannels: string[]; speed: number; // Members get_carrier(): boolean; get_permanent_hw_address(): string; get_s390_subchannels(): string[]; get_speed(): number; } export module DeviceGeneric { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; type_description: string; typeDescription: string; } } export class DeviceGeneric extends Device { static $gtype: GObject.GType<DeviceGeneric>; constructor(properties?: Partial<DeviceGeneric.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceGeneric.ConstructorProperties>, ...args: any[]): void; // Properties type_description: string; typeDescription: string; } export module DeviceIPTunnel { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; encapsulation_limit: number; encapsulationLimit: number; flags: number; flow_label: number; flowLabel: number; input_key: string; inputKey: string; local: string; mode: number; output_key: string; outputKey: string; path_mtu_discovery: boolean; pathMtuDiscovery: boolean; remote: string; tos: number; ttl: number; } } export class DeviceIPTunnel extends Device { static $gtype: GObject.GType<DeviceIPTunnel>; constructor(properties?: Partial<DeviceIPTunnel.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceIPTunnel.ConstructorProperties>, ...args: any[]): void; // Properties encapsulation_limit: number; encapsulationLimit: number; flags: number; flow_label: number; flowLabel: number; input_key: string; inputKey: string; local: string; mode: number; output_key: string; outputKey: string; path_mtu_discovery: boolean; pathMtuDiscovery: boolean; remote: string; tos: number; ttl: number; // Members get_encapsulation_limit(): number; get_flags(): IPTunnelFlags; get_flow_label(): number; get_input_key(): string; get_local(): string; get_mode(): IPTunnelMode; get_output_key(): string; get_parent(): Device; get_path_mtu_discovery(): boolean; get_remote(): string; get_tos(): number; get_ttl(): number; } export module DeviceInfiniband { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; carrier: boolean; } } export class DeviceInfiniband extends Device { static $gtype: GObject.GType<DeviceInfiniband>; constructor(properties?: Partial<DeviceInfiniband.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceInfiniband.ConstructorProperties>, ...args: any[]): void; // Properties carrier: boolean; // Members get_carrier(): boolean; } export module DeviceMacsec { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; cipher_suite: number; cipherSuite: number; encoding_sa: number; encodingSa: number; encrypt: boolean; es: boolean; icv_length: number; icvLength: number; include_sci: boolean; includeSci: boolean; protect: boolean; replay_protect: boolean; replayProtect: boolean; scb: boolean; sci: number; validation: string; window: number; } } export class DeviceMacsec extends Device { static $gtype: GObject.GType<DeviceMacsec>; constructor(properties?: Partial<DeviceMacsec.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceMacsec.ConstructorProperties>, ...args: any[]): void; // Properties cipher_suite: number; cipherSuite: number; encoding_sa: number; encodingSa: number; encrypt: boolean; es: boolean; icv_length: number; icvLength: number; include_sci: boolean; includeSci: boolean; protect: boolean; replay_protect: boolean; replayProtect: boolean; scb: boolean; sci: number; validation: string; window: number; // Members get_cipher_suite(): number; get_encoding_sa(): number; get_encrypt(): boolean; get_es(): boolean; get_icv_length(): number; get_include_sci(): boolean; get_parent(): Device; get_protect(): boolean; get_replay_protect(): boolean; get_scb(): boolean; get_sci(): number; get_validation(): string; get_window(): number; } export module DeviceMacvlan { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; mode: string; no_promisc: boolean; noPromisc: boolean; tap: boolean; } } export class DeviceMacvlan extends Device { static $gtype: GObject.GType<DeviceMacvlan>; constructor(properties?: Partial<DeviceMacvlan.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceMacvlan.ConstructorProperties>, ...args: any[]): void; // Properties mode: string; no_promisc: boolean; noPromisc: boolean; tap: boolean; // Members get_mode(): string; get_no_promisc(): boolean; get_parent(): Device; get_tap(): boolean; } export module DeviceModem { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; apn: string; current_capabilities: DeviceModemCapabilities; currentCapabilities: DeviceModemCapabilities; device_id: string; deviceId: string; modem_capabilities: DeviceModemCapabilities; modemCapabilities: DeviceModemCapabilities; operator_code: string; operatorCode: string; } } export class DeviceModem extends Device { static $gtype: GObject.GType<DeviceModem>; constructor(properties?: Partial<DeviceModem.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceModem.ConstructorProperties>, ...args: any[]): void; // Properties apn: string; current_capabilities: DeviceModemCapabilities; currentCapabilities: DeviceModemCapabilities; device_id: string; deviceId: string; modem_capabilities: DeviceModemCapabilities; modemCapabilities: DeviceModemCapabilities; operator_code: string; operatorCode: string; // Members get_apn(): string; get_current_capabilities(): DeviceModemCapabilities; get_device_id(): string; get_modem_capabilities(): DeviceModemCapabilities; get_operator_code(): string; } export module DeviceOlpcMesh { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; active_channel: number; activeChannel: number; companion: DeviceWifi; } } export class DeviceOlpcMesh extends Device { static $gtype: GObject.GType<DeviceOlpcMesh>; constructor(properties?: Partial<DeviceOlpcMesh.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceOlpcMesh.ConstructorProperties>, ...args: any[]): void; // Properties active_channel: number; activeChannel: number; companion: DeviceWifi; // Members get_active_channel(): number; get_companion(): DeviceWifi; } export module DeviceOvsBridge { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; slaves: Device[]; } } export class DeviceOvsBridge extends Device { static $gtype: GObject.GType<DeviceOvsBridge>; constructor(properties?: Partial<DeviceOvsBridge.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceOvsBridge.ConstructorProperties>, ...args: any[]): void; // Properties slaves: Device[]; // Members get_slaves(): Device[]; } export module DeviceOvsInterface { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; } } export class DeviceOvsInterface extends Device { static $gtype: GObject.GType<DeviceOvsInterface>; constructor(properties?: Partial<DeviceOvsInterface.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceOvsInterface.ConstructorProperties>, ...args: any[]): void; } export module DeviceOvsPort { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; slaves: Device[]; } } export class DeviceOvsPort extends Device { static $gtype: GObject.GType<DeviceOvsPort>; constructor(properties?: Partial<DeviceOvsPort.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceOvsPort.ConstructorProperties>, ...args: any[]): void; // Properties slaves: Device[]; // Members get_slaves(): Device[]; } export module DevicePpp { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; } } export class DevicePpp extends Device { static $gtype: GObject.GType<DevicePpp>; constructor(properties?: Partial<DevicePpp.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DevicePpp.ConstructorProperties>, ...args: any[]): void; } export module DeviceTeam { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; carrier: boolean; config: string; slaves: Device[]; } } export class DeviceTeam extends Device { static $gtype: GObject.GType<DeviceTeam>; constructor(properties?: Partial<DeviceTeam.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceTeam.ConstructorProperties>, ...args: any[]): void; // Properties carrier: boolean; config: string; slaves: Device[]; // Members get_carrier(): boolean; get_config(): string; get_slaves(): Device[]; } export module DeviceTun { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; group: number; mode: string; multi_queue: boolean; multiQueue: boolean; no_pi: boolean; noPi: boolean; owner: number; vnet_hdr: boolean; vnetHdr: boolean; } } export class DeviceTun extends Device { static $gtype: GObject.GType<DeviceTun>; constructor(properties?: Partial<DeviceTun.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceTun.ConstructorProperties>, ...args: any[]): void; // Properties group: number; mode: string; multi_queue: boolean; multiQueue: boolean; no_pi: boolean; noPi: boolean; owner: number; vnet_hdr: boolean; vnetHdr: boolean; // Members get_group(): number; get_mode(): string; get_multi_queue(): boolean; get_no_pi(): boolean; get_owner(): number; get_vnet_hdr(): boolean; } export module DeviceVlan { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; carrier: boolean; vlan_id: number; vlanId: number; } } export class DeviceVlan extends Device { static $gtype: GObject.GType<DeviceVlan>; constructor(properties?: Partial<DeviceVlan.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceVlan.ConstructorProperties>, ...args: any[]): void; // Properties carrier: boolean; vlan_id: number; vlanId: number; // Members get_carrier(): boolean; get_parent(): Device; get_vlan_id(): number; } export module DeviceVrf { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; table: number; } } export class DeviceVrf extends Device { static $gtype: GObject.GType<DeviceVrf>; constructor(properties?: Partial<DeviceVrf.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceVrf.ConstructorProperties>, ...args: any[]): void; // Properties table: number; // Members get_table(): number; } export module DeviceVxlan { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; ageing: number; carrier: boolean; dst_port: number; dstPort: number; group: string; id: number; l2miss: boolean; l3miss: boolean; learning: boolean; limit: number; local: string; proxy: boolean; rsc: boolean; src_port_max: number; srcPortMax: number; src_port_min: number; srcPortMin: number; tos: number; ttl: number; } } export class DeviceVxlan extends Device { static $gtype: GObject.GType<DeviceVxlan>; constructor(properties?: Partial<DeviceVxlan.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceVxlan.ConstructorProperties>, ...args: any[]): void; // Properties ageing: number; carrier: boolean; dst_port: number; dstPort: number; group: string; id: number; l2miss: boolean; l3miss: boolean; learning: boolean; limit: number; local: string; proxy: boolean; rsc: boolean; src_port_max: number; srcPortMax: number; src_port_min: number; srcPortMin: number; tos: number; ttl: number; // Members get_ageing(): number; get_carrier(): boolean; get_dst_port(): number; get_group(): string; get_id(): number; get_l2miss(): boolean; get_l3miss(): boolean; get_learning(): boolean; get_limit(): number; get_local(): string; get_parent(): Device; get_proxy(): boolean; get_rsc(): boolean; get_src_port_max(): number; get_src_port_min(): number; get_tos(): number; get_ttl(): number; } export module DeviceWifi { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; access_points: AccessPoint[]; accessPoints: AccessPoint[]; active_access_point: AccessPoint; activeAccessPoint: AccessPoint; bitrate: number; last_scan: number; lastScan: number; mode: __80211Mode; perm_hw_address: string; permHwAddress: string; wireless_capabilities: DeviceWifiCapabilities; wirelessCapabilities: DeviceWifiCapabilities; } } export class DeviceWifi extends Device { static $gtype: GObject.GType<DeviceWifi>; constructor(properties?: Partial<DeviceWifi.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceWifi.ConstructorProperties>, ...args: any[]): void; // Properties access_points: AccessPoint[]; accessPoints: AccessPoint[]; active_access_point: AccessPoint; activeAccessPoint: AccessPoint; bitrate: number; last_scan: number; lastScan: number; mode: __80211Mode; perm_hw_address: string; permHwAddress: string; wireless_capabilities: DeviceWifiCapabilities; wirelessCapabilities: DeviceWifiCapabilities; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "access-point-added", callback: (_source: this, ap: GObject.Object) => void): number; connect_after(signal: "access-point-added", callback: (_source: this, ap: GObject.Object) => void): number; emit(signal: "access-point-added", ap: GObject.Object): void; connect(signal: "access-point-removed", callback: (_source: this, ap: GObject.Object) => void): number; connect_after(signal: "access-point-removed", callback: (_source: this, ap: GObject.Object) => void): number; emit(signal: "access-point-removed", ap: GObject.Object): void; // Members get_access_point_by_path(path: string): AccessPoint; get_access_points(): AccessPoint[]; get_active_access_point(): AccessPoint; get_bitrate(): number; get_capabilities(): DeviceWifiCapabilities; get_capabilities(...args: never[]): never; get_last_scan(): number; get_mode(): __80211Mode; get_permanent_hw_address(): string; request_scan(cancellable?: Gio.Cancellable | null): boolean; request_scan_async(cancellable?: Gio.Cancellable | null): Promise<boolean>; request_scan_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; request_scan_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; request_scan_finish(result: Gio.AsyncResult): boolean; request_scan_options(options: GLib.Variant, cancellable?: Gio.Cancellable | null): boolean; request_scan_options_async( options: GLib.Variant, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): void; } export module DeviceWifiP2P { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; peers: WifiP2PPeer[]; } } export class DeviceWifiP2P extends Device { static $gtype: GObject.GType<DeviceWifiP2P>; constructor(properties?: Partial<DeviceWifiP2P.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceWifiP2P.ConstructorProperties>, ...args: any[]): void; // Properties peers: WifiP2PPeer[]; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "peer-added", callback: (_source: this, peer: GObject.Object) => void): number; connect_after(signal: "peer-added", callback: (_source: this, peer: GObject.Object) => void): number; emit(signal: "peer-added", peer: GObject.Object): void; connect(signal: "peer-removed", callback: (_source: this, peer: GObject.Object) => void): number; connect_after(signal: "peer-removed", callback: (_source: this, peer: GObject.Object) => void): number; emit(signal: "peer-removed", peer: GObject.Object): void; // Members get_peer_by_path(path: string): WifiP2PPeer; get_peers(): WifiP2PPeer[]; start_find(options?: GLib.Variant | null, cancellable?: Gio.Cancellable | null): Promise<boolean>; start_find( options: GLib.Variant | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; start_find( options?: GLib.Variant | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; start_find_finish(result: Gio.AsyncResult): boolean; stop_find(cancellable?: Gio.Cancellable | null): Promise<boolean>; stop_find(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; stop_find( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; stop_find_finish(result: Gio.AsyncResult): boolean; } export module DeviceWimax { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; active_nsp: WimaxNsp; activeNsp: WimaxNsp; bsid: string; center_frequency: number; centerFrequency: number; cinr: number; hw_address: string; hwAddress: string; nsps: WimaxNsp[]; rssi: number; tx_power: number; txPower: number; } } export class DeviceWimax extends Device { static $gtype: GObject.GType<DeviceWimax>; constructor(properties?: Partial<DeviceWimax.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceWimax.ConstructorProperties>, ...args: any[]): void; // Properties active_nsp: WimaxNsp; activeNsp: WimaxNsp; bsid: string; center_frequency: number; centerFrequency: number; cinr: number; hw_address: string; hwAddress: string; nsps: WimaxNsp[]; rssi: number; tx_power: number; txPower: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "nsp-added", callback: (_source: this, nsp: GObject.Object) => void): number; connect_after(signal: "nsp-added", callback: (_source: this, nsp: GObject.Object) => void): number; emit(signal: "nsp-added", nsp: GObject.Object): void; connect(signal: "nsp-removed", callback: (_source: this, nsp: GObject.Object) => void): number; connect_after(signal: "nsp-removed", callback: (_source: this, nsp: GObject.Object) => void): number; emit(signal: "nsp-removed", nsp: GObject.Object): void; // Members get_active_nsp(): WimaxNsp; get_bsid(): string; get_center_frequency(): number; get_cinr(): number; get_hw_address(): string; get_nsp_by_path(path: string): WimaxNsp; get_nsps(): WimaxNsp[]; get_rssi(): number; get_tx_power(): number; } export module DeviceWireGuard { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; fwmark: number; listen_port: number; listenPort: number; public_key: GLib.Bytes; publicKey: GLib.Bytes; } } export class DeviceWireGuard extends Device { static $gtype: GObject.GType<DeviceWireGuard>; constructor(properties?: Partial<DeviceWireGuard.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceWireGuard.ConstructorProperties>, ...args: any[]): void; // Properties fwmark: number; listen_port: number; listenPort: number; public_key: GLib.Bytes; publicKey: GLib.Bytes; // Members get_fwmark(): number; get_listen_port(): number; get_public_key(): GLib.Bytes; } export module DeviceWpan { export interface ConstructorProperties extends Device.ConstructorProperties { [key: string]: any; } } export class DeviceWpan extends Device { static $gtype: GObject.GType<DeviceWpan>; constructor(properties?: Partial<DeviceWpan.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DeviceWpan.ConstructorProperties>, ...args: any[]): void; } export module DhcpConfig { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; family: number; options: GLib.HashTable<string, string>; } } export abstract class DhcpConfig extends Object { static $gtype: GObject.GType<DhcpConfig>; constructor(properties?: Partial<DhcpConfig.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<DhcpConfig.ConstructorProperties>, ...args: any[]): void; // Properties family: number; options: GLib.HashTable<string, string>; // Members get_family(): number; get_one_option(option: string): string; get_options(): GLib.HashTable<string, string>; } export module IPConfig { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; addresses: any[]; domains: string[]; family: number; gateway: string; nameservers: string[]; routes: IPRoute[]; searches: string[]; wins_servers: string[]; winsServers: string[]; } } export abstract class IPConfig extends Object { static $gtype: GObject.GType<IPConfig>; constructor(properties?: Partial<IPConfig.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<IPConfig.ConstructorProperties>, ...args: any[]): void; // Properties addresses: any[]; domains: string[]; family: number; gateway: string; nameservers: string[]; routes: IPRoute[]; searches: string[]; wins_servers: string[]; winsServers: string[]; // Members get_addresses(): IPAddress[]; get_domains(): string[]; get_family(): number; get_gateway(): string; get_nameservers(): string[]; get_routes(): IPRoute[]; get_searches(): string[]; get_wins_servers(): string[]; } export module Object { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; path: string; } } export abstract class Object extends GObject.Object { static $gtype: GObject.GType<Object>; constructor(properties?: Partial<Object.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Object.ConstructorProperties>, ...args: any[]): void; // Properties path: string; // Members get_client(): Client; get_path(): string; } export module RemoteConnection { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; filename: string; flags: number; unsaved: boolean; visible: boolean; } } export class RemoteConnection extends Object implements Connection { static $gtype: GObject.GType<RemoteConnection>; constructor(properties?: Partial<RemoteConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<RemoteConnection.ConstructorProperties>, ...args: any[]): void; // Properties filename: string; flags: number; unsaved: boolean; visible: boolean; // Members commit_changes(save_to_disk: boolean, cancellable?: Gio.Cancellable | null): boolean; commit_changes_async(save_to_disk: boolean, cancellable?: Gio.Cancellable | null): Promise<boolean>; commit_changes_async( save_to_disk: boolean, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; commit_changes_async( save_to_disk: boolean, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; commit_changes_finish(result: Gio.AsyncResult): boolean; ["delete"](cancellable?: Gio.Cancellable | null): boolean; delete_async(cancellable?: Gio.Cancellable | null): Promise<boolean>; delete_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; delete_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; delete_finish(result: Gio.AsyncResult): boolean; get_filename(): string; get_flags(): SettingsConnectionFlags; get_secrets(setting_name: string, cancellable?: Gio.Cancellable | null): GLib.Variant; get_secrets_async(setting_name: string, cancellable?: Gio.Cancellable | null): Promise<GLib.Variant>; get_secrets_async( setting_name: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; get_secrets_async( setting_name: string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<GLib.Variant> | void; get_secrets_finish(result: Gio.AsyncResult): GLib.Variant; get_unsaved(): boolean; get_visible(): boolean; save(cancellable?: Gio.Cancellable | null): boolean; save_async(cancellable?: Gio.Cancellable | null): Promise<boolean>; save_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; save_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; save_finish(result: Gio.AsyncResult): boolean; update2( settings: GLib.Variant | null, flags: SettingsUpdate2Flags, args?: GLib.Variant | null, cancellable?: Gio.Cancellable | null ): Promise<GLib.Variant>; update2( settings: GLib.Variant | null, flags: SettingsUpdate2Flags, args: GLib.Variant | null, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; update2( settings: GLib.Variant | null, flags: SettingsUpdate2Flags, args?: GLib.Variant | null, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<GLib.Variant> | void; update2_finish(result: Gio.AsyncResult): GLib.Variant; // Implemented Members add_setting(setting: Setting): void; clear_secrets(): void; clear_secrets_with_flags(func?: SettingClearSecretsWithFlagsFn | null): void; clear_settings(): void; compare(b: Connection, flags: SettingCompareFlags): boolean; diff(b: Connection, flags: SettingCompareFlags, out_settings: GLib.HashTable<string, GLib.HashTable>): boolean; dump(): void; for_each_setting_value(func: SettingValueIterFn): void; get_connection_type(): string; get_id(): string; get_interface_name(): string; get_path(): string; get_setting(setting_type: GObject.GType): Setting; get_setting_802_1x(): Setting8021x; get_setting_adsl(): SettingAdsl; get_setting_bluetooth(): SettingBluetooth; get_setting_bond(): SettingBond; get_setting_bridge(): SettingBridge; get_setting_bridge_port(): SettingBridgePort; get_setting_by_name(name: string): Setting; get_setting_cdma(): SettingCdma; get_setting_connection(): SettingConnection; get_setting_dcb(): SettingDcb; get_setting_dummy(): SettingDummy; get_setting_generic(): SettingGeneric; get_setting_gsm(): SettingGsm; get_setting_infiniband(): SettingInfiniband; get_setting_ip4_config(): SettingIP4Config; get_setting_ip6_config(): SettingIP6Config; get_setting_ip_tunnel(): SettingIPTunnel; get_setting_macsec(): SettingMacsec; get_setting_macvlan(): SettingMacvlan; get_setting_olpc_mesh(): SettingOlpcMesh; get_setting_ovs_bridge(): SettingOvsBridge; get_setting_ovs_interface(): SettingOvsInterface; get_setting_ovs_patch(): SettingOvsPatch; get_setting_ovs_port(): SettingOvsPort; get_setting_ppp(): SettingPpp; get_setting_pppoe(): SettingPppoe; get_setting_proxy(): SettingProxy; get_setting_serial(): SettingSerial; get_setting_tc_config(): SettingTCConfig; get_setting_team(): SettingTeam; get_setting_team_port(): SettingTeamPort; get_setting_tun(): SettingTun; get_setting_vlan(): SettingVlan; get_setting_vpn(): SettingVpn; get_setting_vxlan(): SettingVxlan; get_setting_wimax(): SettingWimax; get_setting_wired(): SettingWired; get_setting_wireless(): SettingWireless; get_setting_wireless_security(): SettingWirelessSecurity; get_settings(): Setting[]; get_uuid(): string; get_virtual_device_description(): string; is_type(type: string): boolean; is_virtual(): boolean; need_secrets(): [string, string[] | null]; normalize(parameters?: GLib.HashTable<string, any> | null): [boolean, boolean | null]; remove_setting(setting_type: GObject.GType): void; replace_settings(new_settings: GLib.Variant): boolean; replace_settings_from_connection(new_connection: Connection): void; set_path(path: string): void; to_dbus(flags: ConnectionSerializationFlags): GLib.Variant; update_secrets(setting_name: string, secrets: GLib.Variant): boolean; verify(): boolean; verify_secrets(): boolean; vfunc_changed(): void; vfunc_secrets_cleared(): void; vfunc_secrets_updated(setting: string): void; } export module SecretAgentOld { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; auto_register: boolean; autoRegister: boolean; capabilities: SecretAgentCapabilities; dbus_connection: Gio.DBusConnection; dbusConnection: Gio.DBusConnection; identifier: string; registered: boolean; } } export abstract class SecretAgentOld extends GObject.Object implements Gio.AsyncInitable<SecretAgentOld>, Gio.Initable { static $gtype: GObject.GType<SecretAgentOld>; constructor(properties?: Partial<SecretAgentOld.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SecretAgentOld.ConstructorProperties>, ...args: any[]): void; // Properties auto_register: boolean; autoRegister: boolean; capabilities: SecretAgentCapabilities; dbus_connection: Gio.DBusConnection; dbusConnection: Gio.DBusConnection; identifier: string; registered: boolean; // Members delete_secrets(connection: Connection, callback: SecretAgentOldDeleteSecretsFunc): void; destroy(): void; enable(enable: boolean): void; get_context_busy_watcher<T = GObject.Object>(): T; get_dbus_connection(): Gio.DBusConnection; get_dbus_name_owner(): string; get_main_context(): GLib.MainContext; get_registered(): boolean; get_secrets( connection: Connection, setting_name: string, hints: string[], flags: SecretAgentGetSecretsFlags, callback: SecretAgentOldGetSecretsFunc ): void; register(cancellable?: Gio.Cancellable | null): boolean; register_async(cancellable?: Gio.Cancellable | null): Promise<boolean>; register_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; register_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; register_finish(result: Gio.AsyncResult): boolean; save_secrets(connection: Connection, callback: SecretAgentOldSaveSecretsFunc): void; unregister(cancellable?: Gio.Cancellable | null): boolean; unregister_async(cancellable?: Gio.Cancellable | null): Promise<boolean>; unregister_async(cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; unregister_async( cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; unregister_finish(result: Gio.AsyncResult): boolean; vfunc_cancel_get_secrets(connection_path: string, setting_name: string): void; vfunc_delete_secrets( connection: Connection, connection_path: string, callback: SecretAgentOldDeleteSecretsFunc ): void; vfunc_get_secrets( connection: Connection, connection_path: string, setting_name: string, hints: string[], flags: SecretAgentGetSecretsFlags, callback: SecretAgentOldGetSecretsFunc ): void; vfunc_save_secrets(connection: Connection, connection_path: string, callback: SecretAgentOldSaveSecretsFunc): void; // Implemented Members init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; init_finish(res: Gio.AsyncResult): boolean; new_finish(res: Gio.AsyncResult): SecretAgentOld; vfunc_init_async(io_priority: number, cancellable?: Gio.Cancellable | null): Promise<boolean>; vfunc_init_async( io_priority: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; vfunc_init_async( io_priority: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<boolean> | void; vfunc_init_finish(res: Gio.AsyncResult): boolean; init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module Setting { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; name: string; } } export abstract class Setting extends GObject.Object { static $gtype: GObject.GType<Setting>; constructor(properties?: Partial<Setting.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Setting.ConstructorProperties>, ...args: any[]): void; // Properties name: string; // Members compare(b: Setting, flags: SettingCompareFlags): boolean; diff( b: Setting, flags: SettingCompareFlags, invert_results: boolean, results: GLib.HashTable<string, number> ): [boolean, GLib.HashTable<string, number>]; duplicate(): Setting; enumerate_values(func: SettingValueIterFn): void; get_dbus_property_type(property_name: string): GLib.VariantType; get_name(): string; get_secret_flags(secret_name: string, out_flags: SettingSecretFlags): boolean; option_clear_by_name(predicate?: UtilsPredicateStr | null): void; option_get(opt_name: string): GLib.Variant; option_get_all_names(): string[]; option_get_boolean(opt_name: string): [boolean, boolean | null]; option_get_uint32(opt_name: string): [boolean, number | null]; option_set(opt_name: string, variant?: GLib.Variant | null): void; option_set_boolean(opt_name: string, value: boolean): void; option_set_uint32(opt_name: string, value: number): void; set_secret_flags(secret_name: string, flags: SettingSecretFlags): boolean; to_string(): string; verify(connection?: Connection | null): boolean; verify_secrets(connection?: Connection | null): boolean; vfunc_aggregate(type_i: number, arg?: any | null): boolean; vfunc_get_secret_flags(secret_name: string, out_flags: SettingSecretFlags): boolean; vfunc_init_from_dbus( keys: GLib.HashTable<any, any>, setting_dict: GLib.Variant, connection_dict: GLib.Variant, parse_flags: number ): boolean; vfunc_set_secret_flags(secret_name: string, flags: SettingSecretFlags): boolean; vfunc_update_one_secret(key: string, value: GLib.Variant): number; vfunc_verify(connection: Connection): number; vfunc_verify_secrets(connection?: Connection | null): boolean; static lookup_type(name: string): GObject.GType; } export module Setting6Lowpan { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; } } export class Setting6Lowpan extends Setting { static $gtype: GObject.GType<Setting6Lowpan>; constructor(properties?: Partial<Setting6Lowpan.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Setting6Lowpan.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): Setting6Lowpan; // Members get_parent(): string; } export module Setting8021x { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; altsubject_matches: string[]; altsubjectMatches: string[]; anonymous_identity: string; anonymousIdentity: string; auth_timeout: number; authTimeout: number; ca_cert: GLib.Bytes; caCert: GLib.Bytes; ca_cert_password: string; caCertPassword: string; ca_cert_password_flags: SettingSecretFlags; caCertPasswordFlags: SettingSecretFlags; ca_path: string; caPath: string; client_cert: GLib.Bytes; clientCert: GLib.Bytes; client_cert_password: string; clientCertPassword: string; client_cert_password_flags: SettingSecretFlags; clientCertPasswordFlags: SettingSecretFlags; domain_match: string; domainMatch: string; domain_suffix_match: string; domainSuffixMatch: string; eap: string[]; identity: string; optional: boolean; pac_file: string; pacFile: string; password: string; password_flags: SettingSecretFlags; passwordFlags: SettingSecretFlags; password_raw: GLib.Bytes; passwordRaw: GLib.Bytes; password_raw_flags: SettingSecretFlags; passwordRawFlags: SettingSecretFlags; phase1_auth_flags: number; phase1AuthFlags: number; phase1_fast_provisioning: string; phase1FastProvisioning: string; phase1_peaplabel: string; phase1Peaplabel: string; phase1_peapver: string; phase1Peapver: string; phase2_altsubject_matches: string[]; phase2AltsubjectMatches: string[]; phase2_auth: string; phase2Auth: string; phase2_autheap: string; phase2Autheap: string; phase2_ca_cert: GLib.Bytes; phase2CaCert: GLib.Bytes; phase2_ca_cert_password: string; phase2CaCertPassword: string; phase2_ca_cert_password_flags: SettingSecretFlags; phase2CaCertPasswordFlags: SettingSecretFlags; phase2_ca_path: string; phase2CaPath: string; phase2_client_cert: GLib.Bytes; phase2ClientCert: GLib.Bytes; phase2_client_cert_password: string; phase2ClientCertPassword: string; phase2_client_cert_password_flags: SettingSecretFlags; phase2ClientCertPasswordFlags: SettingSecretFlags; phase2_domain_match: string; phase2DomainMatch: string; phase2_domain_suffix_match: string; phase2DomainSuffixMatch: string; phase2_private_key: GLib.Bytes; phase2PrivateKey: GLib.Bytes; phase2_private_key_password: string; phase2PrivateKeyPassword: string; phase2_private_key_password_flags: SettingSecretFlags; phase2PrivateKeyPasswordFlags: SettingSecretFlags; phase2_subject_match: string; phase2SubjectMatch: string; pin: string; pin_flags: SettingSecretFlags; pinFlags: SettingSecretFlags; private_key: GLib.Bytes; privateKey: GLib.Bytes; private_key_password: string; privateKeyPassword: string; private_key_password_flags: SettingSecretFlags; privateKeyPasswordFlags: SettingSecretFlags; subject_match: string; subjectMatch: string; system_ca_certs: boolean; systemCaCerts: boolean; } } export class Setting8021x extends Setting { static $gtype: GObject.GType<Setting8021x>; constructor(properties?: Partial<Setting8021x.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Setting8021x.ConstructorProperties>, ...args: any[]): void; // Properties altsubject_matches: string[]; altsubjectMatches: string[]; anonymous_identity: string; anonymousIdentity: string; auth_timeout: number; authTimeout: number; ca_cert: GLib.Bytes; caCert: GLib.Bytes; ca_cert_password: string; caCertPassword: string; ca_cert_password_flags: SettingSecretFlags; caCertPasswordFlags: SettingSecretFlags; ca_path: string; caPath: string; client_cert: GLib.Bytes; clientCert: GLib.Bytes; client_cert_password: string; clientCertPassword: string; client_cert_password_flags: SettingSecretFlags; clientCertPasswordFlags: SettingSecretFlags; domain_match: string; domainMatch: string; domain_suffix_match: string; domainSuffixMatch: string; eap: string[]; identity: string; optional: boolean; pac_file: string; pacFile: string; password: string; password_flags: SettingSecretFlags; passwordFlags: SettingSecretFlags; password_raw: GLib.Bytes; passwordRaw: GLib.Bytes; password_raw_flags: SettingSecretFlags; passwordRawFlags: SettingSecretFlags; phase1_auth_flags: number; phase1AuthFlags: number; phase1_fast_provisioning: string; phase1FastProvisioning: string; phase1_peaplabel: string; phase1Peaplabel: string; phase1_peapver: string; phase1Peapver: string; phase2_altsubject_matches: string[]; phase2AltsubjectMatches: string[]; phase2_auth: string; phase2Auth: string; phase2_autheap: string; phase2Autheap: string; phase2_ca_cert: GLib.Bytes; phase2CaCert: GLib.Bytes; phase2_ca_cert_password: string; phase2CaCertPassword: string; phase2_ca_cert_password_flags: SettingSecretFlags; phase2CaCertPasswordFlags: SettingSecretFlags; phase2_ca_path: string; phase2CaPath: string; phase2_client_cert: GLib.Bytes; phase2ClientCert: GLib.Bytes; phase2_client_cert_password: string; phase2ClientCertPassword: string; phase2_client_cert_password_flags: SettingSecretFlags; phase2ClientCertPasswordFlags: SettingSecretFlags; phase2_domain_match: string; phase2DomainMatch: string; phase2_domain_suffix_match: string; phase2DomainSuffixMatch: string; phase2_private_key: GLib.Bytes; phase2PrivateKey: GLib.Bytes; phase2_private_key_password: string; phase2PrivateKeyPassword: string; phase2_private_key_password_flags: SettingSecretFlags; phase2PrivateKeyPasswordFlags: SettingSecretFlags; phase2_subject_match: string; phase2SubjectMatch: string; pin: string; pin_flags: SettingSecretFlags; pinFlags: SettingSecretFlags; private_key: GLib.Bytes; privateKey: GLib.Bytes; private_key_password: string; privateKeyPassword: string; private_key_password_flags: SettingSecretFlags; privateKeyPasswordFlags: SettingSecretFlags; subject_match: string; subjectMatch: string; system_ca_certs: boolean; systemCaCerts: boolean; // Constructors static ["new"](): Setting8021x; // Members add_altsubject_match(altsubject_match: string): boolean; add_eap_method(eap: string): boolean; add_phase2_altsubject_match(phase2_altsubject_match: string): boolean; clear_altsubject_matches(): void; clear_eap_methods(): void; clear_phase2_altsubject_matches(): void; get_altsubject_match(i: number): string; get_anonymous_identity(): string; get_auth_timeout(): number; get_ca_cert_blob(): GLib.Bytes; get_ca_cert_password(): string; get_ca_cert_password_flags(): SettingSecretFlags; get_ca_cert_path(): string; get_ca_cert_scheme(): Setting8021xCKScheme; get_ca_cert_uri(): string; get_ca_path(): string; get_client_cert_blob(): GLib.Bytes; get_client_cert_password(): string; get_client_cert_password_flags(): SettingSecretFlags; get_client_cert_path(): string; get_client_cert_scheme(): Setting8021xCKScheme; get_client_cert_uri(): string; get_domain_match(): string; get_domain_suffix_match(): string; get_eap_method(i: number): string; get_identity(): string; get_num_altsubject_matches(): number; get_num_eap_methods(): number; get_num_phase2_altsubject_matches(): number; get_optional(): boolean; get_pac_file(): string; get_password(): string; get_password_flags(): SettingSecretFlags; get_password_raw(): GLib.Bytes; get_password_raw_flags(): SettingSecretFlags; get_phase1_auth_flags(): Setting8021xAuthFlags; get_phase1_fast_provisioning(): string; get_phase1_peaplabel(): string; get_phase1_peapver(): string; get_phase2_altsubject_match(i: number): string; get_phase2_auth(): string; get_phase2_autheap(): string; get_phase2_ca_cert_blob(): GLib.Bytes; get_phase2_ca_cert_password(): string; get_phase2_ca_cert_password_flags(): SettingSecretFlags; get_phase2_ca_cert_path(): string; get_phase2_ca_cert_scheme(): Setting8021xCKScheme; get_phase2_ca_cert_uri(): string; get_phase2_ca_path(): string; get_phase2_client_cert_blob(): GLib.Bytes; get_phase2_client_cert_password(): string; get_phase2_client_cert_password_flags(): SettingSecretFlags; get_phase2_client_cert_path(): string; get_phase2_client_cert_scheme(): Setting8021xCKScheme; get_phase2_client_cert_uri(): string; get_phase2_domain_match(): string; get_phase2_domain_suffix_match(): string; get_phase2_private_key_blob(): GLib.Bytes; get_phase2_private_key_format(): Setting8021xCKFormat; get_phase2_private_key_password(): string; get_phase2_private_key_password_flags(): SettingSecretFlags; get_phase2_private_key_path(): string; get_phase2_private_key_scheme(): Setting8021xCKScheme; get_phase2_private_key_uri(): string; get_phase2_subject_match(): string; get_pin(): string; get_pin_flags(): SettingSecretFlags; get_private_key_blob(): GLib.Bytes; get_private_key_format(): Setting8021xCKFormat; get_private_key_password(): string; get_private_key_password_flags(): SettingSecretFlags; get_private_key_path(): string; get_private_key_scheme(): Setting8021xCKScheme; get_private_key_uri(): string; get_subject_match(): string; get_system_ca_certs(): boolean; remove_altsubject_match(i: number): void; remove_altsubject_match_by_value(altsubject_match: string): boolean; remove_eap_method(i: number): void; remove_eap_method_by_value(eap: string): boolean; remove_phase2_altsubject_match(i: number): void; remove_phase2_altsubject_match_by_value(phase2_altsubject_match: string): boolean; set_ca_cert(value: string, scheme: Setting8021xCKScheme, out_format: Setting8021xCKFormat): boolean; set_client_cert(value: string, scheme: Setting8021xCKScheme, out_format: Setting8021xCKFormat): boolean; set_phase2_ca_cert(value: string, scheme: Setting8021xCKScheme, out_format: Setting8021xCKFormat): boolean; set_phase2_client_cert(value: string, scheme: Setting8021xCKScheme, out_format: Setting8021xCKFormat): boolean; set_phase2_private_key( value: string, password: string, scheme: Setting8021xCKScheme, out_format: Setting8021xCKFormat ): boolean; set_private_key( value: string, password: string, scheme: Setting8021xCKScheme, out_format: Setting8021xCKFormat ): boolean; static check_cert_scheme(pdata: any | null, length: number): Setting8021xCKScheme; } export module SettingAdsl { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; encapsulation: string; password: string; password_flags: SettingSecretFlags; passwordFlags: SettingSecretFlags; protocol: string; username: string; vci: number; vpi: number; } } export class SettingAdsl extends Setting { static $gtype: GObject.GType<SettingAdsl>; constructor(properties?: Partial<SettingAdsl.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingAdsl.ConstructorProperties>, ...args: any[]): void; // Properties encapsulation: string; password: string; password_flags: SettingSecretFlags; passwordFlags: SettingSecretFlags; protocol: string; username: string; vci: number; vpi: number; // Constructors static ["new"](): SettingAdsl; // Members get_encapsulation(): string; get_password(): string; get_password_flags(): SettingSecretFlags; get_protocol(): string; get_username(): string; get_vci(): number; get_vpi(): number; } export module SettingBluetooth { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; bdaddr: string; type: string; } } export class SettingBluetooth extends Setting { static $gtype: GObject.GType<SettingBluetooth>; constructor(properties?: Partial<SettingBluetooth.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingBluetooth.ConstructorProperties>, ...args: any[]): void; // Properties bdaddr: string; type: string; // Constructors static ["new"](): SettingBluetooth; // Members get_bdaddr(): string; get_connection_type(): string; } export module SettingBond { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; options: GLib.HashTable<string, string>; } } export class SettingBond extends Setting { static $gtype: GObject.GType<SettingBond>; constructor(properties?: Partial<SettingBond.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingBond.ConstructorProperties>, ...args: any[]): void; // Properties options: GLib.HashTable<string, string>; // Constructors static ["new"](): SettingBond; // Members add_option(name: string, value: string): boolean; get_num_options(): number; get_option(idx: number): [boolean, string, string]; get_option_by_name(name: string): string; get_option_default(name: string): string; get_option_normalized(name: string): string; get_valid_options(): string[]; remove_option(name: string): boolean; static validate_option(name: string, value: string): boolean; } export module SettingBridge { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; ageing_time: number; ageingTime: number; forward_delay: number; forwardDelay: number; group_address: string; groupAddress: string; group_forward_mask: number; groupForwardMask: number; hello_time: number; helloTime: number; mac_address: string; macAddress: string; max_age: number; maxAge: number; multicast_hash_max: number; multicastHashMax: number; multicast_last_member_count: number; multicastLastMemberCount: number; multicast_last_member_interval: number; multicastLastMemberInterval: number; multicast_membership_interval: number; multicastMembershipInterval: number; multicast_querier: boolean; multicastQuerier: boolean; multicast_querier_interval: number; multicastQuerierInterval: number; multicast_query_interval: number; multicastQueryInterval: number; multicast_query_response_interval: number; multicastQueryResponseInterval: number; multicast_query_use_ifaddr: boolean; multicastQueryUseIfaddr: boolean; multicast_router: string; multicastRouter: string; multicast_snooping: boolean; multicastSnooping: boolean; multicast_startup_query_count: number; multicastStartupQueryCount: number; multicast_startup_query_interval: number; multicastStartupQueryInterval: number; priority: number; stp: boolean; vlan_default_pvid: number; vlanDefaultPvid: number; vlan_filtering: boolean; vlanFiltering: boolean; vlan_protocol: string; vlanProtocol: string; vlan_stats_enabled: boolean; vlanStatsEnabled: boolean; vlans: BridgeVlan[]; } } export class SettingBridge extends Setting { static $gtype: GObject.GType<SettingBridge>; constructor(properties?: Partial<SettingBridge.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingBridge.ConstructorProperties>, ...args: any[]): void; // Properties ageing_time: number; ageingTime: number; forward_delay: number; forwardDelay: number; group_address: string; groupAddress: string; group_forward_mask: number; groupForwardMask: number; hello_time: number; helloTime: number; mac_address: string; macAddress: string; max_age: number; maxAge: number; multicast_hash_max: number; multicastHashMax: number; multicast_last_member_count: number; multicastLastMemberCount: number; multicast_last_member_interval: number; multicastLastMemberInterval: number; multicast_membership_interval: number; multicastMembershipInterval: number; multicast_querier: boolean; multicastQuerier: boolean; multicast_querier_interval: number; multicastQuerierInterval: number; multicast_query_interval: number; multicastQueryInterval: number; multicast_query_response_interval: number; multicastQueryResponseInterval: number; multicast_query_use_ifaddr: boolean; multicastQueryUseIfaddr: boolean; multicast_router: string; multicastRouter: string; multicast_snooping: boolean; multicastSnooping: boolean; multicast_startup_query_count: number; multicastStartupQueryCount: number; multicast_startup_query_interval: number; multicastStartupQueryInterval: number; priority: number; stp: boolean; vlan_default_pvid: number; vlanDefaultPvid: number; vlan_filtering: boolean; vlanFiltering: boolean; vlan_protocol: string; vlanProtocol: string; vlan_stats_enabled: boolean; vlanStatsEnabled: boolean; vlans: BridgeVlan[]; // Constructors static ["new"](): SettingBridge; // Members add_vlan(vlan: BridgeVlan): void; clear_vlans(): void; get_ageing_time(): number; get_forward_delay(): number; get_group_address(): string; get_group_forward_mask(): number; get_hello_time(): number; get_mac_address(): string; get_max_age(): number; get_multicast_hash_max(): number; get_multicast_last_member_count(): number; get_multicast_last_member_interval(): number; get_multicast_membership_interval(): number; get_multicast_querier(): boolean; get_multicast_querier_interval(): number; get_multicast_query_interval(): number; get_multicast_query_response_interval(): number; get_multicast_query_use_ifaddr(): boolean; get_multicast_router(): string; get_multicast_snooping(): boolean; get_multicast_startup_query_count(): number; get_multicast_startup_query_interval(): number; get_num_vlans(): number; get_priority(): number; get_stp(): boolean; get_vlan(idx: number): BridgeVlan; get_vlan_default_pvid(): number; get_vlan_filtering(): boolean; get_vlan_protocol(): string; get_vlan_stats_enabled(): boolean; remove_vlan(idx: number): void; remove_vlan_by_vid(vid_start: number, vid_end: number): boolean; } export module SettingBridgePort { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; hairpin_mode: boolean; hairpinMode: boolean; path_cost: number; pathCost: number; priority: number; vlans: BridgeVlan[]; } } export class SettingBridgePort extends Setting { static $gtype: GObject.GType<SettingBridgePort>; constructor(properties?: Partial<SettingBridgePort.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingBridgePort.ConstructorProperties>, ...args: any[]): void; // Properties hairpin_mode: boolean; hairpinMode: boolean; path_cost: number; pathCost: number; priority: number; vlans: BridgeVlan[]; // Constructors static ["new"](): SettingBridgePort; // Members add_vlan(vlan: BridgeVlan): void; clear_vlans(): void; get_hairpin_mode(): boolean; get_num_vlans(): number; get_path_cost(): number; get_priority(): number; get_vlan(idx: number): BridgeVlan; remove_vlan(idx: number): void; remove_vlan_by_vid(vid_start: number, vid_end: number): boolean; } export module SettingCdma { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; mtu: number; number: string; password: string; password_flags: SettingSecretFlags; passwordFlags: SettingSecretFlags; username: string; } } export class SettingCdma extends Setting { static $gtype: GObject.GType<SettingCdma>; constructor(properties?: Partial<SettingCdma.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingCdma.ConstructorProperties>, ...args: any[]): void; // Properties mtu: number; number: string; password: string; password_flags: SettingSecretFlags; passwordFlags: SettingSecretFlags; username: string; // Constructors static ["new"](): SettingCdma; // Members get_mtu(): number; get_number(): string; get_password(): string; get_password_flags(): SettingSecretFlags; get_username(): string; } export module SettingConnection { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; auth_retries: number; authRetries: number; autoconnect: boolean; autoconnect_priority: number; autoconnectPriority: number; autoconnect_retries: number; autoconnectRetries: number; autoconnect_slaves: SettingConnectionAutoconnectSlaves; autoconnectSlaves: SettingConnectionAutoconnectSlaves; gateway_ping_timeout: number; gatewayPingTimeout: number; id: string; interface_name: string; interfaceName: string; lldp: number; llmnr: number; master: string; mdns: number; metered: Metered; mud_url: string; mudUrl: string; multi_connect: number; multiConnect: number; permissions: string[]; read_only: boolean; readOnly: boolean; secondaries: string[]; slave_type: string; slaveType: string; stable_id: string; stableId: string; timestamp: number; type: string; uuid: string; wait_device_timeout: number; waitDeviceTimeout: number; zone: string; } } export class SettingConnection extends Setting { static $gtype: GObject.GType<SettingConnection>; constructor(properties?: Partial<SettingConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingConnection.ConstructorProperties>, ...args: any[]): void; // Properties auth_retries: number; authRetries: number; autoconnect: boolean; autoconnect_priority: number; autoconnectPriority: number; autoconnect_retries: number; autoconnectRetries: number; autoconnect_slaves: SettingConnectionAutoconnectSlaves; autoconnectSlaves: SettingConnectionAutoconnectSlaves; gateway_ping_timeout: number; gatewayPingTimeout: number; id: string; interface_name: string; interfaceName: string; lldp: number; llmnr: number; master: string; mdns: number; metered: Metered; mud_url: string; mudUrl: string; multi_connect: number; multiConnect: number; permissions: string[]; read_only: boolean; readOnly: boolean; secondaries: string[]; slave_type: string; slaveType: string; stable_id: string; stableId: string; timestamp: number; type: string; uuid: string; wait_device_timeout: number; waitDeviceTimeout: number; zone: string; // Constructors static ["new"](): SettingConnection; // Members add_permission(ptype: string, pitem: string, detail?: string | null): boolean; add_secondary(sec_uuid: string): boolean; get_auth_retries(): number; get_autoconnect(): boolean; get_autoconnect_priority(): number; get_autoconnect_retries(): number; get_autoconnect_slaves(): SettingConnectionAutoconnectSlaves; get_connection_type(): string; get_gateway_ping_timeout(): number; get_id(): string; get_interface_name(): string; get_lldp(): SettingConnectionLldp; get_llmnr(): SettingConnectionLlmnr; get_master(): string; get_mdns(): SettingConnectionMdns; get_metered(): Metered; get_mud_url(): string; get_multi_connect(): ConnectionMultiConnect; get_num_permissions(): number; get_num_secondaries(): number; get_permission(idx: number, out_ptype: string, out_pitem: string, out_detail: string): boolean; get_read_only(): boolean; get_secondary(idx: number): string; get_slave_type(): string; get_stable_id(): string; get_timestamp(): number; get_uuid(): string; get_wait_device_timeout(): number; get_zone(): string; is_slave_type(type: string): boolean; permissions_user_allowed(uname: string): boolean; remove_permission(idx: number): void; remove_permission_by_value(ptype: string, pitem: string, detail?: string | null): boolean; remove_secondary(idx: number): void; remove_secondary_by_value(sec_uuid: string): boolean; } export module SettingDcb { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; app_fcoe_flags: SettingDcbFlags; appFcoeFlags: SettingDcbFlags; app_fcoe_mode: string; appFcoeMode: string; app_fcoe_priority: number; appFcoePriority: number; app_fip_flags: SettingDcbFlags; appFipFlags: SettingDcbFlags; app_fip_priority: number; appFipPriority: number; app_iscsi_flags: SettingDcbFlags; appIscsiFlags: SettingDcbFlags; app_iscsi_priority: number; appIscsiPriority: number; priority_bandwidth: number[]; priorityBandwidth: number[]; priority_flow_control: boolean[]; priorityFlowControl: boolean[]; priority_flow_control_flags: SettingDcbFlags; priorityFlowControlFlags: SettingDcbFlags; priority_group_bandwidth: number[]; priorityGroupBandwidth: number[]; priority_group_flags: SettingDcbFlags; priorityGroupFlags: SettingDcbFlags; priority_group_id: number[]; priorityGroupId: number[]; priority_strict_bandwidth: boolean[]; priorityStrictBandwidth: boolean[]; priority_traffic_class: number[]; priorityTrafficClass: number[]; } } export class SettingDcb extends Setting { static $gtype: GObject.GType<SettingDcb>; constructor(properties?: Partial<SettingDcb.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingDcb.ConstructorProperties>, ...args: any[]): void; // Properties app_fcoe_flags: SettingDcbFlags; appFcoeFlags: SettingDcbFlags; app_fcoe_mode: string; appFcoeMode: string; app_fcoe_priority: number; appFcoePriority: number; app_fip_flags: SettingDcbFlags; appFipFlags: SettingDcbFlags; app_fip_priority: number; appFipPriority: number; app_iscsi_flags: SettingDcbFlags; appIscsiFlags: SettingDcbFlags; app_iscsi_priority: number; appIscsiPriority: number; priority_bandwidth: number[]; priorityBandwidth: number[]; priority_flow_control: boolean[]; priorityFlowControl: boolean[]; priority_flow_control_flags: SettingDcbFlags; priorityFlowControlFlags: SettingDcbFlags; priority_group_bandwidth: number[]; priorityGroupBandwidth: number[]; priority_group_flags: SettingDcbFlags; priorityGroupFlags: SettingDcbFlags; priority_group_id: number[]; priorityGroupId: number[]; priority_strict_bandwidth: boolean[]; priorityStrictBandwidth: boolean[]; priority_traffic_class: number[]; priorityTrafficClass: number[]; // Constructors static ["new"](): SettingDcb; // Members get_app_fcoe_flags(): SettingDcbFlags; get_app_fcoe_mode(): string; get_app_fcoe_priority(): number; get_app_fip_flags(): SettingDcbFlags; get_app_fip_priority(): number; get_app_iscsi_flags(): SettingDcbFlags; get_app_iscsi_priority(): number; get_priority_bandwidth(user_priority: number): number; get_priority_flow_control(user_priority: number): boolean; get_priority_flow_control_flags(): SettingDcbFlags; get_priority_group_bandwidth(group_id: number): number; get_priority_group_flags(): SettingDcbFlags; get_priority_group_id(user_priority: number): number; get_priority_strict_bandwidth(user_priority: number): boolean; get_priority_traffic_class(user_priority: number): number; set_priority_bandwidth(user_priority: number, bandwidth_percent: number): void; set_priority_flow_control(user_priority: number, enabled: boolean): void; set_priority_group_bandwidth(group_id: number, bandwidth_percent: number): void; set_priority_group_id(user_priority: number, group_id: number): void; set_priority_strict_bandwidth(user_priority: number, strict: boolean): void; set_priority_traffic_class(user_priority: number, traffic_class: number): void; } export module SettingDummy { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; } } export class SettingDummy extends Setting { static $gtype: GObject.GType<SettingDummy>; constructor(properties?: Partial<SettingDummy.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingDummy.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): SettingDummy; } export module SettingEthtool { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; } } export class SettingEthtool extends Setting { static $gtype: GObject.GType<SettingEthtool>; constructor(properties?: Partial<SettingEthtool.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingEthtool.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): SettingEthtool; // Members clear_features(): void; get_feature(optname: string): Ternary; get_optnames(): [string[], number | null]; set_feature(optname: string, value: Ternary): void; } export module SettingGeneric { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; } } export class SettingGeneric extends Setting { static $gtype: GObject.GType<SettingGeneric>; constructor(properties?: Partial<SettingGeneric.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingGeneric.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): SettingGeneric; } export module SettingGsm { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; apn: string; auto_config: boolean; autoConfig: boolean; device_id: string; deviceId: string; home_only: boolean; homeOnly: boolean; mtu: number; network_id: string; networkId: string; number: string; password: string; password_flags: SettingSecretFlags; passwordFlags: SettingSecretFlags; pin: string; pin_flags: SettingSecretFlags; pinFlags: SettingSecretFlags; sim_id: string; simId: string; sim_operator_id: string; simOperatorId: string; username: string; } } export class SettingGsm extends Setting { static $gtype: GObject.GType<SettingGsm>; constructor(properties?: Partial<SettingGsm.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingGsm.ConstructorProperties>, ...args: any[]): void; // Properties apn: string; auto_config: boolean; autoConfig: boolean; device_id: string; deviceId: string; home_only: boolean; homeOnly: boolean; mtu: number; network_id: string; networkId: string; number: string; password: string; password_flags: SettingSecretFlags; passwordFlags: SettingSecretFlags; pin: string; pin_flags: SettingSecretFlags; pinFlags: SettingSecretFlags; sim_id: string; simId: string; sim_operator_id: string; simOperatorId: string; username: string; // Constructors static ["new"](): SettingGsm; // Members get_apn(): string; get_auto_config(): boolean; get_device_id(): string; get_home_only(): boolean; get_mtu(): number; get_network_id(): string; get_number(): string; get_password(): string; get_password_flags(): SettingSecretFlags; get_pin(): string; get_pin_flags(): SettingSecretFlags; get_sim_id(): string; get_sim_operator_id(): string; get_username(): string; } export module SettingIP4Config { export interface ConstructorProperties extends SettingIPConfig.ConstructorProperties { [key: string]: any; dhcp_client_id: string; dhcpClientId: string; dhcp_fqdn: string; dhcpFqdn: string; dhcp_vendor_class_identifier: string; dhcpVendorClassIdentifier: string; } } export class SettingIP4Config extends SettingIPConfig { static $gtype: GObject.GType<SettingIP4Config>; constructor(properties?: Partial<SettingIP4Config.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingIP4Config.ConstructorProperties>, ...args: any[]): void; // Properties dhcp_client_id: string; dhcpClientId: string; dhcp_fqdn: string; dhcpFqdn: string; dhcp_vendor_class_identifier: string; dhcpVendorClassIdentifier: string; // Constructors static ["new"](): SettingIP4Config; // Members get_dhcp_client_id(): string; get_dhcp_fqdn(): string; get_dhcp_vendor_class_identifier(): string; } export module SettingIP6Config { export interface ConstructorProperties extends SettingIPConfig.ConstructorProperties { [key: string]: any; addr_gen_mode: number; addrGenMode: number; dhcp_duid: string; dhcpDuid: string; ip6_privacy: SettingIP6ConfigPrivacy; ip6Privacy: SettingIP6ConfigPrivacy; ra_timeout: number; raTimeout: number; token: string; } } export class SettingIP6Config extends SettingIPConfig { static $gtype: GObject.GType<SettingIP6Config>; constructor(properties?: Partial<SettingIP6Config.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingIP6Config.ConstructorProperties>, ...args: any[]): void; // Properties addr_gen_mode: number; addrGenMode: number; dhcp_duid: string; dhcpDuid: string; ip6_privacy: SettingIP6ConfigPrivacy; ip6Privacy: SettingIP6ConfigPrivacy; ra_timeout: number; raTimeout: number; token: string; // Constructors static ["new"](): SettingIP6Config; // Members get_addr_gen_mode(): SettingIP6ConfigAddrGenMode; get_dhcp_duid(): string; get_ip6_privacy(): SettingIP6ConfigPrivacy; get_ra_timeout(): number; get_token(): string; } export module SettingIPConfig { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; addresses: IPAddress[]; dad_timeout: number; dadTimeout: number; dhcp_hostname: string; dhcpHostname: string; dhcp_hostname_flags: number; dhcpHostnameFlags: number; dhcp_iaid: string; dhcpIaid: string; dhcp_reject_servers: string[]; dhcpRejectServers: string[]; dhcp_send_hostname: boolean; dhcpSendHostname: boolean; dhcp_timeout: number; dhcpTimeout: number; dns: string[]; dns_options: string[]; dnsOptions: string[]; dns_priority: number; dnsPriority: number; dns_search: string[]; dnsSearch: string[]; gateway: string; ignore_auto_dns: boolean; ignoreAutoDns: boolean; ignore_auto_routes: boolean; ignoreAutoRoutes: boolean; may_fail: boolean; mayFail: boolean; method: string; never_default: boolean; neverDefault: boolean; route_metric: number; routeMetric: number; route_table: number; routeTable: number; routes: IPRoute[]; } } export abstract class SettingIPConfig extends Setting { static $gtype: GObject.GType<SettingIPConfig>; constructor(properties?: Partial<SettingIPConfig.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingIPConfig.ConstructorProperties>, ...args: any[]): void; // Properties addresses: IPAddress[]; dad_timeout: number; dadTimeout: number; dhcp_hostname: string; dhcpHostname: string; dhcp_hostname_flags: number; dhcpHostnameFlags: number; dhcp_iaid: string; dhcpIaid: string; dhcp_reject_servers: string[]; dhcpRejectServers: string[]; dhcp_send_hostname: boolean; dhcpSendHostname: boolean; dhcp_timeout: number; dhcpTimeout: number; dns: string[]; dns_options: string[]; dnsOptions: string[]; dns_priority: number; dnsPriority: number; dns_search: string[]; dnsSearch: string[]; gateway: string; ignore_auto_dns: boolean; ignoreAutoDns: boolean; ignore_auto_routes: boolean; ignoreAutoRoutes: boolean; may_fail: boolean; mayFail: boolean; method: string; never_default: boolean; neverDefault: boolean; route_metric: number; routeMetric: number; route_table: number; routeTable: number; routes: IPRoute[]; // Members add_address(address: IPAddress): boolean; add_dhcp_reject_server(server: string): void; add_dns(dns: string): boolean; add_dns_option(dns_option: string): boolean; add_dns_search(dns_search: string): boolean; add_route(route: IPRoute): boolean; add_routing_rule(routing_rule: IPRoutingRule): void; clear_addresses(): void; clear_dhcp_reject_servers(): void; clear_dns(): void; clear_dns_options(is_set: boolean): void; clear_dns_searches(): void; clear_routes(): void; clear_routing_rules(): void; get_address(idx: number): IPAddress; get_dad_timeout(): number; get_dhcp_hostname(): string; get_dhcp_hostname_flags(): DhcpHostnameFlags; get_dhcp_iaid(): string; get_dhcp_reject_servers(): string[]; get_dhcp_send_hostname(): boolean; get_dhcp_timeout(): number; get_dns(idx: number): string; get_dns_option(idx: number): string; get_dns_priority(): number; get_dns_search(idx: number): string; get_gateway(): string; get_ignore_auto_dns(): boolean; get_ignore_auto_routes(): boolean; get_may_fail(): boolean; get_method(): string; get_never_default(): boolean; get_num_addresses(): number; get_num_dns(): number; get_num_dns_options(): number; get_num_dns_searches(): number; get_num_routes(): number; get_num_routing_rules(): number; get_route(idx: number): IPRoute; get_route_metric(): number; get_route_table(): number; get_routing_rule(idx: number): IPRoutingRule; has_dns_options(): boolean; remove_address(idx: number): void; remove_address_by_value(address: IPAddress): boolean; remove_dhcp_reject_server(idx: number): void; remove_dns(idx: number): void; remove_dns_by_value(dns: string): boolean; remove_dns_option(idx: number): void; remove_dns_option_by_value(dns_option: string): boolean; remove_dns_search(idx: number): void; remove_dns_search_by_value(dns_search: string): boolean; remove_route(idx: number): void; remove_route_by_value(route: IPRoute): boolean; remove_routing_rule(idx: number): void; } export module SettingIPTunnel { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; encapsulation_limit: number; encapsulationLimit: number; flags: number; flow_label: number; flowLabel: number; input_key: string; inputKey: string; local: string; mode: number; mtu: number; output_key: string; outputKey: string; path_mtu_discovery: boolean; pathMtuDiscovery: boolean; remote: string; tos: number; ttl: number; } } export class SettingIPTunnel extends Setting { static $gtype: GObject.GType<SettingIPTunnel>; constructor(properties?: Partial<SettingIPTunnel.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingIPTunnel.ConstructorProperties>, ...args: any[]): void; // Properties encapsulation_limit: number; encapsulationLimit: number; flags: number; flow_label: number; flowLabel: number; input_key: string; inputKey: string; local: string; mode: number; mtu: number; output_key: string; outputKey: string; path_mtu_discovery: boolean; pathMtuDiscovery: boolean; remote: string; tos: number; ttl: number; // Constructors static ["new"](): SettingIPTunnel; // Members get_encapsulation_limit(): number; get_flags(): IPTunnelFlags; get_flow_label(): number; get_input_key(): string; get_local(): string; get_mode(): IPTunnelMode; get_mtu(): number; get_output_key(): string; get_parent(): string; get_path_mtu_discovery(): boolean; get_remote(): string; get_tos(): number; get_ttl(): number; } export module SettingInfiniband { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; mac_address: string; macAddress: string; mtu: number; p_key: number; pKey: number; transport_mode: string; transportMode: string; } } export class SettingInfiniband extends Setting { static $gtype: GObject.GType<SettingInfiniband>; constructor(properties?: Partial<SettingInfiniband.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingInfiniband.ConstructorProperties>, ...args: any[]): void; // Properties mac_address: string; macAddress: string; mtu: number; p_key: number; pKey: number; transport_mode: string; transportMode: string; // Constructors static ["new"](): SettingInfiniband; // Members get_mac_address(): string; get_mtu(): number; get_p_key(): number; get_parent(): string; get_transport_mode(): string; get_virtual_interface_name(): string; } export module SettingMacsec { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; encrypt: boolean; mka_cak: string; mkaCak: string; mka_cak_flags: SettingSecretFlags; mkaCakFlags: SettingSecretFlags; mka_ckn: string; mkaCkn: string; mode: number; port: number; send_sci: boolean; sendSci: boolean; validation: number; } } export class SettingMacsec extends Setting { static $gtype: GObject.GType<SettingMacsec>; constructor(properties?: Partial<SettingMacsec.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingMacsec.ConstructorProperties>, ...args: any[]): void; // Properties encrypt: boolean; mka_cak: string; mkaCak: string; mka_cak_flags: SettingSecretFlags; mkaCakFlags: SettingSecretFlags; mka_ckn: string; mkaCkn: string; mode: number; port: number; send_sci: boolean; sendSci: boolean; validation: number; // Constructors static ["new"](): SettingMacsec; // Members get_encrypt(): boolean; get_mka_cak(): string; get_mka_cak_flags(): SettingSecretFlags; get_mka_ckn(): string; get_mode(): SettingMacsecMode; get_parent(): string; get_port(): number; get_send_sci(): boolean; get_validation(): SettingMacsecValidation; } export module SettingMacvlan { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; mode: number; promiscuous: boolean; tap: boolean; } } export class SettingMacvlan extends Setting { static $gtype: GObject.GType<SettingMacvlan>; constructor(properties?: Partial<SettingMacvlan.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingMacvlan.ConstructorProperties>, ...args: any[]): void; // Properties mode: number; promiscuous: boolean; tap: boolean; // Constructors static ["new"](): SettingMacvlan; // Members get_mode(): SettingMacvlanMode; get_parent(): string; get_promiscuous(): boolean; get_tap(): boolean; } export module SettingMatch { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; driver: string[]; interface_name: string[]; interfaceName: string[]; kernel_command_line: string[]; kernelCommandLine: string[]; path: string[]; } } export class SettingMatch extends Setting { static $gtype: GObject.GType<SettingMatch>; constructor(properties?: Partial<SettingMatch.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingMatch.ConstructorProperties>, ...args: any[]): void; // Properties driver: string[]; interface_name: string[]; interfaceName: string[]; kernel_command_line: string[]; kernelCommandLine: string[]; path: string[]; // Constructors static ["new"](): SettingMatch; // Members add_driver(driver: string): void; add_interface_name(interface_name: string): void; add_kernel_command_line(kernel_command_line: string): void; add_path(path: string): void; clear_drivers(): void; clear_interface_names(): void; clear_kernel_command_lines(): void; clear_paths(): void; get_driver(idx: number): string; get_drivers(): string[]; get_interface_name(idx: number): string; get_interface_names(): string[]; get_kernel_command_line(idx: number): string; get_kernel_command_lines(): string[]; get_num_drivers(): number; get_num_interface_names(): number; get_num_kernel_command_lines(): number; get_num_paths(): number; get_path(idx: number): string; get_paths(): string[]; remove_driver(idx: number): void; remove_driver_by_value(driver: string): boolean; remove_interface_name(idx: number): void; remove_interface_name_by_value(interface_name: string): boolean; remove_kernel_command_line(idx: number): void; remove_kernel_command_line_by_value(kernel_command_line: string): boolean; remove_path(idx: number): void; remove_path_by_value(path: string): boolean; } export module SettingOlpcMesh { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; channel: number; dhcp_anycast_address: string; dhcpAnycastAddress: string; ssid: GLib.Bytes; } } export class SettingOlpcMesh extends Setting { static $gtype: GObject.GType<SettingOlpcMesh>; constructor(properties?: Partial<SettingOlpcMesh.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingOlpcMesh.ConstructorProperties>, ...args: any[]): void; // Properties channel: number; dhcp_anycast_address: string; dhcpAnycastAddress: string; ssid: GLib.Bytes; // Constructors static ["new"](): SettingOlpcMesh; // Members get_channel(): number; get_dhcp_anycast_address(): string; get_ssid(): GLib.Bytes; } export module SettingOvsBridge { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; datapath_type: string; datapathType: string; fail_mode: string; failMode: string; mcast_snooping_enable: boolean; mcastSnoopingEnable: boolean; rstp_enable: boolean; rstpEnable: boolean; stp_enable: boolean; stpEnable: boolean; } } export class SettingOvsBridge extends Setting { static $gtype: GObject.GType<SettingOvsBridge>; constructor(properties?: Partial<SettingOvsBridge.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingOvsBridge.ConstructorProperties>, ...args: any[]): void; // Properties datapath_type: string; datapathType: string; fail_mode: string; failMode: string; mcast_snooping_enable: boolean; mcastSnoopingEnable: boolean; rstp_enable: boolean; rstpEnable: boolean; stp_enable: boolean; stpEnable: boolean; // Constructors static ["new"](): SettingOvsBridge; // Members get_datapath_type(): string; get_fail_mode(): string; get_mcast_snooping_enable(): boolean; get_rstp_enable(): boolean; get_stp_enable(): boolean; } export module SettingOvsDpdk { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; devargs: string; } } export class SettingOvsDpdk extends Setting { static $gtype: GObject.GType<SettingOvsDpdk>; constructor(properties?: Partial<SettingOvsDpdk.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingOvsDpdk.ConstructorProperties>, ...args: any[]): void; // Properties devargs: string; // Constructors static ["new"](): SettingOvsDpdk; // Members get_devargs(): string; } export module SettingOvsInterface { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; type: string; } } export class SettingOvsInterface extends Setting { static $gtype: GObject.GType<SettingOvsInterface>; constructor(properties?: Partial<SettingOvsInterface.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingOvsInterface.ConstructorProperties>, ...args: any[]): void; // Properties type: string; // Constructors static ["new"](): SettingOvsInterface; // Members get_interface_type(): string; } export module SettingOvsPatch { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; peer: string; } } export class SettingOvsPatch extends Setting { static $gtype: GObject.GType<SettingOvsPatch>; constructor(properties?: Partial<SettingOvsPatch.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingOvsPatch.ConstructorProperties>, ...args: any[]): void; // Properties peer: string; // Constructors static ["new"](): SettingOvsPatch; // Members get_peer(): string; } export module SettingOvsPort { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; bond_downdelay: number; bondDowndelay: number; bond_mode: string; bondMode: string; bond_updelay: number; bondUpdelay: number; lacp: string; tag: number; vlan_mode: string; vlanMode: string; } } export class SettingOvsPort extends Setting { static $gtype: GObject.GType<SettingOvsPort>; constructor(properties?: Partial<SettingOvsPort.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingOvsPort.ConstructorProperties>, ...args: any[]): void; // Properties bond_downdelay: number; bondDowndelay: number; bond_mode: string; bondMode: string; bond_updelay: number; bondUpdelay: number; lacp: string; tag: number; vlan_mode: string; vlanMode: string; // Constructors static ["new"](): SettingOvsPort; // Members get_bond_downdelay(): number; get_bond_mode(): string; get_bond_updelay(): number; get_lacp(): string; get_tag(): number; get_vlan_mode(): string; } export module SettingPpp { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; baud: number; crtscts: boolean; lcp_echo_failure: number; lcpEchoFailure: number; lcp_echo_interval: number; lcpEchoInterval: number; mppe_stateful: boolean; mppeStateful: boolean; mru: number; mtu: number; no_vj_comp: boolean; noVjComp: boolean; noauth: boolean; nobsdcomp: boolean; nodeflate: boolean; refuse_chap: boolean; refuseChap: boolean; refuse_eap: boolean; refuseEap: boolean; refuse_mschap: boolean; refuseMschap: boolean; refuse_mschapv2: boolean; refuseMschapv2: boolean; refuse_pap: boolean; refusePap: boolean; require_mppe: boolean; requireMppe: boolean; require_mppe_128: boolean; requireMppe128: boolean; } } export class SettingPpp extends Setting { static $gtype: GObject.GType<SettingPpp>; constructor(properties?: Partial<SettingPpp.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingPpp.ConstructorProperties>, ...args: any[]): void; // Properties baud: number; crtscts: boolean; lcp_echo_failure: number; lcpEchoFailure: number; lcp_echo_interval: number; lcpEchoInterval: number; mppe_stateful: boolean; mppeStateful: boolean; mru: number; mtu: number; no_vj_comp: boolean; noVjComp: boolean; noauth: boolean; nobsdcomp: boolean; nodeflate: boolean; refuse_chap: boolean; refuseChap: boolean; refuse_eap: boolean; refuseEap: boolean; refuse_mschap: boolean; refuseMschap: boolean; refuse_mschapv2: boolean; refuseMschapv2: boolean; refuse_pap: boolean; refusePap: boolean; require_mppe: boolean; requireMppe: boolean; require_mppe_128: boolean; requireMppe128: boolean; // Constructors static ["new"](): SettingPpp; // Members get_baud(): number; get_crtscts(): boolean; get_lcp_echo_failure(): number; get_lcp_echo_interval(): number; get_mppe_stateful(): boolean; get_mru(): number; get_mtu(): number; get_no_vj_comp(): boolean; get_noauth(): boolean; get_nobsdcomp(): boolean; get_nodeflate(): boolean; get_refuse_chap(): boolean; get_refuse_eap(): boolean; get_refuse_mschap(): boolean; get_refuse_mschapv2(): boolean; get_refuse_pap(): boolean; get_require_mppe(): boolean; get_require_mppe_128(): boolean; } export module SettingPppoe { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; password: string; password_flags: SettingSecretFlags; passwordFlags: SettingSecretFlags; service: string; username: string; } } export class SettingPppoe extends Setting { static $gtype: GObject.GType<SettingPppoe>; constructor(properties?: Partial<SettingPppoe.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingPppoe.ConstructorProperties>, ...args: any[]): void; // Properties password: string; password_flags: SettingSecretFlags; passwordFlags: SettingSecretFlags; service: string; username: string; // Constructors static ["new"](): SettingPppoe; // Members get_parent(): string; get_password(): string; get_password_flags(): SettingSecretFlags; get_service(): string; get_username(): string; } export module SettingProxy { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; browser_only: boolean; browserOnly: boolean; method: number; pac_script: string; pacScript: string; pac_url: string; pacUrl: string; } } export class SettingProxy extends Setting { static $gtype: GObject.GType<SettingProxy>; constructor(properties?: Partial<SettingProxy.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingProxy.ConstructorProperties>, ...args: any[]): void; // Properties browser_only: boolean; browserOnly: boolean; method: number; pac_script: string; pacScript: string; pac_url: string; pacUrl: string; // Constructors static ["new"](): SettingProxy; // Members get_browser_only(): boolean; get_method(): SettingProxyMethod; get_pac_script(): string; get_pac_url(): string; } export module SettingSerial { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; baud: number; bits: number; parity: SettingSerialParity; send_delay: number; sendDelay: number; stopbits: number; } } export class SettingSerial extends Setting { static $gtype: GObject.GType<SettingSerial>; constructor(properties?: Partial<SettingSerial.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingSerial.ConstructorProperties>, ...args: any[]): void; // Properties baud: number; bits: number; parity: SettingSerialParity; send_delay: number; sendDelay: number; stopbits: number; // Constructors static ["new"](): SettingSerial; // Members get_baud(): number; get_bits(): number; get_parity(): SettingSerialParity; get_send_delay(): number; get_stopbits(): number; } export module SettingSriov { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; autoprobe_drivers: Ternary; autoprobeDrivers: Ternary; total_vfs: number; totalVfs: number; vfs: SriovVF[]; } } export class SettingSriov extends Setting { static $gtype: GObject.GType<SettingSriov>; constructor(properties?: Partial<SettingSriov.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingSriov.ConstructorProperties>, ...args: any[]): void; // Properties autoprobe_drivers: Ternary; autoprobeDrivers: Ternary; total_vfs: number; totalVfs: number; vfs: SriovVF[]; // Constructors static ["new"](): SettingSriov; // Members add_vf(vf: SriovVF): void; clear_vfs(): void; get_autoprobe_drivers(): Ternary; get_num_vfs(): number; get_total_vfs(): number; get_vf(idx: number): SriovVF; remove_vf(idx: number): void; remove_vf_by_index(index: number): boolean; } export module SettingTCConfig { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; qdiscs: TCQdisc[]; tfilters: TCTfilter[]; } } export class SettingTCConfig extends Setting { static $gtype: GObject.GType<SettingTCConfig>; constructor(properties?: Partial<SettingTCConfig.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingTCConfig.ConstructorProperties>, ...args: any[]): void; // Properties qdiscs: TCQdisc[]; tfilters: TCTfilter[]; // Constructors static ["new"](): SettingTCConfig; // Members add_qdisc(qdisc: TCQdisc): boolean; add_tfilter(tfilter: TCTfilter): boolean; clear_qdiscs(): void; clear_tfilters(): void; get_num_qdiscs(): number; get_num_tfilters(): number; get_qdisc(idx: number): TCQdisc; get_tfilter(idx: number): TCTfilter; remove_qdisc(idx: number): void; remove_qdisc_by_value(qdisc: TCQdisc): boolean; remove_tfilter(idx: number): void; remove_tfilter_by_value(tfilter: TCTfilter): boolean; } export module SettingTeam { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; config: string; link_watchers: TeamLinkWatcher[]; linkWatchers: TeamLinkWatcher[]; mcast_rejoin_count: number; mcastRejoinCount: number; mcast_rejoin_interval: number; mcastRejoinInterval: number; notify_peers_count: number; notifyPeersCount: number; notify_peers_interval: number; notifyPeersInterval: number; runner: string; runner_active: boolean; runnerActive: boolean; runner_agg_select_policy: string; runnerAggSelectPolicy: string; runner_fast_rate: boolean; runnerFastRate: boolean; runner_hwaddr_policy: string; runnerHwaddrPolicy: string; runner_min_ports: number; runnerMinPorts: number; runner_sys_prio: number; runnerSysPrio: number; runner_tx_balancer: string; runnerTxBalancer: string; runner_tx_balancer_interval: number; runnerTxBalancerInterval: number; runner_tx_hash: string[]; runnerTxHash: string[]; } } export class SettingTeam extends Setting { static $gtype: GObject.GType<SettingTeam>; constructor(properties?: Partial<SettingTeam.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingTeam.ConstructorProperties>, ...args: any[]): void; // Properties config: string; link_watchers: TeamLinkWatcher[]; linkWatchers: TeamLinkWatcher[]; mcast_rejoin_count: number; mcastRejoinCount: number; mcast_rejoin_interval: number; mcastRejoinInterval: number; notify_peers_count: number; notifyPeersCount: number; notify_peers_interval: number; notifyPeersInterval: number; runner: string; runner_active: boolean; runnerActive: boolean; runner_agg_select_policy: string; runnerAggSelectPolicy: string; runner_fast_rate: boolean; runnerFastRate: boolean; runner_hwaddr_policy: string; runnerHwaddrPolicy: string; runner_min_ports: number; runnerMinPorts: number; runner_sys_prio: number; runnerSysPrio: number; runner_tx_balancer: string; runnerTxBalancer: string; runner_tx_balancer_interval: number; runnerTxBalancerInterval: number; runner_tx_hash: string[]; runnerTxHash: string[]; // Constructors static ["new"](): SettingTeam; // Members add_link_watcher(link_watcher: TeamLinkWatcher): boolean; add_runner_tx_hash(txhash: string): boolean; clear_link_watchers(): void; get_config(): string; get_link_watcher(idx: number): TeamLinkWatcher; get_mcast_rejoin_count(): number; get_mcast_rejoin_interval(): number; get_notify_peers_count(): number; get_notify_peers_interval(): number; get_num_link_watchers(): number; get_num_runner_tx_hash(): number; get_runner(): string; get_runner_active(): boolean; get_runner_agg_select_policy(): string; get_runner_fast_rate(): boolean; get_runner_hwaddr_policy(): string; get_runner_min_ports(): number; get_runner_sys_prio(): number; get_runner_tx_balancer(): string; get_runner_tx_balancer_interval(): number; get_runner_tx_hash(idx: number): string; remove_link_watcher(idx: number): void; remove_link_watcher_by_value(link_watcher: TeamLinkWatcher): boolean; remove_runner_tx_hash(idx: number): void; remove_runner_tx_hash_by_value(txhash: string): boolean; } export module SettingTeamPort { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; config: string; lacp_key: number; lacpKey: number; lacp_prio: number; lacpPrio: number; link_watchers: TeamLinkWatcher[]; linkWatchers: TeamLinkWatcher[]; prio: number; queue_id: number; queueId: number; sticky: boolean; } } export class SettingTeamPort extends Setting { static $gtype: GObject.GType<SettingTeamPort>; constructor(properties?: Partial<SettingTeamPort.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingTeamPort.ConstructorProperties>, ...args: any[]): void; // Properties config: string; lacp_key: number; lacpKey: number; lacp_prio: number; lacpPrio: number; link_watchers: TeamLinkWatcher[]; linkWatchers: TeamLinkWatcher[]; prio: number; queue_id: number; queueId: number; sticky: boolean; // Constructors static ["new"](): SettingTeamPort; // Members add_link_watcher(link_watcher: TeamLinkWatcher): boolean; clear_link_watchers(): void; get_config(): string; get_lacp_key(): number; get_lacp_prio(): number; get_link_watcher(idx: number): TeamLinkWatcher; get_num_link_watchers(): number; get_prio(): number; get_queue_id(): number; get_sticky(): boolean; remove_link_watcher(idx: number): void; remove_link_watcher_by_value(link_watcher: TeamLinkWatcher): boolean; } export module SettingTun { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; group: string; mode: number; multi_queue: boolean; multiQueue: boolean; owner: string; pi: boolean; vnet_hdr: boolean; vnetHdr: boolean; } } export class SettingTun extends Setting { static $gtype: GObject.GType<SettingTun>; constructor(properties?: Partial<SettingTun.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingTun.ConstructorProperties>, ...args: any[]): void; // Properties group: string; mode: number; multi_queue: boolean; multiQueue: boolean; owner: string; pi: boolean; vnet_hdr: boolean; vnetHdr: boolean; // Constructors static ["new"](): SettingTun; // Members get_group(): string; get_mode(): SettingTunMode; get_multi_queue(): boolean; get_owner(): string; get_pi(): boolean; get_vnet_hdr(): boolean; } export module SettingUser { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; data: GLib.HashTable<string, string>; } } export class SettingUser extends Setting { static $gtype: GObject.GType<SettingUser>; constructor(properties?: Partial<SettingUser.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingUser.ConstructorProperties>, ...args: any[]): void; // Properties data: GLib.HashTable<string, string>; // Constructors static ["new"](): SettingUser; // Members get_data(key: string): string; get_data(...args: never[]): never; get_keys(): string[]; set_data(key: string, val?: string | null): boolean; set_data(...args: never[]): never; static check_key(key: string): boolean; static check_val(val: string): boolean; } export module SettingVlan { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; egress_priority_map: string[]; egressPriorityMap: string[]; flags: VlanFlags; id: number; ingress_priority_map: string[]; ingressPriorityMap: string[]; } } export class SettingVlan extends Setting { static $gtype: GObject.GType<SettingVlan>; constructor(properties?: Partial<SettingVlan.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingVlan.ConstructorProperties>, ...args: any[]): void; // Properties egress_priority_map: string[]; egressPriorityMap: string[]; flags: VlanFlags; id: number; ingress_priority_map: string[]; ingressPriorityMap: string[]; // Constructors static ["new"](): SettingVlan; // Members add_priority(map: VlanPriorityMap, from: number, to: number): boolean; add_priority_str(map: VlanPriorityMap, str: string): boolean; clear_priorities(map: VlanPriorityMap): void; get_flags(): number; get_id(): number; get_num_priorities(map: VlanPriorityMap): number; get_parent(): string; get_priority(map: VlanPriorityMap, idx: number): [boolean, number | null, number | null]; remove_priority(map: VlanPriorityMap, idx: number): void; remove_priority_by_value(map: VlanPriorityMap, from: number, to: number): boolean; remove_priority_str_by_value(map: VlanPriorityMap, str: string): boolean; } export module SettingVpn { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; data: GLib.HashTable<string, string>; persistent: boolean; secrets: GLib.HashTable<string, string>; service_type: string; serviceType: string; timeout: number; user_name: string; userName: string; } } export class SettingVpn extends Setting { static $gtype: GObject.GType<SettingVpn>; constructor(properties?: Partial<SettingVpn.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingVpn.ConstructorProperties>, ...args: any[]): void; // Properties data: GLib.HashTable<string, string>; persistent: boolean; secrets: GLib.HashTable<string, string>; service_type: string; serviceType: string; timeout: number; user_name: string; userName: string; // Constructors static ["new"](): SettingVpn; // Members add_data_item(key: string, item?: string | null): void; add_secret(key: string, secret?: string | null): void; foreach_data_item(func: VpnIterFunc): void; foreach_secret(func: VpnIterFunc): void; get_data_item(key: string): string; get_data_keys(): string[]; get_num_data_items(): number; get_num_secrets(): number; get_persistent(): boolean; get_secret(key: string): string; get_secret_keys(): string[]; get_service_type(): string; get_timeout(): number; get_user_name(): string; remove_data_item(key: string): boolean; remove_secret(key: string): boolean; } export module SettingVrf { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; table: number; } } export class SettingVrf extends Setting { static $gtype: GObject.GType<SettingVrf>; constructor(properties?: Partial<SettingVrf.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingVrf.ConstructorProperties>, ...args: any[]): void; // Properties table: number; // Constructors static ["new"](): SettingVrf; // Members get_table(): number; } export module SettingVxlan { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; ageing: number; destination_port: number; destinationPort: number; id: number; l2_miss: boolean; l2Miss: boolean; l3_miss: boolean; l3Miss: boolean; learning: boolean; limit: number; local: string; proxy: boolean; remote: string; rsc: boolean; source_port_max: number; sourcePortMax: number; source_port_min: number; sourcePortMin: number; tos: number; ttl: number; } } export class SettingVxlan extends Setting { static $gtype: GObject.GType<SettingVxlan>; constructor(properties?: Partial<SettingVxlan.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingVxlan.ConstructorProperties>, ...args: any[]): void; // Properties ageing: number; destination_port: number; destinationPort: number; id: number; l2_miss: boolean; l2Miss: boolean; l3_miss: boolean; l3Miss: boolean; learning: boolean; limit: number; local: string; proxy: boolean; remote: string; rsc: boolean; source_port_max: number; sourcePortMax: number; source_port_min: number; sourcePortMin: number; tos: number; ttl: number; // Constructors static ["new"](): SettingVxlan; // Members get_ageing(): number; get_destination_port(): number; get_id(): number; get_l2_miss(): boolean; get_l3_miss(): boolean; get_learning(): boolean; get_limit(): number; get_local(): string; get_parent(): string; get_proxy(): boolean; get_remote(): string; get_rsc(): boolean; get_source_port_max(): number; get_source_port_min(): number; get_tos(): number; get_ttl(): number; } export module SettingWifiP2P { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; peer: string; wfd_ies: GLib.Bytes; wfdIes: GLib.Bytes; wps_method: number; wpsMethod: number; } } export class SettingWifiP2P extends Setting { static $gtype: GObject.GType<SettingWifiP2P>; constructor(properties?: Partial<SettingWifiP2P.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingWifiP2P.ConstructorProperties>, ...args: any[]): void; // Properties peer: string; wfd_ies: GLib.Bytes; wfdIes: GLib.Bytes; wps_method: number; wpsMethod: number; // Constructors static ["new"](): SettingWifiP2P; // Members get_peer(): string; get_wfd_ies(): GLib.Bytes; get_wps_method(): SettingWirelessSecurityWpsMethod; } export module SettingWimax { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; mac_address: string; macAddress: string; network_name: string; networkName: string; } } export class SettingWimax extends Setting { static $gtype: GObject.GType<SettingWimax>; constructor(properties?: Partial<SettingWimax.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingWimax.ConstructorProperties>, ...args: any[]): void; // Properties mac_address: string; macAddress: string; network_name: string; networkName: string; // Constructors static ["new"](): SettingWimax; // Members get_mac_address(): string; get_network_name(): string; } export module SettingWireGuard { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; fwmark: number; ip4_auto_default_route: Ternary; ip4AutoDefaultRoute: Ternary; ip6_auto_default_route: Ternary; ip6AutoDefaultRoute: Ternary; listen_port: number; listenPort: number; mtu: number; peer_routes: boolean; peerRoutes: boolean; private_key: string; privateKey: string; private_key_flags: SettingSecretFlags; privateKeyFlags: SettingSecretFlags; } } export class SettingWireGuard extends Setting { static $gtype: GObject.GType<SettingWireGuard>; constructor(properties?: Partial<SettingWireGuard.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingWireGuard.ConstructorProperties>, ...args: any[]): void; // Properties fwmark: number; ip4_auto_default_route: Ternary; ip4AutoDefaultRoute: Ternary; ip6_auto_default_route: Ternary; ip6AutoDefaultRoute: Ternary; listen_port: number; listenPort: number; mtu: number; peer_routes: boolean; peerRoutes: boolean; private_key: string; privateKey: string; private_key_flags: SettingSecretFlags; privateKeyFlags: SettingSecretFlags; // Constructors static ["new"](): SettingWireGuard; // Members append_peer(peer: WireGuardPeer): void; clear_peers(): number; get_fwmark(): number; get_ip4_auto_default_route(): Ternary; get_ip6_auto_default_route(): Ternary; get_listen_port(): number; get_mtu(): number; get_peer(idx: number): WireGuardPeer; get_peer_by_public_key(public_key: string): [WireGuardPeer, number | null]; get_peer_routes(): boolean; get_peers_len(): number; get_private_key(): string; get_private_key_flags(): SettingSecretFlags; remove_peer(idx: number): boolean; set_peer(peer: WireGuardPeer, idx: number): void; } export module SettingWired { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; auto_negotiate: boolean; autoNegotiate: boolean; cloned_mac_address: string; clonedMacAddress: string; duplex: string; generate_mac_address_mask: string; generateMacAddressMask: string; mac_address: string; macAddress: string; mac_address_blacklist: string[]; macAddressBlacklist: string[]; mtu: number; port: string; s390_nettype: string; s390Nettype: string; s390_options: GLib.HashTable<string, string>; s390Options: GLib.HashTable<string, string>; s390_subchannels: string[]; s390Subchannels: string[]; speed: number; wake_on_lan: number; wakeOnLan: number; wake_on_lan_password: string; wakeOnLanPassword: string; } } export class SettingWired extends Setting { static $gtype: GObject.GType<SettingWired>; constructor(properties?: Partial<SettingWired.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingWired.ConstructorProperties>, ...args: any[]): void; // Properties auto_negotiate: boolean; autoNegotiate: boolean; cloned_mac_address: string; clonedMacAddress: string; duplex: string; generate_mac_address_mask: string; generateMacAddressMask: string; mac_address: string; macAddress: string; mac_address_blacklist: string[]; macAddressBlacklist: string[]; mtu: number; port: string; s390_nettype: string; s390Nettype: string; s390_options: GLib.HashTable<string, string>; s390Options: GLib.HashTable<string, string>; s390_subchannels: string[]; s390Subchannels: string[]; speed: number; wake_on_lan: number; wakeOnLan: number; wake_on_lan_password: string; wakeOnLanPassword: string; // Constructors static ["new"](): SettingWired; // Members add_mac_blacklist_item(mac: string): boolean; add_s390_option(key: string, value: string): boolean; clear_mac_blacklist_items(): void; get_auto_negotiate(): boolean; get_cloned_mac_address(): string; get_duplex(): string; get_generate_mac_address_mask(): string; get_mac_address(): string; get_mac_address_blacklist(): string[]; get_mac_blacklist_item(idx: number): string; get_mtu(): number; get_num_mac_blacklist_items(): number; get_num_s390_options(): number; get_port(): string; get_s390_nettype(): string; get_s390_option(idx: number): [boolean, string, string]; get_s390_option_by_key(key: string): string; get_s390_subchannels(): string[]; get_speed(): number; get_valid_s390_options(): string[]; get_wake_on_lan(): SettingWiredWakeOnLan; get_wake_on_lan_password(): string; remove_mac_blacklist_item(idx: number): void; remove_mac_blacklist_item_by_value(mac: string): boolean; remove_s390_option(key: string): boolean; } export module SettingWireless { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; ap_isolation: Ternary; apIsolation: Ternary; band: string; bssid: string; channel: number; cloned_mac_address: string; clonedMacAddress: string; generate_mac_address_mask: string; generateMacAddressMask: string; hidden: boolean; mac_address: string; macAddress: string; mac_address_blacklist: string[]; macAddressBlacklist: string[]; mac_address_randomization: number; macAddressRandomization: number; mode: string; mtu: number; powersave: number; rate: number; seen_bssids: string[]; seenBssids: string[]; ssid: GLib.Bytes; tx_power: number; txPower: number; wake_on_wlan: number; wakeOnWlan: number; } } export class SettingWireless extends Setting { static $gtype: GObject.GType<SettingWireless>; constructor(properties?: Partial<SettingWireless.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingWireless.ConstructorProperties>, ...args: any[]): void; // Properties ap_isolation: Ternary; apIsolation: Ternary; band: string; bssid: string; channel: number; cloned_mac_address: string; clonedMacAddress: string; generate_mac_address_mask: string; generateMacAddressMask: string; hidden: boolean; mac_address: string; macAddress: string; mac_address_blacklist: string[]; macAddressBlacklist: string[]; mac_address_randomization: number; macAddressRandomization: number; mode: string; mtu: number; powersave: number; rate: number; seen_bssids: string[]; seenBssids: string[]; ssid: GLib.Bytes; tx_power: number; txPower: number; wake_on_wlan: number; wakeOnWlan: number; // Constructors static ["new"](): SettingWireless; // Members add_mac_blacklist_item(mac: string): boolean; add_seen_bssid(bssid: string): boolean; ap_security_compatible( s_wireless_sec: SettingWirelessSecurity, ap_flags: __80211ApFlags, ap_wpa: __80211ApSecurityFlags, ap_rsn: __80211ApSecurityFlags, ap_mode: __80211Mode ): boolean; clear_mac_blacklist_items(): void; get_ap_isolation(): Ternary; get_band(): string; get_bssid(): string; get_channel(): number; get_cloned_mac_address(): string; get_generate_mac_address_mask(): string; get_hidden(): boolean; get_mac_address(): string; get_mac_address_blacklist(): string[]; get_mac_address_randomization(): SettingMacRandomization; get_mac_blacklist_item(idx: number): string; get_mode(): string; get_mtu(): number; get_num_mac_blacklist_items(): number; get_num_seen_bssids(): number; get_powersave(): number; get_rate(): number; get_seen_bssid(i: number): string; get_ssid(): GLib.Bytes; get_tx_power(): number; get_wake_on_wlan(): SettingWirelessWakeOnWLan; remove_mac_blacklist_item(idx: number): void; remove_mac_blacklist_item_by_value(mac: string): boolean; } export module SettingWirelessSecurity { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; auth_alg: string; authAlg: string; fils: number; group: string[]; key_mgmt: string; keyMgmt: string; leap_password: string; leapPassword: string; leap_password_flags: SettingSecretFlags; leapPasswordFlags: SettingSecretFlags; leap_username: string; leapUsername: string; pairwise: string[]; pmf: number; proto: string[]; psk: string; psk_flags: SettingSecretFlags; pskFlags: SettingSecretFlags; wep_key_flags: SettingSecretFlags; wepKeyFlags: SettingSecretFlags; wep_key_type: WepKeyType; wepKeyType: WepKeyType; wep_key0: string; wepKey0: string; wep_key1: string; wepKey1: string; wep_key2: string; wepKey2: string; wep_key3: string; wepKey3: string; wep_tx_keyidx: number; wepTxKeyidx: number; wps_method: number; wpsMethod: number; } } export class SettingWirelessSecurity extends Setting { static $gtype: GObject.GType<SettingWirelessSecurity>; constructor(properties?: Partial<SettingWirelessSecurity.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingWirelessSecurity.ConstructorProperties>, ...args: any[]): void; // Properties auth_alg: string; authAlg: string; fils: number; group: string[]; key_mgmt: string; keyMgmt: string; leap_password: string; leapPassword: string; leap_password_flags: SettingSecretFlags; leapPasswordFlags: SettingSecretFlags; leap_username: string; leapUsername: string; pairwise: string[]; pmf: number; proto: string[]; psk: string; psk_flags: SettingSecretFlags; pskFlags: SettingSecretFlags; wep_key_flags: SettingSecretFlags; wepKeyFlags: SettingSecretFlags; wep_key_type: WepKeyType; wepKeyType: WepKeyType; wep_key0: string; wepKey0: string; wep_key1: string; wepKey1: string; wep_key2: string; wepKey2: string; wep_key3: string; wepKey3: string; wep_tx_keyidx: number; wepTxKeyidx: number; wps_method: number; wpsMethod: number; // Constructors static ["new"](): SettingWirelessSecurity; // Members add_group(group: string): boolean; add_pairwise(pairwise: string): boolean; add_proto(proto: string): boolean; clear_groups(): void; clear_pairwise(): void; clear_protos(): void; get_auth_alg(): string; get_fils(): SettingWirelessSecurityFils; get_group(i: number): string; get_key_mgmt(): string; get_leap_password(): string; get_leap_password_flags(): SettingSecretFlags; get_leap_username(): string; get_num_groups(): number; get_num_pairwise(): number; get_num_protos(): number; get_pairwise(i: number): string; get_pmf(): SettingWirelessSecurityPmf; get_proto(i: number): string; get_psk(): string; get_psk_flags(): SettingSecretFlags; get_wep_key(idx: number): string; get_wep_key_flags(): SettingSecretFlags; get_wep_key_type(): WepKeyType; get_wep_tx_keyidx(): number; get_wps_method(): SettingWirelessSecurityWpsMethod; remove_group(i: number): void; remove_group_by_value(group: string): boolean; remove_pairwise(i: number): void; remove_pairwise_by_value(pairwise: string): boolean; remove_proto(i: number): void; remove_proto_by_value(proto: string): boolean; set_wep_key(idx: number, key: string): void; } export module SettingWpan { export interface ConstructorProperties extends Setting.ConstructorProperties { [key: string]: any; channel: number; mac_address: string; macAddress: string; page: number; pan_id: number; panId: number; short_address: number; shortAddress: number; } } export class SettingWpan extends Setting { static $gtype: GObject.GType<SettingWpan>; constructor(properties?: Partial<SettingWpan.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SettingWpan.ConstructorProperties>, ...args: any[]): void; // Properties channel: number; mac_address: string; macAddress: string; page: number; pan_id: number; panId: number; short_address: number; shortAddress: number; // Constructors static ["new"](): SettingWpan; // Members get_channel(): number; get_mac_address(): string; get_page(): number; get_pan_id(): number; get_short_address(): number; } export module SimpleConnection { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class SimpleConnection extends GObject.Object implements Connection { static $gtype: GObject.GType<SimpleConnection>; constructor(properties?: Partial<SimpleConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<SimpleConnection.ConstructorProperties>, ...args: any[]): void; // Members static new(): Connection; static new_clone(connection: Connection): Connection; static new_from_dbus(dict: GLib.Variant): Connection; // Implemented Members add_setting(setting: Setting): void; clear_secrets(): void; clear_secrets_with_flags(func?: SettingClearSecretsWithFlagsFn | null): void; clear_settings(): void; compare(b: Connection, flags: SettingCompareFlags): boolean; diff(b: Connection, flags: SettingCompareFlags, out_settings: GLib.HashTable<string, GLib.HashTable>): boolean; dump(): void; for_each_setting_value(func: SettingValueIterFn): void; get_connection_type(): string; get_id(): string; get_interface_name(): string; get_path(): string; get_setting(setting_type: GObject.GType): Setting; get_setting_802_1x(): Setting8021x; get_setting_adsl(): SettingAdsl; get_setting_bluetooth(): SettingBluetooth; get_setting_bond(): SettingBond; get_setting_bridge(): SettingBridge; get_setting_bridge_port(): SettingBridgePort; get_setting_by_name(name: string): Setting; get_setting_cdma(): SettingCdma; get_setting_connection(): SettingConnection; get_setting_dcb(): SettingDcb; get_setting_dummy(): SettingDummy; get_setting_generic(): SettingGeneric; get_setting_gsm(): SettingGsm; get_setting_infiniband(): SettingInfiniband; get_setting_ip4_config(): SettingIP4Config; get_setting_ip6_config(): SettingIP6Config; get_setting_ip_tunnel(): SettingIPTunnel; get_setting_macsec(): SettingMacsec; get_setting_macvlan(): SettingMacvlan; get_setting_olpc_mesh(): SettingOlpcMesh; get_setting_ovs_bridge(): SettingOvsBridge; get_setting_ovs_interface(): SettingOvsInterface; get_setting_ovs_patch(): SettingOvsPatch; get_setting_ovs_port(): SettingOvsPort; get_setting_ppp(): SettingPpp; get_setting_pppoe(): SettingPppoe; get_setting_proxy(): SettingProxy; get_setting_serial(): SettingSerial; get_setting_tc_config(): SettingTCConfig; get_setting_team(): SettingTeam; get_setting_team_port(): SettingTeamPort; get_setting_tun(): SettingTun; get_setting_vlan(): SettingVlan; get_setting_vpn(): SettingVpn; get_setting_vxlan(): SettingVxlan; get_setting_wimax(): SettingWimax; get_setting_wired(): SettingWired; get_setting_wireless(): SettingWireless; get_setting_wireless_security(): SettingWirelessSecurity; get_settings(): Setting[]; get_uuid(): string; get_virtual_device_description(): string; is_type(type: string): boolean; is_virtual(): boolean; need_secrets(): [string, string[] | null]; normalize(parameters?: GLib.HashTable<string, any> | null): [boolean, boolean | null]; remove_setting(setting_type: GObject.GType): void; replace_settings(new_settings: GLib.Variant): boolean; replace_settings_from_connection(new_connection: Connection): void; set_path(path: string): void; to_dbus(flags: ConnectionSerializationFlags): GLib.Variant; update_secrets(setting_name: string, secrets: GLib.Variant): boolean; verify(): boolean; verify_secrets(): boolean; vfunc_changed(): void; vfunc_secrets_cleared(): void; vfunc_secrets_updated(setting: string): void; } export module VpnConnection { export interface ConstructorProperties extends ActiveConnection.ConstructorProperties { [key: string]: any; banner: string; vpn_state: VpnConnectionState; vpnState: VpnConnectionState; } } export class VpnConnection extends ActiveConnection { static $gtype: GObject.GType<VpnConnection>; constructor(properties?: Partial<VpnConnection.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<VpnConnection.ConstructorProperties>, ...args: any[]): void; // Properties banner: string; vpn_state: VpnConnectionState; vpnState: VpnConnectionState; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "vpn-state-changed", callback: (_source: this, object: number, p0: number) => void): number; connect_after(signal: "vpn-state-changed", callback: (_source: this, object: number, p0: number) => void): number; emit(signal: "vpn-state-changed", object: number, p0: number): void; // Members get_banner(): string; get_vpn_state(): VpnConnectionState; } export module VpnPluginInfo { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; filename: string; keyfile: GLib.KeyFile; name: string; } } export class VpnPluginInfo extends GObject.Object implements Gio.Initable { static $gtype: GObject.GType<VpnPluginInfo>; constructor(properties?: Partial<VpnPluginInfo.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<VpnPluginInfo.ConstructorProperties>, ...args: any[]): void; // Properties filename: string; keyfile: GLib.KeyFile; name: string; // Constructors static new_from_file(filename: string): VpnPluginInfo; static new_search_file(name?: string | null, service?: string | null): VpnPluginInfo; static new_with_data(filename: string, keyfile: GLib.KeyFile): VpnPluginInfo; // Members get_aliases(): string[]; get_auth_dialog(): string; get_editor_plugin(): VpnEditorPlugin; get_filename(): string; get_name(): string; get_plugin(): string; get_program(): string; get_service(): string; load_editor_plugin(): VpnEditorPlugin; lookup_property(group: string, key: string): string; set_editor_plugin(plugin?: VpnEditorPlugin | null): void; supports_hints(): boolean; supports_multiple(): boolean; static list_add(list: VpnPluginInfo[], plugin_info: VpnPluginInfo): boolean; static list_find_by_filename(list: VpnPluginInfo[], filename: string): VpnPluginInfo; static list_find_by_name(list: VpnPluginInfo[], name: string): VpnPluginInfo; static list_find_by_service(list: VpnPluginInfo[], service: string): VpnPluginInfo; static list_find_service_type(list: VpnPluginInfo[], name: string): string; static list_get_service_types(list: VpnPluginInfo[], only_existing: boolean, with_abbreviations: boolean): string[]; static list_load(): VpnPluginInfo[]; static list_remove(list: VpnPluginInfo[], plugin_info: VpnPluginInfo): boolean; static validate_filename(filename: string): boolean; // Implemented Members init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module VpnPluginOld { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; service_name: string; serviceName: string; state: VpnServiceState; } } export abstract class VpnPluginOld extends GObject.Object implements Gio.Initable { static $gtype: GObject.GType<VpnPluginOld>; constructor(properties?: Partial<VpnPluginOld.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<VpnPluginOld.ConstructorProperties>, ...args: any[]): void; // Properties service_name: string; serviceName: string; state: VpnServiceState; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "config", callback: (_source: this, object: GLib.Variant) => void): number; connect_after(signal: "config", callback: (_source: this, object: GLib.Variant) => void): number; emit(signal: "config", object: GLib.Variant): void; connect(signal: "failure", callback: (_source: this, object: number) => void): number; connect_after(signal: "failure", callback: (_source: this, object: number) => void): number; emit(signal: "failure", object: number): void; connect(signal: "ip4-config", callback: (_source: this, object: GLib.Variant) => void): number; connect_after(signal: "ip4-config", callback: (_source: this, object: GLib.Variant) => void): number; emit(signal: "ip4-config", object: GLib.Variant): void; connect(signal: "ip6-config", callback: (_source: this, object: GLib.Variant) => void): number; connect_after(signal: "ip6-config", callback: (_source: this, object: GLib.Variant) => void): number; emit(signal: "ip6-config", object: GLib.Variant): void; connect(signal: "login-banner", callback: (_source: this, object: string) => void): number; connect_after(signal: "login-banner", callback: (_source: this, object: string) => void): number; emit(signal: "login-banner", object: string): void; connect(signal: "quit", callback: (_source: this) => void): number; connect_after(signal: "quit", callback: (_source: this) => void): number; emit(signal: "quit"): void; connect(signal: "secrets-required", callback: (_source: this, object: string, p0: string[]) => void): number; connect_after(signal: "secrets-required", callback: (_source: this, object: string, p0: string[]) => void): number; emit(signal: "secrets-required", object: string, p0: string[]): void; connect(signal: "state-changed", callback: (_source: this, object: number) => void): number; connect_after(signal: "state-changed", callback: (_source: this, object: number) => void): number; emit(signal: "state-changed", object: number): void; // Members disconnect(): boolean; disconnect(...args: never[]): never; failure(reason: VpnPluginFailure): void; get_connection(): Gio.DBusConnection; get_state(): VpnServiceState; secrets_required(message: string, hints: string): void; set_config(config: GLib.Variant): void; set_ip4_config(ip4_config: GLib.Variant): void; set_ip6_config(ip6_config: GLib.Variant): void; set_login_banner(banner: string): void; set_state(state: VpnServiceState): void; vfunc_config(config: GLib.Variant): void; vfunc_connect(connection: Connection): boolean; vfunc_connect_interactive(connection: Connection, details: GLib.Variant): boolean; vfunc_disconnect(): boolean; vfunc_failure(reason: VpnPluginFailure): void; vfunc_ip4_config(ip4_config: GLib.Variant): void; vfunc_ip6_config(config: GLib.Variant): void; vfunc_login_banner(banner: string): void; vfunc_need_secrets(connection: Connection, setting_name: string): boolean; vfunc_new_secrets(connection: Connection): boolean; vfunc_quit(): void; vfunc_state_changed(state: VpnServiceState): void; static get_secret_flags(data: GLib.HashTable<any, any>, secret_name: string): [boolean, SettingSecretFlags]; static read_vpn_details(fd: number): [boolean, GLib.HashTable<any, any>, GLib.HashTable<any, any>]; // Implemented Members init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module VpnServicePlugin { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; service_name: string; serviceName: string; state: VpnServiceState; watch_peer: boolean; watchPeer: boolean; } } export abstract class VpnServicePlugin extends GObject.Object implements Gio.Initable { static $gtype: GObject.GType<VpnServicePlugin>; constructor(properties?: Partial<VpnServicePlugin.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<VpnServicePlugin.ConstructorProperties>, ...args: any[]): void; // Properties service_name: string; serviceName: string; state: VpnServiceState; watch_peer: boolean; watchPeer: boolean; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "config", callback: (_source: this, object: GLib.Variant) => void): number; connect_after(signal: "config", callback: (_source: this, object: GLib.Variant) => void): number; emit(signal: "config", object: GLib.Variant): void; connect(signal: "failure", callback: (_source: this, object: number) => void): number; connect_after(signal: "failure", callback: (_source: this, object: number) => void): number; emit(signal: "failure", object: number): void; connect(signal: "ip4-config", callback: (_source: this, object: GLib.Variant) => void): number; connect_after(signal: "ip4-config", callback: (_source: this, object: GLib.Variant) => void): number; emit(signal: "ip4-config", object: GLib.Variant): void; connect(signal: "ip6-config", callback: (_source: this, object: GLib.Variant) => void): number; connect_after(signal: "ip6-config", callback: (_source: this, object: GLib.Variant) => void): number; emit(signal: "ip6-config", object: GLib.Variant): void; connect(signal: "login-banner", callback: (_source: this, object: string) => void): number; connect_after(signal: "login-banner", callback: (_source: this, object: string) => void): number; emit(signal: "login-banner", object: string): void; connect(signal: "quit", callback: (_source: this) => void): number; connect_after(signal: "quit", callback: (_source: this) => void): number; emit(signal: "quit"): void; connect(signal: "secrets-required", callback: (_source: this, object: string, p0: string[]) => void): number; connect_after(signal: "secrets-required", callback: (_source: this, object: string, p0: string[]) => void): number; emit(signal: "secrets-required", object: string, p0: string[]): void; connect(signal: "state-changed", callback: (_source: this, object: number) => void): number; connect_after(signal: "state-changed", callback: (_source: this, object: number) => void): number; emit(signal: "state-changed", object: number): void; // Members disconnect(): boolean; disconnect(...args: never[]): never; failure(reason: VpnPluginFailure): void; get_connection(): Gio.DBusConnection; secrets_required(message: string, hints: string): void; set_config(config: GLib.Variant): void; set_ip4_config(ip4_config: GLib.Variant): void; set_ip6_config(ip6_config: GLib.Variant): void; set_login_banner(banner: string): void; shutdown(): void; vfunc_config(config: GLib.Variant): void; vfunc_connect(connection: Connection): boolean; vfunc_connect_interactive(connection: Connection, details: GLib.Variant): boolean; vfunc_disconnect(): boolean; vfunc_failure(reason: VpnPluginFailure): void; vfunc_ip4_config(ip4_config: GLib.Variant): void; vfunc_ip6_config(config: GLib.Variant): void; vfunc_login_banner(banner: string): void; vfunc_need_secrets(connection: Connection, setting_name: string): boolean; vfunc_new_secrets(connection: Connection): boolean; vfunc_quit(): void; vfunc_state_changed(state: VpnServiceState): void; static get_secret_flags(data: GLib.HashTable<any, any>, secret_name: string): [boolean, SettingSecretFlags]; static read_vpn_details(fd: number): [boolean, GLib.HashTable<any, any>, GLib.HashTable<any, any>]; // Implemented Members init(cancellable?: Gio.Cancellable | null): boolean; vfunc_init(cancellable?: Gio.Cancellable | null): boolean; } export module WifiP2PPeer { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; flags: __80211ApFlags; hw_address: string; hwAddress: string; last_seen: number; lastSeen: number; manufacturer: string; model: string; model_number: string; modelNumber: string; name: string; serial: string; strength: number; wfd_ies: GLib.Bytes; wfdIes: GLib.Bytes; } } export class WifiP2PPeer extends Object { static $gtype: GObject.GType<WifiP2PPeer>; constructor(properties?: Partial<WifiP2PPeer.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<WifiP2PPeer.ConstructorProperties>, ...args: any[]): void; // Properties flags: __80211ApFlags; hw_address: string; hwAddress: string; last_seen: number; lastSeen: number; manufacturer: string; model: string; model_number: string; modelNumber: string; name: string; serial: string; strength: number; wfd_ies: GLib.Bytes; wfdIes: GLib.Bytes; // Members connection_valid(connection: Connection): boolean; filter_connections(connections: Connection[]): Connection[]; get_flags(): __80211ApFlags; get_hw_address(): string; get_last_seen(): number; get_manufacturer(): string; get_model(): string; get_model_number(): string; get_name(): string; get_serial(): string; get_strength(): number; get_wfd_ies(): GLib.Bytes; } export module WimaxNsp { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; name: string; network_type: WimaxNspNetworkType; networkType: WimaxNspNetworkType; signal_quality: number; signalQuality: number; } } export class WimaxNsp extends Object { static $gtype: GObject.GType<WimaxNsp>; constructor(properties?: Partial<WimaxNsp.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<WimaxNsp.ConstructorProperties>, ...args: any[]): void; // Properties name: string; network_type: WimaxNspNetworkType; networkType: WimaxNspNetworkType; signal_quality: number; signalQuality: number; // Members connection_valid(connection: Connection): boolean; filter_connections(connections: Connection[]): Connection[]; get_name(): string; get_network_type(): WimaxNspNetworkType; get_signal_quality(): number; } export class BridgeVlan { static $gtype: GObject.GType<BridgeVlan>; constructor(vid_start: number, vid_end: number); constructor(copy: BridgeVlan); // Constructors static ["new"](vid_start: number, vid_end: number): BridgeVlan; // Members cmp(b: BridgeVlan): number; get_vid_range(): [boolean, number, number]; is_pvid(): boolean; is_sealed(): boolean; is_untagged(): boolean; new_clone(): BridgeVlan; ref(): BridgeVlan; seal(): void; set_pvid(value: boolean): void; set_untagged(value: boolean): void; to_str(): string; unref(): void; static from_str(str: string): BridgeVlan; } export class DnsEntry { static $gtype: GObject.GType<DnsEntry>; constructor(copy: DnsEntry); // Members get_domains(): string[]; get_interface(): string; get_nameservers(): string[]; get_priority(): number; get_vpn(): boolean; unref(): void; } export class IPAddress { static $gtype: GObject.GType<IPAddress>; constructor(family: number, addr: string, prefix: number); constructor(copy: IPAddress); // Constructors static ["new"](family: number, addr: string, prefix: number): IPAddress; static new_binary(family: number, addr: any | null, prefix: number): IPAddress; // Members cmp_full(b: IPAddress, cmp_flags: IPAddressCmpFlags): number; dup(): IPAddress; equal(other: IPAddress): boolean; get_address(): string; get_attribute(name: string): GLib.Variant; get_attribute_names(): string[]; get_family(): number; get_prefix(): number; ref(): void; set_address(addr: string): void; set_attribute(name: string, value?: GLib.Variant | null): void; set_prefix(prefix: number): void; unref(): void; } export class IPRoute { static $gtype: GObject.GType<IPRoute>; constructor(family: number, dest: string, prefix: number, next_hop: string | null, metric: number); constructor(copy: IPRoute); // Constructors static ["new"](family: number, dest: string, prefix: number, next_hop: string | null, metric: number): IPRoute; static new_binary(family: number, dest: any | null, prefix: number, next_hop: any | null, metric: number): IPRoute; // Members dup(): IPRoute; equal(other: IPRoute): boolean; equal_full(other: IPRoute, cmp_flags: number): boolean; get_attribute(name: string): GLib.Variant; get_attribute_names(): string[]; get_dest(): string; get_family(): number; get_metric(): number; get_next_hop(): string; get_prefix(): number; ref(): void; set_attribute(name: string, value?: GLib.Variant | null): void; set_dest(dest: string): void; set_metric(metric: number): void; set_next_hop(next_hop?: string | null): void; set_prefix(prefix: number): void; unref(): void; static attribute_validate(name: string, value: GLib.Variant, family: number): [boolean, boolean]; static get_variant_attribute_spec(): VariantAttributeSpec; } export class IPRoutingRule { static $gtype: GObject.GType<IPRoutingRule>; constructor(addr_family: number); constructor(copy: IPRoutingRule); // Constructors static ["new"](addr_family: number): IPRoutingRule; // Members cmp(other?: IPRoutingRule | null): number; get_action(): number; get_addr_family(): number; get_destination_port_end(): number; get_destination_port_start(): number; get_from(): string; get_from_len(): number; get_fwmark(): number; get_fwmask(): number; get_iifname(): string; get_invert(): boolean; get_ipproto(): number; get_oifname(): string; get_priority(): number; get_source_port_end(): number; get_source_port_start(): number; get_suppress_prefixlength(): number; get_table(): number; get_to(): string; get_to_len(): number; get_tos(): number; is_sealed(): boolean; new_clone(): IPRoutingRule; ref(): IPRoutingRule; seal(): void; set_action(action: number): void; set_destination_port(start: number, end: number): void; set_from(from: string | null, len: number): void; set_fwmark(fwmark: number, fwmask: number): void; set_iifname(iifname?: string | null): void; set_invert(invert: boolean): void; set_ipproto(ipproto: number): void; set_oifname(oifname?: string | null): void; set_priority(priority: number): void; set_source_port(start: number, end: number): void; set_suppress_prefixlength(suppress_prefixlength: number): void; set_table(table: number): void; set_to(to: string | null, len: number): void; set_tos(tos: number): void; to_string(to_string_flags: IPRoutingRuleAsStringFlags, extra_args?: GLib.HashTable<any, any> | null): string; unref(): void; validate(): boolean; static from_string( str: string, to_string_flags: IPRoutingRuleAsStringFlags, extra_args?: GLib.HashTable<any, any> | null ): IPRoutingRule; } export class LldpNeighbor { static $gtype: GObject.GType<LldpNeighbor>; constructor(); constructor(copy: LldpNeighbor); // Constructors static ["new"](): LldpNeighbor; // Members get_attr_names(): string[]; get_attr_string_value(name: string): [boolean, string | null]; get_attr_type(name: string): GLib.VariantType; get_attr_uint_value(name: string): [boolean, number | null]; get_attr_value(name: string): GLib.Variant; ref(): void; unref(): void; } export class SriovVF { static $gtype: GObject.GType<SriovVF>; constructor(index: number); constructor(copy: SriovVF); // Constructors static ["new"](index: number): SriovVF; // Members add_vlan(vlan_id: number): boolean; dup(): SriovVF; equal(other: SriovVF): boolean; get_attribute(name: string): GLib.Variant; get_attribute_names(): string[]; get_index(): number; get_vlan_ids(): number[]; get_vlan_protocol(vlan_id: number): SriovVFVlanProtocol; get_vlan_qos(vlan_id: number): number; ref(): void; remove_vlan(vlan_id: number): boolean; set_attribute(name: string, value?: GLib.Variant | null): void; set_vlan_protocol(vlan_id: number, protocol: SriovVFVlanProtocol): void; set_vlan_qos(vlan_id: number, qos: number): void; unref(): void; static attribute_validate(name: string, value: GLib.Variant): [boolean, boolean]; } export class TCAction { static $gtype: GObject.GType<TCAction>; constructor(kind: string); constructor(copy: TCAction); // Constructors static ["new"](kind: string): TCAction; // Members dup(): TCAction; equal(other: TCAction): boolean; get_attribute(name: string): GLib.Variant; get_attribute_names(): string[]; get_kind(): string; ref(): void; set_attribute(name: string, value?: GLib.Variant | null): void; unref(): void; } export class TCQdisc { static $gtype: GObject.GType<TCQdisc>; constructor(kind: string, parent: number); constructor(copy: TCQdisc); // Constructors static ["new"](kind: string, parent: number): TCQdisc; // Members dup(): TCQdisc; equal(other: TCQdisc): boolean; get_attribute(name: string): GLib.Variant; get_attribute_names(): string[]; get_handle(): number; get_kind(): string; get_parent(): number; ref(): void; set_attribute(name: string, value?: GLib.Variant | null): void; set_handle(handle: number): void; unref(): void; } export class TCTfilter { static $gtype: GObject.GType<TCTfilter>; constructor(kind: string, parent: number); constructor(copy: TCTfilter); // Constructors static ["new"](kind: string, parent: number): TCTfilter; // Members dup(): TCTfilter; equal(other: TCTfilter): boolean; get_action(): TCAction; get_handle(): number; get_kind(): string; get_parent(): number; ref(): void; set_action(action: TCAction): void; set_handle(handle: number): void; unref(): void; } export class TeamLinkWatcher { static $gtype: GObject.GType<TeamLinkWatcher>; constructor( init_wait: number, interval: number, missed_max: number, target_host: string, source_host: string, flags: TeamLinkWatcherArpPingFlags ); constructor(copy: TeamLinkWatcher); // Constructors static new_arp_ping( init_wait: number, interval: number, missed_max: number, target_host: string, source_host: string, flags: TeamLinkWatcherArpPingFlags ): TeamLinkWatcher; static new_arp_ping2( init_wait: number, interval: number, missed_max: number, vlanid: number, target_host: string, source_host: string, flags: TeamLinkWatcherArpPingFlags ): TeamLinkWatcher; static new_ethtool(delay_up: number, delay_down: number): TeamLinkWatcher; static new_nsna_ping(init_wait: number, interval: number, missed_max: number, target_host: string): TeamLinkWatcher; // Members dup(): TeamLinkWatcher; equal(other: TeamLinkWatcher): boolean; get_delay_down(): number; get_delay_up(): number; get_flags(): TeamLinkWatcherArpPingFlags; get_init_wait(): number; get_interval(): number; get_missed_max(): number; get_name(): string; get_source_host(): string; get_target_host(): string; get_vlanid(): number; ref(): void; unref(): void; } export class VariantAttributeSpec { static $gtype: GObject.GType<VariantAttributeSpec>; constructor(copy: VariantAttributeSpec); } export class VpnEditorPluginVT { static $gtype: GObject.GType<VpnEditorPluginVT>; constructor(copy: VpnEditorPluginVT); } export class WireGuardPeer { static $gtype: GObject.GType<WireGuardPeer>; constructor(); constructor(copy: WireGuardPeer); // Constructors static ["new"](): WireGuardPeer; // Members append_allowed_ip(allowed_ip: string, accept_invalid: boolean): boolean; clear_allowed_ips(): void; cmp(b: WireGuardPeer | null, compare_flags: SettingCompareFlags): number; get_allowed_ip(idx: number, out_is_valid?: boolean | null): string; get_allowed_ips_len(): number; get_endpoint(): string; get_persistent_keepalive(): number; get_preshared_key(): string; get_preshared_key_flags(): SettingSecretFlags; get_public_key(): string; is_sealed(): boolean; is_valid(check_non_secrets: boolean, check_secrets: boolean): boolean; new_clone(with_secrets: boolean): WireGuardPeer; ref(): WireGuardPeer; remove_allowed_ip(idx: number): boolean; seal(): void; set_endpoint(endpoint: string, allow_invalid: boolean): boolean; set_persistent_keepalive(persistent_keepalive: number): void; set_preshared_key(preshared_key: string | null, accept_invalid: boolean): boolean; set_preshared_key_flags(preshared_key_flags: SettingSecretFlags): void; set_public_key(public_key: string | null, accept_invalid: boolean): boolean; unref(): void; } export interface ConnectionNamespace { $gtype: GObject.GType<Connection>; prototype: ConnectionPrototype; } export type Connection = ConnectionPrototype; export interface ConnectionPrototype extends GObject.Object { // Members add_setting(setting: Setting): void; clear_secrets(): void; clear_secrets_with_flags(func?: SettingClearSecretsWithFlagsFn | null): void; clear_settings(): void; compare(b: Connection, flags: SettingCompareFlags): boolean; diff(b: Connection, flags: SettingCompareFlags, out_settings: GLib.HashTable<string, GLib.HashTable>): boolean; dump(): void; for_each_setting_value(func: SettingValueIterFn): void; get_connection_type(): string; get_id(): string; get_interface_name(): string; get_path(): string; get_setting(setting_type: GObject.GType): Setting; get_setting_802_1x(): Setting8021x; get_setting_adsl(): SettingAdsl; get_setting_bluetooth(): SettingBluetooth; get_setting_bond(): SettingBond; get_setting_bridge(): SettingBridge; get_setting_bridge_port(): SettingBridgePort; get_setting_by_name(name: string): Setting; get_setting_cdma(): SettingCdma; get_setting_connection(): SettingConnection; get_setting_dcb(): SettingDcb; get_setting_dummy(): SettingDummy; get_setting_generic(): SettingGeneric; get_setting_gsm(): SettingGsm; get_setting_infiniband(): SettingInfiniband; get_setting_ip4_config(): SettingIP4Config; get_setting_ip6_config(): SettingIP6Config; get_setting_ip_tunnel(): SettingIPTunnel; get_setting_macsec(): SettingMacsec; get_setting_macvlan(): SettingMacvlan; get_setting_olpc_mesh(): SettingOlpcMesh; get_setting_ovs_bridge(): SettingOvsBridge; get_setting_ovs_interface(): SettingOvsInterface; get_setting_ovs_patch(): SettingOvsPatch; get_setting_ovs_port(): SettingOvsPort; get_setting_ppp(): SettingPpp; get_setting_pppoe(): SettingPppoe; get_setting_proxy(): SettingProxy; get_setting_serial(): SettingSerial; get_setting_tc_config(): SettingTCConfig; get_setting_team(): SettingTeam; get_setting_team_port(): SettingTeamPort; get_setting_tun(): SettingTun; get_setting_vlan(): SettingVlan; get_setting_vpn(): SettingVpn; get_setting_vxlan(): SettingVxlan; get_setting_wimax(): SettingWimax; get_setting_wired(): SettingWired; get_setting_wireless(): SettingWireless; get_setting_wireless_security(): SettingWirelessSecurity; get_settings(): Setting[]; get_uuid(): string; get_virtual_device_description(): string; is_type(type: string): boolean; is_virtual(): boolean; need_secrets(): [string, string[] | null]; normalize(parameters?: GLib.HashTable<string, any> | null): [boolean, boolean | null]; remove_setting(setting_type: GObject.GType): void; replace_settings(new_settings: GLib.Variant): boolean; replace_settings_from_connection(new_connection: Connection): void; set_path(path: string): void; to_dbus(flags: ConnectionSerializationFlags): GLib.Variant; update_secrets(setting_name: string, secrets: GLib.Variant): boolean; verify(): boolean; verify_secrets(): boolean; vfunc_changed(): void; vfunc_secrets_cleared(): void; vfunc_secrets_updated(setting: string): void; } export const Connection: ConnectionNamespace; export interface VpnEditorNamespace { $gtype: GObject.GType<VpnEditor>; prototype: VpnEditorPrototype; } export type VpnEditor = VpnEditorPrototype; export interface VpnEditorPrototype extends GObject.Object { // Members get_widget<T = GObject.Object>(): T; update_connection(connection: Connection): boolean; vfunc_changed(): void; vfunc_get_widget<T = GObject.Object>(): T; vfunc_update_connection(connection: Connection): boolean; } export const VpnEditor: VpnEditorNamespace; export interface VpnEditorPluginNamespace { $gtype: GObject.GType<VpnEditorPlugin>; prototype: VpnEditorPluginPrototype; load(plugin_name: string, check_service: string): VpnEditorPlugin; load_from_file( plugin_name: string, check_service: string, check_owner: number, check_file: UtilsCheckFilePredicate ): VpnEditorPlugin; } export type VpnEditorPlugin = VpnEditorPluginPrototype; export interface VpnEditorPluginPrototype extends GObject.Object { // Properties description: string; name: string; service: string; // Members ["export"](path: string, connection: Connection): boolean; get_capabilities(): VpnEditorPluginCapability; get_editor(connection: Connection): VpnEditor; get_plugin_info(): VpnPluginInfo; get_suggested_filename(connection: Connection): string; get_vt(vt_size: number): [number, VpnEditorPluginVT]; ["import"](path: string): Connection; set_plugin_info(plugin_info?: VpnPluginInfo | null): void; vfunc_export_to_file(path: string, connection: Connection): boolean; vfunc_get_capabilities(): VpnEditorPluginCapability; vfunc_get_editor(connection: Connection): VpnEditor; vfunc_get_suggested_filename(connection: Connection): string; vfunc_get_vt(out_vt_size: number): VpnEditorPluginVT; vfunc_notify_plugin_info_set(plugin_info: VpnPluginInfo): void; } export const VpnEditorPlugin: VpnEditorPluginNamespace;
the_stack
namespace fgui { export class LineInfo { public width: number = 0; public height: number = 0; public textHeight: number = 0; public text: string; public y: number = 0; private static pool: LineInfo[] = []; public static get(): LineInfo { if (LineInfo.pool.length) { let ret: LineInfo = LineInfo.pool.pop(); ret.width = 0; ret.height = 0; ret.textHeight = 0; ret.text = null; ret.y = 0; return ret; } else return new LineInfo(); } public static recycle(value: LineInfo): void { LineInfo.pool.push(value); } public static recycleMany(value: LineInfo[]): void { if(value && value.length) { value.forEach(v => { LineInfo.pool.push(v); }, this); } value.length = 0; } } export class GTextField extends GObject implements IColorGear, IColorableTitle { protected $textField: UITextField; protected $btContainer: UIContainer; protected $bitmapFont: BitmapFont; protected $lines: LineInfo[]; protected $bitmapPool: PIXI.Sprite[]; protected $font: string; //could be either fontFamily or an URI pointed to a bitmap font resource protected $style: PIXI.TextStyle; protected $verticalAlign: VertAlignType = VertAlignType.Top; protected $offset: PIXI.Point = new PIXI.Point(); protected $color: number; protected $singleLine:boolean = true; protected $text: string = ""; protected $fontProperties:PIXI.FontMetrics; protected $autoSize: AutoSizeType; protected $widthAutoSize: boolean; protected $heightAutoSize: boolean; protected $requireRender: boolean; protected $updatingSize: boolean; protected $sizeDirty: boolean; protected $textWidth: number = 0; protected $textHeight: number = 0; public static GUTTER_X: number = 2; public static GUTTER_Y: number = 2; public constructor() { super(); this.$style = new PIXI.TextStyle({ fontSize: 12, fontFamily: UIConfig.defaultFont, align: AlignType.Left, leading: 3, fill: 0 }); this.$verticalAlign = VertAlignType.Top; this.$text = ""; this.$autoSize = AutoSizeType.Both; this.$widthAutoSize = true; this.$heightAutoSize = true; this.$bitmapPool = []; this.touchable = false; //base GTextField has no interaction } protected createDisplayObject(): void { this.$textField = new UITextField(this); this.setDisplayObject(this.$textField); } private switchBitmapMode(val: boolean): void { if (val && this.displayObject == this.$textField) { if (this.$btContainer == null) this.$btContainer = new UIContainer(this); this.switchDisplayObject(this.$btContainer); } else if (!val && this.displayObject == this.$btContainer) this.switchDisplayObject(this.$textField); } public dispose(): void { GTimer.inst.remove(this.$render, this); this.$bitmapFont = null; this.$bitmapPool.length = 0; this.$bitmapPool = null; this.$style = null; super.dispose(); } public set text(value:string) { this.setText(value); } protected setText(value: string):void { if(value == null) value = ""; if (this.$text == value) return; this.$text = value; this.updateGear(GearType.Text); if (this.parent && this.parent.$inProgressBuilding) this.renderNow(); else this.render(); } public get text(): string { return this.getText(); } protected getText():string { return this.$text; } public get color(): number { return this.getColor(); } protected getColor():number { return this.$color; } protected setColor(value:number):void { if (this.$color != value) { this.$color = value; this.updateGear(GearType.Color); this.$style.fill = this.$color; this.render(); } } public set color(value: number) { this.setColor(value); } public get titleColor(): number { return this.color; } public set titleColor(value: number) { this.color = value; } public get lineHeight():number { if(this.$style.lineHeight > 0) return this.$style.lineHeight; if(!this.$fontProperties) return (+this.$style.fontSize) + this.$style.strokeThickness; //rough value return this.$fontProperties.fontSize + this.$style.strokeThickness + this.$style.leading; } public set lineHeight(lh:number) { this.$style.lineHeight = lh; } public get font(): string { return this.$font || UIConfig.defaultFont; } public set font(value: string) { if (this.$font != value) { this.$font = value; if (this.$font && utils.StringUtil.startsWith(this.$font, "ui://")) this.$bitmapFont = UIPackage.getBitmapFontByURL(this.$font); else this.$style.fontFamily = this.$font || UIConfig.defaultFont; this.render(); } } public get fontSize(): number { return +this.$style.fontSize; } public set fontSize(value: number) { if (value <= 0) return; if (this.$style.fontSize != value) { this.$style.fontSize = value; this.render(); } } public get align(): AlignType { return this.$style.align as AlignType; } public set align(value: AlignType) { if (this.$style.align != value) { this.$style.align = value; this.render(); } } public get verticalAlign(): VertAlignType { return this.$verticalAlign; } public set verticalAlign(value: VertAlignType) { if (this.$verticalAlign != value) { this.$verticalAlign = value; if(!this.$inProgressBuilding) this.layoutAlign(); } } public get leading(): number { return this.$style.leading; } public set leading(value: number) { if (this.$style.leading != value) { this.$style.leading = value; this.render(); } } public get letterSpacing(): number { return this.$style.letterSpacing; } public set letterSpacing(value: number) { if (this.$style.letterSpacing != value) { this.$style.letterSpacing = value; this.render(); } } public get underline(): boolean { return false; //TODO: not supported yet } public set underline(value: boolean) { //TODO: not supported yet } public get bold(): boolean { return this.$style.fontWeight == "bold"; } public set bold(value: boolean) { let v: string = value === true ? "bold" : "normal"; if (this.$style.fontWeight != v) { this.$style.fontWeight = v; this.render(); } } public get weight(): string { return this.$style.fontWeight; } public set weight(v: string) { if (this.$style.fontWeight != v) { this.$style.fontWeight = v; this.render(); } } public get variant(): string { return this.$style.fontVariant; } public set variant(v: string) { if (this.$style.fontVariant != v) { this.$style.fontVariant = v; this.render(); } } public get italic(): boolean { return this.$style.fontStyle == "italic"; } public set italic(value: boolean) { let v: string = value === true ? "italic" : "normal"; if (this.$style.fontStyle != v) { this.$style.fontStyle = v; this.render(); } } public get multipleLine(): boolean { return !this.$singleLine; } public set multipleLine(value: boolean) { value = !value; if(this.$singleLine != value) { this.$singleLine = value; this.render(); } } public get stroke(): number { return +this.$style.strokeThickness; } public set stroke(value: number) { if (this.$style.strokeThickness != value) this.$style.strokeThickness = value; } public get strokeColor(): number | string { return this.$style.stroke; } public set strokeColor(value: number | string) { if (this.$style.stroke != value) this.$style.stroke = value; } public set autoSize(value: AutoSizeType) { if (this.$autoSize != value) { this.$autoSize = value; this.$widthAutoSize = (value == AutoSizeType.Both || value == AutoSizeType.Shrink); this.$heightAutoSize = (value == AutoSizeType.Both || value == AutoSizeType.Height); this.render(); } } public get autoSize(): AutoSizeType { return this.$autoSize; } public get textWidth(): number { if (this.$requireRender) this.renderNow(); return this.$textWidth; } public get textHeight(): number { if (this.$requireRender) this.renderNow(); return this.$textHeight; } public ensureSizeCorrect(): void { if (this.$sizeDirty && this.$requireRender) this.renderNow(); } protected render(): void { if (!this.$requireRender) { this.$requireRender = true; GTimer.inst.callLater(this.$render, this); } if (!this.$sizeDirty && (this.$widthAutoSize || this.$heightAutoSize)) { this.$sizeDirty = true; this.emit(DisplayObjectEvent.SIZE_DELAY_CHANGE, this); } } private applyStyle():void { this.$textField.style.stroke = this.$style.stroke; this.$textField.style.strokeThickness = this.$style.strokeThickness; this.$textField.style.fontStyle = this.$style.fontStyle; this.$textField.style.fontVariant = this.$style.fontVariant; this.$textField.style.fontWeight = this.$style.fontWeight; this.$textField.style.letterSpacing = this.$style.letterSpacing; this.$textField.style.align = this.$style.align; this.$textField.style.fontSize = this.$style.fontSize; this.$textField.style.fontFamily = this.$style.fontFamily; this.$textField.style.fill = this.$style.fill; this.$textField.style.leading = this.$style.leading; } private $render(): void { if (this.$requireRender) this.renderNow(); } protected renderNow(updateBounds: boolean = true): void { this.$requireRender = false; this.$sizeDirty = false; if (this.$bitmapFont != null) { this.renderWithBitmapFont(updateBounds); return; } this.switchBitmapMode(false); this.applyStyle(); this.$textField.$updateMinHeight(); let wordWrap = !this.$widthAutoSize && this.multipleLine; this.$textField.width = this.$textField.style.wordWrapWidth = (wordWrap || this.autoSize == AutoSizeType.None) ? Math.ceil(this.width) : 10000; this.$textField.style.wordWrap = wordWrap; this.$textField.style.breakWords = wordWrap; this.$textField.text = this.$text; //trigger t.dirty = true this.$fontProperties = PIXI.TextMetrics.measureFont(this.$style.toFontString()); this.$textWidth = Math.ceil(this.$textField.textWidth); if (this.$textWidth > 0) this.$textWidth += GTextField.GUTTER_X * 2; //margin gap this.$textHeight = Math.ceil(this.$textField.textHeight); if (this.$textHeight > 0) this.$textHeight += GTextField.GUTTER_Y * 2; //margin gap let w = this.width, h = this.height; if(this.autoSize == AutoSizeType.Shrink) this.shrinkTextField(); else { this.$textField.scale.set(1, 1); if (this.$widthAutoSize) { w = this.$textWidth; this.$textField.width = w; } if (this.$heightAutoSize) { h = this.$textHeight; if (this.$textField.height != this.$textHeight) this.$textField.height = this.$textHeight; } else { h = this.height; if (this.$textHeight > h) this.$textHeight = h; } } if (updateBounds) { this.$updatingSize = true; this.setSize(w, h); this.$updatingSize = false; } this.layoutAlign(); } private renderWithBitmapFont(updateBounds: boolean): void { this.switchBitmapMode(true); this.$btContainer.children.forEach((c, i) => { this.$bitmapPool.push(this.$btContainer.getChildAt(i) as PIXI.Sprite); }, this); this.$btContainer.removeChildren(); if (!this.$lines) this.$lines = []; else LineInfo.recycleMany(this.$lines); let letterSpacing: number = this.letterSpacing; let lineSpacing: number = this.leading - 1; let rectWidth: number = this.width - GTextField.GUTTER_X * 2; let lineWidth: number = 0, lineHeight: number = 0, lineTextHeight: number = 0; let glyphWidth: number = 0, glyphHeight: number = 0; let wordChars: number = 0, wordStart: number = 0, wordEnd: number = 0; let lastLineHeight: number = 0; let lineBuffer: string = ""; let lineY: number = GTextField.GUTTER_Y; let line: LineInfo; let wordWrap: boolean = !this.$widthAutoSize && this.multipleLine; let fontScale: number = this.$bitmapFont.resizable ? this.fontSize / this.$bitmapFont.size : 1; let glyph: BMGlyph; this.$textWidth = 0; this.$textHeight = 0; let textLength: number = this.text.length; for (let offset: number = 0; offset < textLength; ++offset) { let ch: string = this.$text.charAt(offset); let cc: number = ch.charCodeAt(offset); if (ch == "\n") { lineBuffer += ch; line = LineInfo.get(); line.width = lineWidth; if (lineTextHeight == 0) { if (lastLineHeight == 0) lastLineHeight = Math.ceil(this.fontSize * fontScale); if (lineHeight == 0) lineHeight = lastLineHeight; lineTextHeight = lineHeight; } line.height = lineHeight; lastLineHeight = lineHeight; line.textHeight = lineTextHeight; line.text = lineBuffer; line.y = lineY; lineY += (line.height + lineSpacing); if (line.width > this.$textWidth) this.$textWidth = line.width; this.$lines.push(line); lineBuffer = ""; lineWidth = 0; lineHeight = 0; lineTextHeight = 0; wordChars = 0; wordStart = 0; wordEnd = 0; continue; } if (cc > 256 || cc <= 32) { if (wordChars > 0) wordEnd = lineWidth; wordChars = 0; } else { if (wordChars == 0) wordStart = lineWidth; wordChars++; } if (ch == " ") { glyphWidth = Math.ceil(this.fontSize / 2); glyphHeight = Math.ceil(this.fontSize); } else { glyph = this.$bitmapFont.glyphs[ch]; if (glyph) { glyphWidth = Math.ceil(glyph.advance * fontScale); glyphHeight = Math.ceil(glyph.lineHeight * fontScale); } else if (ch == " ") { glyphWidth = Math.ceil(this.$bitmapFont.size * fontScale / 2); glyphHeight = Math.ceil(this.$bitmapFont.size * fontScale); } else { glyphWidth = 0; glyphHeight = 0; } } if (glyphHeight > lineTextHeight) lineTextHeight = glyphHeight; if (glyphHeight > lineHeight) lineHeight = glyphHeight; if (lineWidth != 0) lineWidth += letterSpacing; lineWidth += glyphWidth; if (!wordWrap || lineWidth <= rectWidth) { lineBuffer += ch; } else { line = LineInfo.get(); line.height = lineHeight; line.textHeight = lineTextHeight; if (lineBuffer.length == 0) {//the line cannt fit even a char line.text = ch; } else if (wordChars > 0 && wordEnd > 0) {//if word had broken, move it to new line lineBuffer += ch; let len: number = lineBuffer.length - wordChars; line.text = utils.StringUtil.trimRight(lineBuffer.substr(0, len)); line.width = wordEnd; lineBuffer = lineBuffer.substr(len + 1); lineWidth -= wordStart; } else { line.text = lineBuffer; line.width = lineWidth - (glyphWidth + letterSpacing); lineBuffer = ch; lineWidth = glyphWidth; lineHeight = glyphHeight; lineTextHeight = glyphHeight; } line.y = lineY; lineY += (line.height + lineSpacing); if (line.width > this.$textWidth) this.$textWidth = line.width; wordChars = 0; wordStart = 0; wordEnd = 0; this.$lines.push(line); } } if (lineBuffer.length > 0 || this.$lines.length > 0 && utils.StringUtil.endsWith(this.$lines[this.$lines.length - 1].text, "\n")) { line = LineInfo.get(); line.width = lineWidth; if (lineHeight == 0) lineHeight = lastLineHeight; if (lineTextHeight == 0) lineTextHeight = lineHeight; line.height = lineHeight; line.textHeight = lineTextHeight; line.text = lineBuffer; line.y = lineY; if (line.width > this.$textWidth) this.$textWidth = line.width; this.$lines.push(line); } if (this.$textWidth > 0) this.$textWidth += GTextField.GUTTER_X * 2; let count: number = this.$lines.length; if (count == 0) { this.$textHeight = 0; } else { line = this.$lines[this.$lines.length - 1]; this.$textHeight = line.y + line.height + GTextField.GUTTER_Y; } let w: number, h: number = 0; if (this.$widthAutoSize) { if (this.$textWidth == 0) w = 0; else w = this.$textWidth; } else w = this.width; if (this.$heightAutoSize) { if (this.$textHeight == 0) h = 0; else h = this.$textHeight; } else h = this.height; if (updateBounds) { this.$updatingSize = true; this.setSize(w, h); this.$updatingSize = false; } if (w == 0 || h == 0) return; rectWidth = this.width - GTextField.GUTTER_X * 2; this.$lines.forEach(line => { let charX = GTextField.GUTTER_X; let lineIndent: number = 0; let charIndent: number = 0; if (this.align == AlignType.Center) lineIndent = (rectWidth - line.width) / 2; else if (this.align == AlignType.Right) lineIndent = rectWidth - line.width; else lineIndent = 0; textLength = line.text.length; for (let j: number = 0; j < textLength; j++) { let ch = line.text.charAt(j); glyph = this.$bitmapFont.glyphs[ch]; if (glyph != null) { charIndent = (line.height + line.textHeight) / 2 - Math.ceil(glyph.lineHeight * fontScale); let bm: PIXI.Sprite; if (this.$bitmapPool.length) bm = this.$bitmapPool.pop(); else bm = new PIXI.Sprite(); bm.x = charX + lineIndent + Math.ceil(glyph.offsetX * fontScale); bm.y = line.y + charIndent + Math.ceil(glyph.offsetY * fontScale); bm.texture = glyph.texture; bm.scale.set(fontScale, fontScale); bm.tint = this.$bitmapFont.colorable === true ? this.$color : 0xFFFFFF; this.$btContainer.addChild(bm); charX += letterSpacing + Math.ceil(glyph.advance * fontScale); } else if (ch == " ") { charX += letterSpacing + Math.ceil(this.$bitmapFont.size * fontScale / 2); } else { charX += letterSpacing; } } }); } public localToGlobal(ax: number = 0, ay: number = 0, resultPoint?: PIXI.Point): PIXI.Point { ax -= this.$offset.x; ay -= this.$offset.y; return super.localToGlobal(ax, ay, resultPoint); } public globalToLocal(ax: number = 0, ay: number = 0, resultPoint?: PIXI.Point): PIXI.Point { let r = super.globalToLocal(ax, ay, resultPoint); r.x -= this.$offset.x; r.y -= this.$offset.y; return r; } protected handleSizeChanged(): void { if (this.$updatingSize) return; if (this.$bitmapFont != null) { if (!this.$widthAutoSize) this.render(); } else { if (this.$inProgressBuilding) { this.$textField.width = this.width; this.$textField.height = this.height; } else { if(this.$autoSize == AutoSizeType.Shrink) this.shrinkTextField(); else { if (!this.$widthAutoSize) { if (!this.$heightAutoSize) { this.$textField.width = this.width; this.$textField.height = this.height; } else this.$textField.width = this.width; } } } } this.layoutAlign(); } protected shrinkTextField():void { let fitScale = Math.min(1, this.width / this.$textWidth); this.$textField.scale.set(fitScale, fitScale); } protected layoutAlign(): void { let tw = this.$textWidth, th = this.$textHeight; if(this.autoSize == AutoSizeType.Shrink) { tw *= this.displayObject.scale.x; th *= this.displayObject.scale.y; } if (this.$verticalAlign == VertAlignType.Top || th == 0) this.$offset.y = GTextField.GUTTER_Y; else { let dh: number = Math.max(0, this.height - th); if (this.$verticalAlign == VertAlignType.Middle) this.$offset.y = dh * .5; else if(this.$verticalAlign == VertAlignType.Bottom) this.$offset.y = dh; } let xPos = 0; switch(this.$style.align) { case "center": xPos = (this.width - tw) * .5; break; case "right": xPos = this.width - tw; break; } this.$offset.x = xPos; this.updatePosition(); } private updatePosition():void { this.displayObject.position.set(Math.floor(this.x + this.$offset.x), Math.floor(this.y + this.$offset.y)); } protected handleXYChanged(): void { super.handleXYChanged(); if (this.$displayObject) this.updatePosition(); } public setupBeforeAdd(xml: utils.XmlNode): void { super.setupBeforeAdd(xml); let str: string = xml.attributes.font; if(str) this.font = str; str = xml.attributes.vAlign; if (str) this.verticalAlign = ParseVertAlignType(str); str = xml.attributes.leading; if (str) this.$style.leading = parseInt(str); str = xml.attributes.letterSpacing; if (str) this.$style.letterSpacing = parseInt(str); str = xml.attributes.fontSize; if (str) this.$style.fontSize = parseInt(str); str = xml.attributes.color; if (str) this.color = utils.StringUtil.convertFromHtmlColor(str); str = xml.attributes.align; if (str) this.align = ParseAlignType(str); str = xml.attributes.autoSize; if (str) { this.autoSize = ParseAutoSizeType(str); this.$widthAutoSize = (this.$autoSize == AutoSizeType.Both || this.$autoSize == AutoSizeType.Shrink); this.$heightAutoSize = (this.$autoSize == AutoSizeType.Both || this.$autoSize == AutoSizeType.Height); } this.underline = xml.attributes.underline == "true"; this.italic = xml.attributes.italic == "true"; this.bold = xml.attributes.bold == "true"; this.multipleLine = xml.attributes.singleLine != "true"; str = xml.attributes.strokeColor; if (str) { this.strokeColor = utils.StringUtil.convertFromHtmlColor(str); str = xml.attributes.strokeSize; if (str) this.stroke = parseInt(str) + 1; else this.stroke = 2; } } public setupAfterAdd(xml: utils.XmlNode): void { super.setupAfterAdd(xml); let str: string = xml.attributes.text; if (str != null && str.length > 0) this.text = str; this.$sizeDirty = false; } } }
the_stack
import { EventEmitter, Injectable, NgZone } from '@angular/core'; import { Subject } from 'rxjs'; import { PlatformUtil } from '../../core/utils'; import { FilteringExpressionsTree } from '../../data-operations/filtering-expressions-tree'; import { IgxGridBaseDirective } from '../grid/public_api'; export interface GridSelectionRange { rowStart: number; rowEnd: number; columnStart: string | number; columnEnd: string | number; } export interface ISelectionNode { row: number; column: number; layout?: IMultiRowLayoutNode; isSummaryRow?: boolean; } export interface IMultiRowLayoutNode { rowStart: number; colStart: number; rowEnd: number; colEnd: number; columnVisibleIndex: number; } interface ISelectionKeyboardState { node: null | ISelectionNode; shift: boolean; range: GridSelectionRange; active: boolean; } interface ISelectionPointerState extends ISelectionKeyboardState { ctrl: boolean; primaryButton: boolean; } interface IColumnSelectionState { field: null | string; range: string[]; } type SelectionState = ISelectionKeyboardState | ISelectionPointerState; @Injectable() export class IgxGridSelectionService { public grid; public dragMode = false; public activeElement: ISelectionNode | null; public keyboardState = {} as ISelectionKeyboardState; public pointerState = {} as ISelectionPointerState; public columnsState = {} as IColumnSelectionState; public selection = new Map<number, Set<number>>(); public temp = new Map<number, Set<number>>(); public rowSelection: Set<any> = new Set<any>(); public indeterminateRows: Set<any> = new Set<any>(); public columnSelection: Set<string> = new Set<string>(); /** * @hidden @internal */ public selectedRowsChange = new Subject(); /** * Toggled when a pointerdown event is triggered inside the grid body (cells). * When `false` the drag select behavior is disabled. */ private pointerEventInGridBody = false; private allRowsSelected: boolean; private _ranges: Set<string> = new Set<string>(); private _selectionRange: Range; /** * Returns the current selected ranges in the grid from both * keyboard and pointer interactions */ public get ranges(): GridSelectionRange[] { // The last action was keyboard + shift selection -> add it this.addKeyboardRange(); const ranges = Array.from(this._ranges).map(range => JSON.parse(range)); // No ranges but we have a focused cell -> add it if (!ranges.length && this.activeElement && this.grid.isCellSelectable) { ranges.push(this.generateRange(this.activeElement)); } return ranges; } public get primaryButton(): boolean { return this.pointerState.primaryButton; } public set primaryButton(value: boolean) { this.pointerState.primaryButton = value; } constructor(private zone: NgZone, protected platform: PlatformUtil) { this.initPointerState(); this.initKeyboardState(); this.initColumnsState(); } /** * Resets the keyboard state */ public initKeyboardState(): void { this.keyboardState.node = null; this.keyboardState.shift = false; this.keyboardState.range = null; this.keyboardState.active = false; } /** * Resets the pointer state */ public initPointerState(): void { this.pointerState.node = null; this.pointerState.ctrl = false; this.pointerState.shift = false; this.pointerState.range = null; this.pointerState.primaryButton = true; } /** * Resets the columns state */ public initColumnsState(): void { this.columnsState.field = null; this.columnsState.range = []; } /** * Adds a single node. * Single clicks | Ctrl + single clicks on cells is the usual case. */ public add(node: ISelectionNode, addToRange = true): void { if (this.selection.has(node.row)) { this.selection.get(node.row).add(node.column); } else { this.selection.set(node.row, new Set<number>()).get(node.row).add(node.column); } if (addToRange) { this._ranges.add(JSON.stringify(this.generateRange(node))); } } /** * Adds the active keyboard range selection (if any) to the `ranges` meta. */ public addKeyboardRange(): void { if (this.keyboardState.range) { this._ranges.add(JSON.stringify(this.keyboardState.range)); } } public remove(node: ISelectionNode): void { if (this.selection.has(node.row)) { this.selection.get(node.row).delete(node.column); } if (this.isActiveNode(node)) { this.activeElement = null; } this._ranges.delete(JSON.stringify(this.generateRange(node))); } public isInMap(node: ISelectionNode): boolean { return (this.selection.has(node.row) && this.selection.get(node.row).has(node.column)) || (this.temp.has(node.row) && this.temp.get(node.row).has(node.column)); } public selected(node: ISelectionNode): boolean { return (this.isActiveNode(node) && this.grid.isCellSelectable) || this.isInMap(node); } public isActiveNode(node: ISelectionNode): boolean { if (this.activeElement) { const isActive = this.activeElement.column === node.column && this.activeElement.row === node.row; if (this.grid.hasColumnLayouts) { const layout = this.activeElement.layout; return isActive && this.isActiveLayout(layout, node.layout); } return isActive; } return false; } public isActiveLayout(current: IMultiRowLayoutNode, target: IMultiRowLayoutNode): boolean { return current.columnVisibleIndex === target.columnVisibleIndex; } public addRangeMeta(node: ISelectionNode, state?: SelectionState): void { this._ranges.add(JSON.stringify(this.generateRange(node, state))); } public removeRangeMeta(node: ISelectionNode, state?: SelectionState): void { this._ranges.delete(JSON.stringify(this.generateRange(node, state))); } /** * Generates a new selection range from the given `node`. * If `state` is passed instead it will generate the range based on the passed `node` * and the start node of the `state`. */ public generateRange(node: ISelectionNode, state?: SelectionState): GridSelectionRange { if (!state) { return { rowStart: node.row, rowEnd: node.row, columnStart: node.column, columnEnd: node.column }; } const { row, column } = state.node; const rowStart = Math.min(node.row, row); const rowEnd = Math.max(node.row, row); const columnStart = Math.min(node.column, column); const columnEnd = Math.max(node.column, column); return { rowStart, rowEnd, columnStart, columnEnd }; } /** * */ public keyboardStateOnKeydown(node: ISelectionNode, shift: boolean, shiftTab: boolean): void { this.keyboardState.active = true; this.initPointerState(); this.keyboardState.shift = shift && !shiftTab; if (!this.grid.navigation.isDataRow(node.row)) { return; } // Kb navigation with shift and no previous node. // Clear the current selection init the start node. if (this.keyboardState.shift && !this.keyboardState.node) { this.clear(); this.keyboardState.node = Object.assign({}, node); } } public keyboardStateOnFocus(node: ISelectionNode, emitter: EventEmitter<GridSelectionRange>, dom): void { const kbState = this.keyboardState; // Focus triggered by keyboard navigation if (kbState.active) { if (this.platform.isChromium) { this._moveSelectionChrome(dom); } // Start generating a range if shift is hold if (kbState.shift) { this.dragSelect(node, kbState); kbState.range = this.generateRange(node, kbState); emitter.emit(this.generateRange(node, kbState)); return; } this.initKeyboardState(); this.clear(); this.add(node); } } public pointerDown(node: ISelectionNode, shift: boolean, ctrl: boolean): void { this.addKeyboardRange(); this.initKeyboardState(); this.pointerState.ctrl = ctrl; this.pointerState.shift = shift; this.pointerEventInGridBody = true; document.body.addEventListener('pointerup', this.pointerOriginHandler); // No ctrl key pressed - no multiple selection if (!ctrl) { this.clear(); } if (shift) { // No previously 'clicked' node. Use the last active node. if (!this.pointerState.node) { this.pointerState.node = this.activeElement || node; } this.pointerDownShiftKey(node); this.clearTextSelection(); return; } this.removeRangeMeta(node); this.pointerState.node = node; } public pointerDownShiftKey(node: ISelectionNode): void { this.clear(); this.selectRange(node, this.pointerState); } public mergeMap(target: Map<number, Set<number>>, source: Map<number, Set<number>>): void { const iterator = source.entries(); let pair = iterator.next(); let key: number; let value: Set<number>; while (!pair.done) { [key, value] = pair.value; if (target.has(key)) { const newValue = target.get(key); value.forEach(record => newValue.add(record)); target.set(key, newValue); } else { target.set(key, value); } pair = iterator.next(); } } public pointerEnter(node: ISelectionNode, event: PointerEvent): boolean { // https://www.w3.org/TR/pointerevents/#the-button-property this.dragMode = (event.buttons === 1 && (event.button === -1 || event.button === 0)) && this.pointerEventInGridBody; if (!this.dragMode) { return false; } this.clearTextSelection(); // If the users triggers a drag-like event by first clicking outside the grid cells // and then enters in the grid body we may not have a initial pointer starting node. // Assume the first pointerenter node is where we start. if (!this.pointerState.node) { this.pointerState.node = node; } if (this.pointerState.ctrl) { this.selectRange(node, this.pointerState, this.temp); } else { this.dragSelect(node, this.pointerState); } return true; } public pointerUp(node: ISelectionNode, emitter: EventEmitter<GridSelectionRange>): boolean { if (this.dragMode) { this.restoreTextSelection(); this.addRangeMeta(node, this.pointerState); this.mergeMap(this.selection, this.temp); this.zone.runTask(() => emitter.emit(this.generateRange(node, this.pointerState))); this.temp.clear(); this.dragMode = false; return true; } if (this.pointerState.shift) { this.clearTextSelection(); this.restoreTextSelection(); this.addRangeMeta(node, this.pointerState); emitter.emit(this.generateRange(node, this.pointerState)); return true; } if (this.pointerEventInGridBody) { this.add(node); } return false; } public selectRange(node: ISelectionNode, state: SelectionState, collection: Map<number, Set<number>> = this.selection): void { if (collection === this.temp) { collection.clear(); } const { rowStart, rowEnd, columnStart, columnEnd } = this.generateRange(node, state); for (let i = rowStart; i <= rowEnd; i++) { for (let j = columnStart as number; j <= columnEnd; j++) { if (collection.has(i)) { collection.get(i).add(j); } else { collection.set(i, new Set<number>()).get(i).add(j); } } } } public dragSelect(node: ISelectionNode, state: SelectionState): void { if (!this.pointerState.ctrl) { this.selection.clear(); } this.selectRange(node, state); } public clear(clearAcriveEl = false): void { if (clearAcriveEl) { this.activeElement = null; } this.selection.clear(); this.temp.clear(); this._ranges.clear(); } public clearTextSelection(): void { const selection = window.getSelection(); if (selection.rangeCount) { this._selectionRange = selection.getRangeAt(0); this._selectionRange.collapse(true); selection.removeAllRanges(); } } public restoreTextSelection(): void { const selection = window.getSelection(); if (!selection.rangeCount) { selection.addRange(this._selectionRange || document.createRange()); } } /** Returns array of the selected row id's. */ public getSelectedRows(): Array<any> { return this.rowSelection.size ? Array.from(this.rowSelection.keys()) : []; } /** Returns array of the rows in indeterminate state. */ public getIndeterminateRows(): Array<any> { return this.indeterminateRows.size ? Array.from(this.indeterminateRows.keys()) : []; } /** Clears row selection, if filtering is applied clears only selected rows from filtered data. */ public clearRowSelection(event?): void { const removedRec = this.isFilteringApplied() ? this.getRowIDs(this.allData).filter(rID => this.isRowSelected(rID)) : this.getSelectedRows(); const newSelection = this.isFilteringApplied() ? this.getSelectedRows().filter(x => !removedRec.includes(x)) : []; this.emitRowSelectionEvent(newSelection, [], removedRec, event); } /** Select all rows, if filtering is applied select only from filtered data. */ public selectAllRows(event?) { const allRowIDs = this.getRowIDs(this.allData); const addedRows = allRowIDs.filter((rID) => !this.isRowSelected(rID)); const newSelection = this.rowSelection.size ? this.getSelectedRows().concat(addedRows) : addedRows; this.indeterminateRows.clear(); this.selectedRowsChange.next(); this.emitRowSelectionEvent(newSelection, addedRows, [], event); } /** Select the specified row and emit event. */ public selectRowById(rowID, clearPrevSelection?, event?): void { if (!this.grid.isRowSelectable || this.isRowDeleted(rowID)) { return; } clearPrevSelection = !this.grid.isMultiRowSelectionEnabled || clearPrevSelection; const newSelection = clearPrevSelection ? [rowID] : this.getSelectedRows().indexOf(rowID) !== -1 ? this.getSelectedRows() : [...this.getSelectedRows(), rowID]; const removed = clearPrevSelection ? this.getSelectedRows() : []; this.selectedRowsChange.next(); this.emitRowSelectionEvent(newSelection, [rowID], removed, event); } /** Deselect the specified row and emit event. */ public deselectRow(rowID, event?): void { if (!this.isRowSelected(rowID)) { return; } const newSelection = this.getSelectedRows().filter(r => r !== rowID); if (this.rowSelection.size && this.rowSelection.has(rowID)) { this.selectedRowsChange.next(); this.emitRowSelectionEvent(newSelection, [], [rowID], event); } } /** Select specified rows. No event is emitted. */ public selectRowsWithNoEvent(rowIDs: any[], clearPrevSelection?): void { if (clearPrevSelection) { this.rowSelection.clear(); } rowIDs.forEach(rowID => this.rowSelection.add(rowID)); this.allRowsSelected = undefined; this.selectedRowsChange.next(); } /** Deselect specified rows. No event is emitted. */ public deselectRowsWithNoEvent(rowIDs: any[]): void { rowIDs.forEach(rowID => this.rowSelection.delete(rowID)); this.allRowsSelected = undefined; this.selectedRowsChange.next(); } public isRowSelected(rowID): boolean { return this.rowSelection.size > 0 && this.rowSelection.has(rowID); } public isRowInIndeterminateState(rowID): boolean { return this.indeterminateRows.size > 0 && this.indeterminateRows.has(rowID); } /** Select range from last selected row to the current specified row. */ public selectMultipleRows(rowID, rowData, event?): void { this.allRowsSelected = undefined; if (!this.rowSelection.size || this.isRowDeleted(rowID)) { this.selectRowById(rowID); return; } const gridData = this.allData; const lastRowID = this.getSelectedRows()[this.rowSelection.size - 1]; const currIndex = gridData.indexOf(this.getRowDataById(lastRowID)); const newIndex = gridData.indexOf(rowData); const rows = gridData.slice(Math.min(currIndex, newIndex), Math.max(currIndex, newIndex) + 1); const added = this.getRowIDs(rows).filter(rID => !this.isRowSelected(rID)); const newSelection = this.getSelectedRows().concat(added); this.selectedRowsChange.next(); this.emitRowSelectionEvent(newSelection, added, [], event); } public areAllRowSelected(): boolean { if (!this.grid.data) { return false; } if (this.allRowsSelected !== undefined) { return this.allRowsSelected; } const dataItemsID = this.getRowIDs(this.allData); return this.allRowsSelected = Math.min(this.rowSelection.size, dataItemsID.length) > 0 && new Set(Array.from(this.rowSelection.values()).concat(dataItemsID)).size === this.rowSelection.size; } public hasSomeRowSelected(): boolean { const filteredData = this.isFilteringApplied() ? this.getRowIDs(this.grid.filteredData).some(rID => this.isRowSelected(rID)) : true; return this.rowSelection.size > 0 && filteredData && !this.areAllRowSelected(); } public get filteredSelectedRowIds(): any[] { return this.isFilteringApplied() ? this.getRowIDs(this.allData).filter(rowID => this.isRowSelected(rowID)) : this.getSelectedRows().filter(rowID => !this.isRowDeleted(rowID)); } public emitRowSelectionEvent(newSelection, added, removed, event?): boolean { const currSelection = this.getSelectedRows(); if (this.areEqualCollections(currSelection, newSelection)) { return; } const args = { oldSelection: currSelection, newSelection, added, removed, event, cancel: false }; this.grid.rowSelected.emit(args); if (args.cancel) { return; } this.selectRowsWithNoEvent(args.newSelection, true); } public getRowDataById(rowID): any { if (!this.grid.primaryKey) { return rowID; } const rowIndex = this.getRowIDs(this.grid.gridAPI.get_all_data(true)).indexOf(rowID); return rowIndex < 0 ? {} : this.grid.gridAPI.get_all_data(true)[rowIndex]; } public getRowIDs(data): Array<any> { return this.grid.primaryKey && data.length ? data.map(rec => rec[this.grid.primaryKey]) : data; } public clearHeaderCBState(): void { this.allRowsSelected = undefined; } /** Clear rowSelection and update checkbox state */ public clearAllSelectedRows(): void { this.rowSelection.clear(); this.indeterminateRows.clear(); this.clearHeaderCBState(); this.selectedRowsChange.next(); } /** Returns all data in the grid, with applied filtering and sorting and without deleted rows. */ public get allData(): Array<any> { let allData; if (this.isFilteringApplied() || this.grid.sortingExpressions.length) { allData = this.grid.pinnedRecordsCount ? this.grid._filteredSortedUnpinnedData : this.grid.filteredSortedData; } else { allData = this.grid.gridAPI.get_all_data(true); } return allData.filter(rData => !this.isRowDeleted(this.grid.gridAPI.get_row_id(rData))); } /** Returns array of the selected columns fields. */ public getSelectedColumns(): Array<any> { return this.columnSelection.size ? Array.from(this.columnSelection.keys()) : []; } public isColumnSelected(field: string): boolean { return this.columnSelection.size > 0 && this.columnSelection.has(field); } /** Select the specified column and emit event. */ public selectColumn(field: string, clearPrevSelection?, selectColumnsRange?, event?): void { const stateColumn = this.columnsState.field ? this.grid.getColumnByName(this.columnsState.field) : null; if (!event || !stateColumn || stateColumn.visibleIndex < 0 || !selectColumnsRange) { this.columnsState.field = field; this.columnsState.range = []; const newSelection = clearPrevSelection ? [field] : this.getSelectedColumns().indexOf(field) !== -1 ? this.getSelectedColumns() : [...this.getSelectedColumns(), field]; const removed = clearPrevSelection ? this.getSelectedColumns().filter(colField => colField !== field) : []; const added = this.isColumnSelected(field) ? [] : [field]; this.emitColumnSelectionEvent(newSelection, added, removed, event); } else if (selectColumnsRange) { this.selectColumnsRange(field, event); } } /** Select specified columns. And emit event. */ public selectColumns(fields: string[], clearPrevSelection?, selectColumnsRange?, event?): void { const columns = fields.map(f => this.grid.getColumnByName(f)).sort((a, b) => a.visibleIndex - b.visibleIndex); const stateColumn = this.columnsState.field ? this.grid.getColumnByName(this.columnsState.field) : null; if (!stateColumn || stateColumn.visibleIndex < 0 || !selectColumnsRange) { this.columnsState.field = columns[0] ? columns[0].field : null; this.columnsState.range = []; const added = fields.filter(colField => !this.isColumnSelected(colField)); const removed = clearPrevSelection ? this.getSelectedColumns().filter(colField => fields.indexOf(colField) === -1) : []; const newSelection = clearPrevSelection ? fields : this.getSelectedColumns().concat(added); this.emitColumnSelectionEvent(newSelection, added, removed, event); } else { const filedStart = stateColumn.visibleIndex > columns[columns.length - 1].visibleIndex ? columns[0].field : columns[columns.length - 1].field; this.selectColumnsRange(filedStart, event); } } /** Select range from last clicked column to the current specified column. */ public selectColumnsRange(field: string, event): void { const currIndex = this.grid.getColumnByName(this.columnsState.field).visibleIndex; const newIndex = this.grid.columnToVisibleIndex(field); const columnsFields = this.grid.visibleColumns .filter(c => !c.columnGroup) .sort((a, b) => a.visibleIndex - b.visibleIndex) .slice(Math.min(currIndex, newIndex), Math.max(currIndex, newIndex) + 1) .filter(col => col.selectable).map(col => col.field); const removed = []; const oldAdded = []; const added = columnsFields.filter(colField => !this.isColumnSelected(colField)); this.columnsState.range.forEach(f => { if (columnsFields.indexOf(f) === -1) { removed.push(f); } else { oldAdded.push(f); } }); this.columnsState.range = columnsFields.filter(colField => !this.isColumnSelected(colField) || oldAdded.indexOf(colField) > -1); const newSelection = this.getSelectedColumns().concat(added).filter(c => removed.indexOf(c) === -1); this.emitColumnSelectionEvent(newSelection, added, removed, event); } /** Select specified columns. No event is emitted. */ public selectColumnsWithNoEvent(fields: string[], clearPrevSelection?): void { if (clearPrevSelection) { this.columnSelection.clear(); } fields.forEach(field => { this.columnSelection.add(field); }); } /** Deselect the specified column and emit event. */ public deselectColumn(field: string, event?): void { this.initColumnsState(); const newSelection = this.getSelectedColumns().filter(c => c !== field); this.emitColumnSelectionEvent(newSelection, [], [field], event); } /** Deselect specified columns. No event is emitted. */ public deselectColumnsWithNoEvent(fields: string[]): void { fields.forEach(field => this.columnSelection.delete(field)); } /** Deselect specified columns. And emit event. */ public deselectColumns(fields: string[], event?): void { const removed = this.getSelectedColumns().filter(colField => fields.indexOf(colField) > -1); const newSelection = this.getSelectedColumns().filter(colField => fields.indexOf(colField) === -1); this.emitColumnSelectionEvent(newSelection, [], removed, event); } public emitColumnSelectionEvent(newSelection, added, removed, event?): boolean { const currSelection = this.getSelectedColumns(); if (this.areEqualCollections(currSelection, newSelection)) { return; } const args = { oldSelection: currSelection, newSelection, added, removed, event, cancel: false }; this.grid.columnSelected.emit(args); if (args.cancel) { return; } this.selectColumnsWithNoEvent(args.newSelection, true); } /** Clear columnSelection */ public clearAllSelectedColumns(): void { this.columnSelection.clear(); } protected areEqualCollections(first, second): boolean { return first.length === second.length && new Set(first.concat(second)).size === first.length; } /** * (╯°□°)╯︵ ┻━┻ * Chrome and Chromium don't care about the active * range after keyboard navigation, thus this. */ private _moveSelectionChrome(node: Node) { const selection = window.getSelection(); selection.removeAllRanges(); const range = new Range(); range.selectNode(node); range.collapse(true); selection.addRange(range); } private isFilteringApplied(): boolean { const grid = this.grid as IgxGridBaseDirective; return !FilteringExpressionsTree.empty(grid.filteringExpressionsTree) || !FilteringExpressionsTree.empty(grid.advancedFilteringExpressionsTree); } private isRowDeleted(rowID): boolean { return this.grid.gridAPI.row_deleted_transaction(rowID); } private pointerOriginHandler = () => { this.pointerEventInGridBody = false; document.body.removeEventListener('pointerup', this.pointerOriginHandler); }; }
the_stack
import joynr from "joynr"; import testbase from "test-base"; import * as TestInterfaceProvider from "../generated-javascript/joynr/interlanguagetest/TestInterfaceProvider"; const prettyLog = testbase.logging.prettyLog; import * as IltUtil from "./IltUtil"; import ExtendedEnumerationWithPartlyDefinedValues from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedEnumerationWithPartlyDefinedValues"; import ExtendedTypeCollectionEnumerationInTypeCollection from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedTypeCollectionEnumerationInTypeCollection"; import Enumeration from "../generated-javascript/joynr/interlanguagetest/Enumeration"; import MethodWithAnonymousErrorEnumErrorEnum from "../generated-javascript/joynr/interlanguagetest/TestInterface/MethodWithAnonymousErrorEnumErrorEnum"; import ExtendedErrorEnumTc from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/ExtendedErrorEnumTc"; import MethodWithExtendedErrorEnumErrorEnum from "../generated-javascript/joynr/interlanguagetest/TestInterface/MethodWithExtendedErrorEnumErrorEnum"; import MapStringString from "../generated-javascript/joynr/interlanguagetest/namedTypeCollection2/MapStringString"; // Attributes let attributeUInt8 = 0; let attributeDouble = 0.0; let attributeBooleanReadonly = false; let attributeStringNoSubscriptions = ""; let attributeInt8readonlyNoSubscriptions = 0; let attributeArrayOfStringImplicit = [""]; let attributeByteBuffer: any; let attributeEnumeration: any; let attributeExtendedEnumerationReadonly: any; let attributeBaseStruct: any; let attributeExtendedExtendedBaseStruct: any; let attributeMapStringString: any; let attributeFireAndForget = 0; const typeDefValues = { attributeInt64: 1, attributeString: "TypeDefString", attributeStruct: IltUtil.create("BaseStruct"), attributeMap: new MapStringString(), attributeEnum: Enumeration.ENUM_0_VALUE_1, attributeByteBufferTypeDef: IltUtil.create("ByteArray"), attributeArrayTypeDef: IltUtil.create("StringArray"), attributeByteBuffer: undefined, attributeArray: undefined }; // eslint-disable-next-line @typescript-eslint/explicit-function-return-type function genericSetterGetter(attributeName: keyof typeof typeDefValues) { return { set: (value: any) => { prettyLog(`IltProvider.set called for attribute ${attributeName}`); typeDefValues[attributeName] = value; }, get: async (): Promise<any> => { prettyLog(`IltProvider.get called for attribute ${attributeName}`); return typeDefValues[attributeName]; } }; } const IltProvider: TestInterfaceProvider.TestInterfaceProviderImplementation = { // attribute getter and setter attributeUInt8: { get: async (): Promise<any> => { prettyLog("IltProvider.attributeUInt8.get() called"); return attributeUInt8; }, set: (value: any) => { prettyLog(`IltProvider.attributeUInt8.set(${value}) called`); attributeUInt8 = value; } }, attributeDouble: { get: async () => { prettyLog("IltProvider.attributeDouble.get() called"); return attributeDouble; }, set: (value: any) => { prettyLog(`IltProvider.attributeDouble.set(${value}) called`); attributeDouble = value; } }, attributeBooleanReadonly: { get: async () => { prettyLog("IltProvider.attributeBooleanReadonly.get() called"); attributeBooleanReadonly = true; return attributeBooleanReadonly; } }, attributeStringNoSubscriptions: { get: async () => { prettyLog("IltProvider.attributeStringNoSubscriptions.get() called"); return attributeStringNoSubscriptions; }, set: (value: any) => { prettyLog(`IltProvider.attributeStringNoSubscriptions.set(${value}) called`); attributeStringNoSubscriptions = value; } }, attributeInt8readonlyNoSubscriptions: { get: async () => { prettyLog("IltProvider.attributeInt8readonlyNoSubscriptions.get() called"); attributeInt8readonlyNoSubscriptions = -128; return attributeInt8readonlyNoSubscriptions; } }, attributeArrayOfStringImplicit: { get: async () => { prettyLog("IltProvider.attributeArrayOfStringImplicit.get() called"); return attributeArrayOfStringImplicit; }, set: (value: any) => { prettyLog(`IltProvider.attributeArrayOfStringImplicit.set(${value}) called`); attributeArrayOfStringImplicit = value; } }, attributeByteBuffer: { get: async () => { prettyLog("IltProvider.attributeByteBuffer.get() called"); return attributeByteBuffer; }, set: (value: any) => { prettyLog(`IltProvider.attributeByteBuffer.set(${value}) called`); attributeByteBuffer = value; } }, attributeEnumeration: { get: async () => { prettyLog("IltProvider.attributeEnumeration.get() called"); return attributeEnumeration; }, set: (value: any) => { prettyLog(`IltProvider.attributeEnumeration.set(${value}) called`); attributeEnumeration = value; } }, attributeExtendedEnumerationReadonly: { get: async () => { prettyLog("IltProvider.attributeExtendedEnumerationReadonly.get() called"); attributeExtendedEnumerationReadonly = ExtendedEnumerationWithPartlyDefinedValues.ENUM_2_VALUE_EXTENSION_FOR_ENUM_WITHOUT_DEFINED_VALUES; return attributeExtendedEnumerationReadonly; } }, attributeBaseStruct: { get: async () => { prettyLog("IltProvider.attributeBaseStruct.get() called"); return attributeBaseStruct; }, set: (value: any) => { prettyLog(`IltProvider.attributeBaseStruct.set(${value}) called`); attributeBaseStruct = value; } }, attributeExtendedExtendedBaseStruct: { get: async () => { prettyLog("IltProvider.attributeExtendedExtendedBaseStruct.get() called"); return attributeExtendedExtendedBaseStruct; }, set: (value: any) => { prettyLog(`IltProvider.attributeExtendedExtendedBaseStruct.set(${value}) called`); attributeExtendedExtendedBaseStruct = value; } }, attributeMapStringString: { get: async () => { prettyLog("IltProvider.attributeMapStringString.get() called"); return attributeMapStringString; }, set: (value: any) => { prettyLog(`IltProvider.attributeMapStringString.set(${JSON.stringify(value)}) called`); attributeMapStringString = value; } }, attributeInt64TypeDef: genericSetterGetter("attributeInt64"), attributeStringTypeDef: genericSetterGetter("attributeString"), attributeStructTypeDef: genericSetterGetter("attributeStruct"), attributeMapTypeDef: genericSetterGetter("attributeMap"), attributeEnumTypeDef: genericSetterGetter("attributeEnum"), attributeByteBufferTypeDef: genericSetterGetter("attributeByteBuffer"), attributeArrayTypeDef: genericSetterGetter("attributeArray"), attributeFireAndForget: { get: async () => { prettyLog("IltProvider.attributeFireAndForget.get() called"); return attributeFireAndForget; }, set: (value: any) => { prettyLog(`IltProvider.attributeFireAndForget.set(${value}) called`); attributeFireAndForget = value; } }, attributeWithExceptionFromGetter: { get: async () => { prettyLog("IltProvider.attributeWithExceptionFromGetter.get() called"); throw new joynr.exceptions.ProviderRuntimeException({ detailMessage: "Exception from getAttributeWithExceptionFromGetter" }); } }, attributeWithExceptionFromSetter: { get: async () => { prettyLog("IltProvider.attributeWithExceptionFromSetter.get() called"); return Promise.resolve(false); }, set: (value: any) => { prettyLog(`IltProvider.attributeWithExceptionFromSetter.set(${value}) called`); throw new joynr.exceptions.ProviderRuntimeException({ detailMessage: "Exception from setAttributeWithExceptionFromSetter" }); } }, // methods methodWithoutParameters() { prettyLog("IltProvider.methodWithoutParameters() called"); return Promise.resolve(); }, methodWithoutInputParameter() { prettyLog("IltProvider.methodWithoutInputParameter() called"); return Promise.resolve({ booleanOut: true }); }, methodWithoutOutputParameter(opArgs: { booleanArg: boolean }) { prettyLog(`IltProvider.methodWithoutOutputParameter(${JSON.stringify(opArgs)}) called`); if (opArgs.booleanArg === undefined || opArgs.booleanArg === null || opArgs.booleanArg !== false) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithoutOutputParameter: received wrong argument" }) ); } else { return Promise.resolve(); } }, methodWithSinglePrimitiveParameters(opArgs) { prettyLog(`IltProvider.methodWithSinglePrimitiveParameters(${JSON.stringify(opArgs)}) called`); if (opArgs.uInt16Arg === undefined || opArgs.uInt16Arg === null || opArgs.uInt16Arg !== 32767) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithSinglePrimitiveParameters: invalid argument uInt16Arg" }) ); } else { opArgs.uInt16Arg = 32767; return Promise.resolve({ stringOut: opArgs.uInt16Arg.toString() }); } }, methodWithMultiplePrimitiveParameters(opArgs) { prettyLog(`IltProvider.methodWithMultiplePrimitiveParameters(${JSON.stringify(opArgs)}) called`); if (opArgs.int32Arg === undefined || opArgs.int32Arg === null || opArgs.int32Arg !== 2147483647) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultiplePrimitiveParameters: invalid argument int32Arg" }) ); } else if ( opArgs.floatArg === undefined || opArgs.floatArg === null || !IltUtil.cmpFloat(opArgs.floatArg, 47.11) ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultiplePrimitiveParameters: invalid argument floatArg" }) ); } if (opArgs.booleanArg === undefined || opArgs.booleanArg === null || opArgs.booleanArg !== false) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultiplePrimitiveParameters: invalid argument booleanArg" }) ); } else { return Promise.resolve({ stringOut: opArgs.int32Arg.toString(), doubleOut: opArgs.floatArg }); } }, methodWithSingleArrayParameters(opArgs) { prettyLog(`IltProvider.methodWithSingleArrayParameters(${JSON.stringify(opArgs)}) called`); if ( opArgs.doubleArrayArg === undefined || opArgs.doubleArrayArg === null || !IltUtil.check("DoubleArray", opArgs.doubleArrayArg) ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithSingleArrayParameters: invalid argument doubleArrayArg" }) ); } else { return Promise.resolve({ stringArrayOut: IltUtil.create("StringArray") }); } }, methodWithMultipleArrayParameters(opArgs) { prettyLog(`IltProvider.methodWithMultipleArrayParameters(${JSON.stringify(opArgs)}) called`); if ( opArgs.stringArrayArg === undefined || opArgs.stringArrayArg === null || !IltUtil.check("StringArray", opArgs.stringArrayArg) ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultipleArrayParameters: invalid argument stringArrayArg" }) ); } else if ( opArgs.int8ArrayArg === undefined || opArgs.int8ArrayArg === null || !IltUtil.check("ByteArray", opArgs.int8ArrayArg) ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultipleArrayParameters: invalid argument int8ArrayArg" }) ); } else if ( opArgs.enumArrayArg === undefined || opArgs.enumArrayArg === null || !IltUtil.check("ExtendedInterfaceEnumInTypeCollectionArray", opArgs.enumArrayArg) ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultipleArrayParameters: invalid argument enumArrayArg" }) ); } else if ( opArgs.structWithStringArrayArrayArg === undefined || opArgs.structWithStringArrayArrayArg === null || !IltUtil.check("StructWithStringArrayArray", opArgs.structWithStringArrayArrayArg) ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultipleArrayParameters: invalid argument structWithStringArrayArrayArg" }) ); } else { return Promise.resolve({ uInt64ArrayOut: IltUtil.create("UInt64Array"), structWithStringArrayArrayOut: [ IltUtil.create("StructWithStringArray"), IltUtil.create("StructWithStringArray") ] }); } }, methodWithSingleByteBufferParameter(opArgs) { prettyLog(`IltProvider.methodWithSingleByteBufferParameter(${JSON.stringify(opArgs)}) called`); if (opArgs.byteBufferIn === undefined || opArgs.byteBufferIn === null) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithSingleByteBufferParameter: received wrong argument" }) ); } return Promise.resolve({ byteBufferOut: opArgs.byteBufferIn }); }, methodWithMultipleByteBufferParameters(opArgs) { prettyLog(`IltProvider.methodWithMultipleByteBufferParameters(${JSON.stringify(opArgs)}) called`); if (opArgs.byteBufferIn1 === undefined || opArgs.byteBufferIn1 === null) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultipleByteBufferParameters: invalid argument byteBufferIn1" }) ); } if (opArgs.byteBufferIn2 === undefined || opArgs.byteBufferIn2 === null) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultipleByteBufferParameters: invalid argument byteBufferIn2" }) ); } return Promise.resolve({ byteBufferOut: opArgs.byteBufferIn1.concat(opArgs.byteBufferIn2) }); }, async methodWithInt64TypeDefParameter(opArgs) { prettyLog(`IltProvider.methodWithInt64TypeDefParameter(${JSON.stringify(opArgs)}) called`); if (opArgs.int64TypeDefIn === undefined || opArgs.int64TypeDefIn === null) { throw new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithInt64TypeDefParameter: received wrong argument" }); } return { int64TypeDefOut: opArgs.int64TypeDefIn }; }, async methodWithStringTypeDefParameter(opArgs) { prettyLog(`IltProvider.methodWithStringTypeDefParameter(${JSON.stringify(opArgs)}) called`); if (opArgs.stringTypeDefIn === undefined || opArgs.stringTypeDefIn === null) { throw new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithStringTypeDefParameter: received wrong argument" }); } return { stringTypeDefOut: opArgs.stringTypeDefIn }; }, async methodWithStructTypeDefParameter(opArgs) { prettyLog(`IltProvider.methodWithStructTypeDefParameter(${JSON.stringify(opArgs)}) called`); if (opArgs.structTypeDefIn === undefined || opArgs.structTypeDefIn === null) { throw new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithStructTypeDefParameter: received wrong argument" }); } return { structTypeDefOut: opArgs.structTypeDefIn }; }, async methodWithMapTypeDefParameter(opArgs) { prettyLog(`IltProvider.methodWithMapTypeDefParameter(${JSON.stringify(opArgs)}) called`); if (opArgs.mapTypeDefIn === undefined || opArgs.mapTypeDefIn === null) { throw new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMapTypeDefParameter: received wrong argument" }); } return { mapTypeDefOut: opArgs.mapTypeDefIn }; }, async methodWithEnumTypeDefParameter(opArgs) { prettyLog(`IltProvider.methodWithEnumTypeDefParameter(${JSON.stringify(opArgs)}) called`); if (opArgs.enumTypeDefIn === undefined || opArgs.enumTypeDefIn === null) { throw new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithEnumTypeDefParameter: received wrong argument" }); } return { enumTypeDefOut: opArgs.enumTypeDefIn }; }, async methodWithByteBufferTypeDefParameter(opArgs) { prettyLog(`IltProvider.methodWithByteBufferTypeDefParameter(${JSON.stringify(opArgs)}) called`); if (opArgs.byteBufferTypeDefIn === undefined || opArgs.byteBufferTypeDefIn === null) { throw new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithByteBufferTypeDefParameter: received wrong argument" }); } return { byteBufferTypeDefOut: opArgs.byteBufferTypeDefIn }; }, async methodWithArrayTypeDefParameter(opArgs) { prettyLog(`IltProvider.methodWithArrayTypeDefParameter(${JSON.stringify(opArgs)}) called`); if (opArgs.arrayTypeDefIn === undefined || opArgs.arrayTypeDefIn === null) { throw new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithArrayTypeDefParameter: received wrong argument" }); } return { arrayTypeDefOut: opArgs.arrayTypeDefIn }; }, methodWithSingleEnumParameters(opArgs) { prettyLog(`IltProvider.methodWithSingleEnumParameters(${JSON.stringify(opArgs)}) called`); if ( opArgs.enumerationArg === undefined || opArgs.enumerationArg === null || opArgs.enumerationArg !== ExtendedEnumerationWithPartlyDefinedValues.ENUM_2_VALUE_EXTENSION_FOR_ENUM_WITHOUT_DEFINED_VALUES ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithSingleEnumParameters: invalid argument enumerationArg" }) ); } else { return Promise.resolve({ enumerationOut: ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION }); } }, methodWithMultipleEnumParameters(opArgs) { prettyLog(`IltProvider.methodWithMultipleEnumParameters(${JSON.stringify(opArgs)}) called`); if ( opArgs.enumerationArg === undefined || opArgs.enumerationArg === null || opArgs.enumerationArg !== Enumeration.ENUM_0_VALUE_3 ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultipleEnumParameters: invalid argument enumerationArg" }) ); } else if ( opArgs.extendedEnumerationArg === undefined || opArgs.extendedEnumerationArg === null || opArgs.extendedEnumerationArg !== ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultipleEnumParameters: invalid argument extendedEnumerationArg" }) ); } else { return Promise.resolve({ extendedEnumerationOut: ExtendedEnumerationWithPartlyDefinedValues.ENUM_2_VALUE_EXTENSION_FOR_ENUM_WITHOUT_DEFINED_VALUES, enumerationOut: Enumeration.ENUM_0_VALUE_1 }); } }, methodWithSingleMapParameters(opArgs) { prettyLog(`IltProvider.methodWithSingleMapParameters(${JSON.stringify(opArgs)}) called`); if (opArgs.mapArg === undefined || opArgs.mapArg === null) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithSingleMapParameters: invalid argument mapArg" }) ); } else { const mapOut = new MapStringString(); for (let i = 1; i <= 3; i++) { mapOut.put(opArgs.mapArg.get(`keyString${i}`), `keyString${i}`); } return Promise.resolve({ mapOut }); } }, methodWithSingleStructParameters(opArgs) { prettyLog(`IltProvider.methodWithSingleStructParameters(${JSON.stringify(opArgs)}) called`); if ( opArgs.extendedBaseStructArg === undefined || opArgs.extendedBaseStructArg === null || !IltUtil.check("ExtendedBaseStruct", opArgs.extendedBaseStructArg) ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithSingleStructParameters: invalid argument extendedBaseStructArg" }) ); } else { return Promise.resolve({ extendedStructOfPrimitivesOut: IltUtil.createExtendedStructOfPrimitives() }); } }, methodWithMultipleStructParameters(opArgs) { prettyLog(`IltProvider.methodWithMultipleStructParameters(${JSON.stringify(opArgs)}) called`); if ( opArgs.extendedStructOfPrimitivesArg === undefined || opArgs.extendedStructOfPrimitivesArg === null || !IltUtil.checkExtendedStructOfPrimitives(opArgs.extendedStructOfPrimitivesArg) ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultipleStructParameters: invalid argument extendedStructOfPrimitivesArg" }) ); } else if ( opArgs.baseStructArg === undefined || opArgs.baseStructArg === null || !IltUtil.check("BaseStruct", opArgs.baseStructArg) ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithMultipleStructParameters: invalid argument baseStructArg" }) ); } else { return Promise.resolve({ baseStructWithoutElementsOut: IltUtil.create("BaseStructWithoutElements"), extendedExtendedBaseStructOut: IltUtil.create("ExtendedExtendedBaseStruct") }); } }, methodWithStringsAndSpecifiedStringOutLength(opArgs) { prettyLog(`IltProvider.methodWithStringsAndSpecifiedStringOutLength(${JSON.stringify(opArgs)}) called`); if ( opArgs.int32StringLengthArg === undefined || opArgs.int32StringLengthArg === null || opArgs.int32StringLengthArg > 1024 * 1024 ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodWithStringsAndSpecifiedStringOutLength: Maximum length exceeded" }) ); } else { let stringOutValue = ""; for (let i = 0; i < opArgs.int32StringLengthArg; i++) { stringOutValue += "A"; } return Promise.resolve({ stringOut: stringOutValue }); } }, // FIRE-AND-FORGET METHODS methodFireAndForgetWithoutParameter(opArgs) { prettyLog(`IltProvider.methodFireAndForgetWithoutParameter(${JSON.stringify(opArgs)}) called`); IltProvider.attributeFireAndForget.set(attributeFireAndForget + 1); // TODO: no idea what the valueChanged does, because set would emit ValueChanged with value +1. // @ts-ignore IltProvider.attributeFireAndForget.valueChanged(attributeFireAndForget); }, methodFireAndForgetWithInputParameter(opArgs) { prettyLog(`IltProvider.methodFireAndForgetWithInputParameter(${JSON.stringify(opArgs)}) called`); if (opArgs.int32Arg === undefined || opArgs.int32Arg === null || typeof opArgs.int32Arg !== "number") { prettyLog("methodFireAndForgetWithInputParameter: invalid argument int32Arg"); IltProvider.attributeFireAndForget.set(-1); } else { IltProvider.attributeFireAndForget.set(opArgs.int32Arg); } // @ts-ignore IltProvider.attributeFireAndForget.valueChanged(attributeFireAndForget); }, // OVERLOADED METHODS overloadedMethod(opArgs: any): any { prettyLog(`IltProvider.overloadedMethod(${JSON.stringify(opArgs)}) called`); if ( opArgs.int64Arg !== undefined && opArgs.int64Arg !== null && opArgs.booleanArg !== undefined && opArgs.booleanArg !== null && opArgs.enumArrayArg !== undefined && opArgs.enumArrayArg !== null && opArgs.baseStructArg !== undefined && opArgs.baseStructArg !== null ) { prettyLog("IltProvider.overloadedMethod (3)"); if (opArgs.int64Arg !== 1) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethod_3: invalid argument int64Arg" }) ); } else if (opArgs.booleanArg !== false) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethod_3: invalid argument booleanArg" }) ); } else if (!IltUtil.check("ExtendedExtendedEnumerationArray", opArgs.enumArrayArg)) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethod_3: invalid argument enumArrayArg" }) ); } else if (!IltUtil.check("BaseStruct", opArgs.baseStructArg)) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethod_3: invalid argument baseStructArg" }) ); } else { return Promise.resolve({ doubleOut: 0, stringArrayOut: IltUtil.create("StringArray"), extendedBaseStructOut: IltUtil.create("ExtendedBaseStruct") }); } } else if (opArgs.booleanArg !== undefined && opArgs.booleanArg !== null) { prettyLog("IltProvider.overloadedMethod (2)"); if (opArgs.booleanArg !== false) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethod_2: invalid argument booleanArg" }) ); } else { return Promise.resolve({ stringOut: "TestString 2" }); } } else if (opArgs !== undefined && opArgs !== null) { prettyLog("IltProvider.overloadedMethod (1)"); return Promise.resolve({ stringOut: "TestString 1" }); } else { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethod: invalid arguments" }) ); } }, overloadedMethodWithSelector(opArgs: any): any { prettyLog(`IltProvider.overloadedMethodWithSelector(${JSON.stringify(opArgs)}) called`); if ( opArgs.int64Arg !== undefined && opArgs.int64Arg !== null && opArgs.booleanArg !== undefined && opArgs.booleanArg !== null && opArgs.enumArrayArg !== undefined && opArgs.enumArrayArg !== null && opArgs.baseStructArg !== undefined && opArgs.baseStructArg !== null ) { prettyLog("IltProvider.overloadedMethodWithSelector (3)"); if (opArgs.int64Arg !== 1) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethodWithSelector_3: invalid argument int64Arg" }) ); } else if (opArgs.booleanArg !== false) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethodWithSelector_3: invalid argument booleanArg" }) ); } else if (!IltUtil.check("ExtendedExtendedEnumerationArray", opArgs.enumArrayArg)) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethodWithSelector_3: invalid argument enumArrayArg" }) ); } else if (!IltUtil.check("BaseStruct", opArgs.baseStructArg)) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethodWithSelector_3: invalid argument baseStructArg" }) ); } else { return Promise.resolve({ doubleOut: 1.1, stringArrayOut: IltUtil.create("StringArray"), extendedBaseStructOut: IltUtil.create("ExtendedBaseStruct") }); } } else if (opArgs.booleanArg !== undefined && opArgs.booleanArg !== null) { prettyLog("IltProvider.overloadedMethodWithSelector (2)"); if (opArgs.booleanArg !== false) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethodWithSelector_2: invalid argument booleanArg" }) ); } else { return Promise.resolve({ stringOut: "Return value from overloadedMethodWithSelector 2" }); } } else if (opArgs !== undefined && opArgs !== null) { prettyLog("IltProvider.overloadedMethodWithSelector (1)"); return Promise.resolve({ stringOut: "Return value from overloadedMethodWithSelector 1" }); } else { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "overloadedMethodWithSelector: invalid arguments" }) ); } }, // METHODS WITH ERROR DEFINITIONS methodWithoutErrorEnum(opArgs) { prettyLog(`IltProvider.methodWithoutErrorEnum(${JSON.stringify(opArgs)}) called`); if ( opArgs.wantedExceptionArg !== undefined && opArgs.wantedExceptionArg !== null && opArgs.wantedExceptionArg === "ProviderRuntimeException" ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "Exception from methodWithoutErrorEnum" }) ); } else { return Promise.resolve(); } }, methodWithAnonymousErrorEnum(opArgs) { prettyLog(`IltProvider.methodWithAnonymousErrorEnum(${JSON.stringify(opArgs)}) called`); if ( opArgs.wantedExceptionArg !== undefined && opArgs.wantedExceptionArg !== null && opArgs.wantedExceptionArg === "ProviderRuntimeException" ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "Exception from methodWithAnonymousErrorEnum" }) ); } else if ( opArgs.wantedExceptionArg !== undefined && opArgs.wantedExceptionArg !== null && opArgs.wantedExceptionArg === "ApplicationException" ) { return Promise.reject(MethodWithAnonymousErrorEnumErrorEnum.ERROR_3_1_NTC); } else { return Promise.resolve(); } }, methodWithExistingErrorEnum(opArgs) { prettyLog(`IltProvider.methodWithExistingErrorEnum(${JSON.stringify(opArgs)}) called`); if ( opArgs.wantedExceptionArg !== undefined && opArgs.wantedExceptionArg !== null && opArgs.wantedExceptionArg === "ProviderRuntimeException" ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "Exception from methodWithExistingErrorEnum" }) ); } else if ( opArgs.wantedExceptionArg !== undefined && opArgs.wantedExceptionArg !== null && opArgs.wantedExceptionArg === "ApplicationException_1" ) { return Promise.reject(ExtendedErrorEnumTc.ERROR_2_3_TC2); } else if ( opArgs.wantedExceptionArg !== undefined && opArgs.wantedExceptionArg !== null && opArgs.wantedExceptionArg === "ApplicationException_2" ) { return Promise.reject(ExtendedErrorEnumTc.ERROR_1_2_TC_2); } else { return Promise.resolve(); } }, methodWithExtendedErrorEnum(opArgs) { prettyLog(`IltProvider.methodWithExtendedErrorEnum(${JSON.stringify(opArgs)}) called`); if ( opArgs.wantedExceptionArg !== undefined && opArgs.wantedExceptionArg !== null && opArgs.wantedExceptionArg === "ProviderRuntimeException" ) { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "Exception from methodWithExtendedErrorEnum" }) ); } else if ( opArgs.wantedExceptionArg !== undefined && opArgs.wantedExceptionArg !== null && opArgs.wantedExceptionArg === "ApplicationException_1" ) { return Promise.reject(MethodWithExtendedErrorEnumErrorEnum.ERROR_3_3_NTC); } else if ( opArgs.wantedExceptionArg !== undefined && opArgs.wantedExceptionArg !== null && opArgs.wantedExceptionArg === "ApplicationException_2" ) { return Promise.reject(MethodWithExtendedErrorEnumErrorEnum.ERROR_2_1_TC2); } else { return Promise.resolve(); } }, methodToFireBroadcastWithSinglePrimitiveParameter(opArgs) { prettyLog(`IltProvider.methodToFireBroadcastWithSinglePrimitiveParameter(${JSON.stringify(opArgs)}) called`); const stringOut = "boom"; const outputParameters = IltProvider.broadcastWithSinglePrimitiveParameter!.createBroadcastOutputParameters(); outputParameters.setStringOut(stringOut); IltProvider.broadcastWithSinglePrimitiveParameter!.fire(outputParameters, opArgs.partitions); return Promise.resolve(); }, methodToFireBroadcastWithMultiplePrimitiveParameters(opArgs) { prettyLog(`IltProvider.methodToFireBroadcastWithMultiplePrimitiveParameters(${JSON.stringify(opArgs)}) called`); const stringOut = "boom"; const doubleOut = 1.1; const outputParameters = IltProvider.broadcastWithMultiplePrimitiveParameters!.createBroadcastOutputParameters(); outputParameters.setStringOut(stringOut); outputParameters.setDoubleOut(doubleOut); IltProvider.broadcastWithMultiplePrimitiveParameters!.fire(outputParameters, opArgs.partitions); return Promise.resolve(); }, methodToFireBroadcastWithSingleArrayParameter(opArgs) { prettyLog(`IltProvider.methodToFireBroadcastWithSingleArrayParameter(${JSON.stringify(opArgs)}) called`); const stringArrayOut = IltUtil.create("StringArray"); const outputParameters = IltProvider.broadcastWithSingleArrayParameter!.createBroadcastOutputParameters(); outputParameters.setStringArrayOut(stringArrayOut); IltProvider.broadcastWithSingleArrayParameter!.fire(outputParameters, opArgs.partitions); return Promise.resolve(); }, methodToFireBroadcastWithMultipleArrayParameters(opArgs) { prettyLog(`IltProvider.methodToFireBroadcastWithMultipleArrayParameters(${JSON.stringify(opArgs)}) called`); const uInt64ArrayOut = IltUtil.create("UInt64Array"); const structWithStringArrayArrayOut = IltUtil.create("StructWithStringArrayArray"); const outputParameters = IltProvider.broadcastWithMultipleArrayParameters!.createBroadcastOutputParameters(); outputParameters.setUInt64ArrayOut(uInt64ArrayOut); outputParameters.setStructWithStringArrayArrayOut(structWithStringArrayArrayOut); IltProvider.broadcastWithMultipleArrayParameters!.fire(outputParameters, opArgs.partitions); return Promise.resolve(); }, methodToFireBroadcastWithSingleByteBufferParameter(opArgs) { prettyLog(`IltProvider.methodToFireBroadcastWithSingleByteBufferParameter(${JSON.stringify(opArgs)}) called`); const outputParameters = IltProvider.broadcastWithSingleByteBufferParameter!.createBroadcastOutputParameters(); outputParameters.setByteBufferOut(opArgs.byteBufferIn); IltProvider.broadcastWithSingleByteBufferParameter!.fire(outputParameters, opArgs.partitions); return Promise.resolve(); }, methodToFireBroadcastWithMultipleByteBufferParameters(opArgs) { prettyLog( `IltProvider.methodToFireBroadcastWithMultipleByteBufferParameters(${JSON.stringify(opArgs)}) called` ); const outputParameters = IltProvider.broadcastWithMultipleByteBufferParameters!.createBroadcastOutputParameters(); outputParameters.setByteBufferOut1(opArgs.byteBufferIn1); outputParameters.setByteBufferOut2(opArgs.byteBufferIn2); IltProvider.broadcastWithMultipleByteBufferParameters!.fire(outputParameters, opArgs.partitions); return Promise.resolve(); }, methodToFireBroadcastWithSingleEnumerationParameter(opArgs) { prettyLog(`IltProvider.methodToFireBroadcastWithSingleEnumerationParameter(${JSON.stringify(opArgs)}) called`); const enumerationOut = ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION; const outputParameters = IltProvider.broadcastWithSingleEnumerationParameter!.createBroadcastOutputParameters(); outputParameters.setEnumerationOut(enumerationOut); IltProvider.broadcastWithSingleEnumerationParameter!.fire(outputParameters, opArgs.partitions); return Promise.resolve(); }, methodToFireBroadcastWithMultipleEnumerationParameters(opArgs) { prettyLog( `IltProvider.methodToFireBroadcastWithMultipleEnumerationParameters(${JSON.stringify(opArgs)}) called` ); const extendedEnumerationOut = ExtendedEnumerationWithPartlyDefinedValues.ENUM_2_VALUE_EXTENSION_FOR_ENUM_WITHOUT_DEFINED_VALUES; const enumerationOut = Enumeration.ENUM_0_VALUE_1; const outputParameters = IltProvider.broadcastWithMultipleEnumerationParameters!.createBroadcastOutputParameters(); outputParameters.setExtendedEnumerationOut(extendedEnumerationOut); outputParameters.setEnumerationOut(enumerationOut); IltProvider.broadcastWithMultipleEnumerationParameters!.fire(outputParameters, opArgs.partitions); return Promise.resolve(); }, methodToFireBroadcastWithSingleStructParameter(opArgs) { prettyLog(`IltProvider.methodToFireBroadcastWithSingleStructParameter(${JSON.stringify(opArgs)}) called`); const extendedStructOfPrimitivesOut = IltUtil.createExtendedStructOfPrimitives(); const outputParameters = IltProvider.broadcastWithSingleStructParameter!.createBroadcastOutputParameters(); outputParameters.setExtendedStructOfPrimitivesOut(extendedStructOfPrimitivesOut); IltProvider.broadcastWithSingleStructParameter!.fire(outputParameters, opArgs.partitions); return Promise.resolve(); }, methodToFireBroadcastWithMultipleStructParameters(opArgs) { prettyLog(`IltProvider.methodToFireBroadcastWithMultipleStructParameters(${JSON.stringify(opArgs)}) called`); const baseStructWithoutElementsOut = IltUtil.create("BaseStructWithoutElements"); const extendedExtendedBaseStructOut = IltUtil.create("ExtendedExtendedBaseStruct"); const outputParameters = IltProvider.broadcastWithMultipleStructParameters!.createBroadcastOutputParameters(); outputParameters.setBaseStructWithoutElementsOut(baseStructWithoutElementsOut); outputParameters.setExtendedExtendedBaseStructOut(extendedExtendedBaseStructOut); IltProvider.broadcastWithMultipleStructParameters!.fire(outputParameters, opArgs.partitions); return Promise.resolve(); }, methodToFireBroadcastWithFiltering(opArgs) { prettyLog(`IltProvider.methodToFireBroadcastWithFiltering(${JSON.stringify(opArgs)}) called`); const stringOut = opArgs.stringArg; const stringArrayOut = IltUtil.create("StringArray"); const enumerationOut = ExtendedTypeCollectionEnumerationInTypeCollection.ENUM_2_VALUE_EXTENSION_FOR_TYPECOLLECTION; const structWithStringArrayOut = IltUtil.create("StructWithStringArray"); const structWithStringArrayArrayOut = IltUtil.create("StructWithStringArrayArray"); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const outputParameters = IltProvider.broadcastWithFiltering!.createBroadcastOutputParameters(); if (stringOut === undefined || stringOut === null || typeof stringOut !== "string") { return Promise.reject( new joynr.exceptions.ProviderRuntimeException({ detailMessage: "methodToFireBroadcastWithFiltering: received wrong argument" }) ); } else { outputParameters.setStringOut(stringOut); outputParameters.setStringArrayOut(stringArrayOut); outputParameters.setEnumerationOut(enumerationOut); outputParameters.setStructWithStringArrayOut(structWithStringArrayOut); outputParameters.setStructWithStringArrayArrayOut(structWithStringArrayArrayOut); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion IltProvider.broadcastWithFiltering!.fire(outputParameters); return Promise.resolve(); } } }; export = IltProvider;
the_stack
import { authn, icons, ns, pad, widgets } from 'solid-ui' import { graph, log, NamedNode, Namespace, sym, serialize, Store } from 'rdflib' import { PaneDefinition } from 'pane-registry' import { AppDetails } from 'solid-ui/lib/authn/types' /* pad Pane ** */ const paneDef: PaneDefinition = { // icon: (module.__dirname || __dirname) + 'images/ColourOn.png', icon: icons.iconBase + 'noun_79217.svg', name: 'pad', audience: [ns.solid('PowerUser')], // Does the subject deserve an pad pane? label: function (subject, context) { const t = (context.session.store as Store).findTypeURIs(subject) if (t['http://www.w3.org/ns/pim/pad#Notepad']) { return 'pad' } return null // No under other circumstances }, mintClass: ns.pad('Notepad'), mintNew: function (context, newPaneOptions: any) { const store = context.session.store as Store const updater = store.updater if (newPaneOptions.me && !newPaneOptions.me.uri) { throw new Error('notepad mintNew: Invalid userid') } const newInstance = (newPaneOptions.newInstance = newPaneOptions.newInstance || store.sym(newPaneOptions.newBase + 'index.ttl#this')) // const newInstance = kb.sym(newBase + 'pad.ttl#thisPad'); const newPadDoc = newInstance.doc() store.add(newInstance, ns.rdf('type'), ns.pad('Notepad'), newPadDoc) store.add(newInstance, ns.dc('title'), 'Shared Notes', newPadDoc) store.add(newInstance, ns.dc('created'), new Date() as any, newPadDoc) // @@ TODO Remove casting if (newPaneOptions.me) { store.add(newInstance, ns.dc('author'), newPaneOptions.me, newPadDoc) } // kb.add(newInstance, ns.pad('next'), newInstance, newPadDoc); // linked list empty @@ const chunk = store.sym(newInstance.uri + '_line0') store.add(newInstance, ns.pad('next'), chunk, newPadDoc) // Linked list has one entry store.add(chunk, ns.pad('next'), newInstance, newPadDoc) store.add(chunk, ns.dc('author'), newPaneOptions.me, newPadDoc) store.add(chunk, ns.sioc('content'), '', newPadDoc) return new Promise(function (resolve, reject) { if (!updater) { reject(new Error('Have no updater')) return } updater.put( newPadDoc, store.statementsMatching(undefined, undefined, undefined, newPadDoc), 'text/turtle', function (uri2, ok, message) { if (ok) { resolve(newPaneOptions) } else { reject( new Error('FAILED to save new tool at: ' + uri2 + ' : ' + message) ) } } ) }) }, // and follow instructions there // @@ TODO Set better type for paneOptions render: function (subject, context, paneOptions: any) { const dom = context.dom const store = context.session.store as Store // Utility functions const complainIfBad = function (ok: boolean, message: string) { if (!ok) { div.appendChild(widgets.errorMessageBlock(dom, message, 'pink')) } } const clearElement = function (ele: HTMLElement) { while (ele.firstChild) { ele.removeChild(ele.firstChild) } return ele } // Access control // Two constiations of ACL for this app, public read and public read/write // In all cases owner has read write control const genACLtext = function ( docURI: string, aclURI: string, allWrite: boolean ) { const g = graph() const auth = Namespace('http://www.w3.org/ns/auth/acl#') let a = g.sym(aclURI + '#a1') const acl = g.sym(aclURI) const doc = g.sym(docURI) g.add(a, ns.rdf('type'), auth('Authorization'), acl) g.add(a, auth('accessTo'), doc, acl) g.add(a, auth('agent'), me, acl) g.add(a, auth('mode'), auth('Read'), acl) g.add(a, auth('mode'), auth('Write'), acl) g.add(a, auth('mode'), auth('Control'), acl) a = g.sym(aclURI + '#a2') g.add(a, ns.rdf('type'), auth('Authorization'), acl) g.add(a, auth('accessTo'), doc, acl) g.add(a, auth('agentClass'), ns.foaf('Agent'), acl) g.add(a, auth('mode'), auth('Read'), acl) if (allWrite) { g.add(a, auth('mode'), auth('Write'), acl) } // TODO: Figure out why `serialize` isn't on the type definition according to TypeScript: return serialize(acl, g, aclURI, 'text/turtle') } /** * @param docURI * @param allWrite * @param callbackFunction * * @returns {Promise<Response>} */ const setACL = function setACL ( docURI: string, allWrite: boolean, callbackFunction: Function ) { const aclDoc = store.any( sym(docURI), sym('http://www.iana.org/assignments/link-relations/acl') ) as NamedNode // @@ check that this get set by web.js if (!fetcher) { throw new Error('Have no fetcher') } if (aclDoc) { // Great we already know where it is const aclText = genACLtext(docURI, aclDoc.uri, allWrite) return fetcher .webOperation('PUT', aclDoc.uri, { data: aclText, contentType: 'text/turtle' }) .then(() => callbackFunction(true)) .catch(err => { callbackFunction(false, err.message) }) } else { return fetcher .load(docURI) .catch((err: Error) => { callbackFunction(false, 'Getting headers for ACL: ' + err) }) .then(() => { const aclDoc = store.any( sym(docURI), sym('http://www.iana.org/assignments/link-relations/acl') ) as NamedNode if (!aclDoc) { // complainIfBad(false, "No Link rel=ACL header for " + docURI); throw new Error('No Link rel=ACL header for ' + docURI) } const aclText = genACLtext(docURI, aclDoc.uri, allWrite) return fetcher.webOperation('PUT', aclDoc.uri, { data: aclText, contentType: 'text/turtle' }) }) .then(() => callbackFunction(true)) .catch(err => { callbackFunction(false, err.message) }) } } // Reproduction: spawn a new instance // // Viral growth path: user of app decides to make another instance const newInstanceButton = function () { const button = div.appendChild(dom.createElement('button')) button.textContent = 'Start another pad' button.addEventListener('click', function () { return showBootstrap(subject, spawnArea, 'pad') }) return button } // Option of either using the workspace system or just typing in a URI const showBootstrap = function showBootstrap ( thisInstance: any, container: HTMLElement, noun: string ) { const div = clearElement(container) const appDetails = { noun: 'notepad' } as AppDetails div.appendChild( authn.newAppInstance(dom, appDetails, (workspace: string | null, newBase) => { // FIXME: not sure if this will work at all, just // trying to get the types to match - Michiel. return initializeNewInstanceInWorkspace(new NamedNode(workspace || newBase)) }) ) div.appendChild(dom.createElement('hr')) // @@ const p = div.appendChild(dom.createElement('p')) p.textContent = 'Where would you like to store the data for the ' + noun + '? ' + 'Give the URL of the directory where you would like the data stored.' const baseField = div.appendChild(dom.createElement('input')) baseField.setAttribute('type', 'text') baseField.size = 80 // really a string ;(baseField as any).label = 'base URL' baseField.autocomplete = 'on' div.appendChild(dom.createElement('br')) // @@ const button = div.appendChild(dom.createElement('button')) button.textContent = 'Start new ' + noun + ' at this URI' button.addEventListener('click', function (_e) { let newBase = baseField.value if (newBase.slice(-1) !== '/') { newBase += '/' } initializeNewInstanceAtBase(thisInstance, newBase) }) } // Create new document files for new instance of app const initializeNewInstanceInWorkspace = function (ws: NamedNode) { // @@ TODO Clean up type for newBase let newBase: any = store.any(ws, ns.space('uriPrefix')) if (!newBase) { newBase = ws.uri.split('#')[0] } else { newBase = newBase.value } if (newBase.slice(-1) !== '/') { log.error(appPathSegment + ': No / at end of uriPrefix ' + newBase) // @@ paramater? newBase = newBase + '/' } const now = new Date() newBase += appPathSegment + '/id' + now.getTime() + '/' // unique id initializeNewInstanceAtBase(thisInstance, newBase) } const initializeNewInstanceAtBase = function ( thisInstance: any, newBase: string ) { const here = sym(thisInstance.uri.split('#')[0]) const base = here // @@ ??? const newPadDoc = store.sym(newBase + 'pad.ttl') const newIndexDoc = store.sym(newBase + 'index.html') const toBeCopied = [{ local: 'index.html', contentType: 'text/html' }] const newInstance = store.sym(newPadDoc.uri + '#thisPad') // log.debug("\n Ready to put " + kb.statementsMatching(undefined, undefined, undefined, there)); //@@ const agenda: Function[] = [] let f // @@ This needs some form of visible progress bar for (f = 0; f < toBeCopied.length; f++) { const item = toBeCopied[f] const fun = function copyItem (item: any) { agenda.push(function () { const newURI = newBase + item.local console.log('Copying ' + base + item.local + ' to ' + newURI) const setThatACL = function () { setACL(newURI, false, function (ok: boolean, message: string) { if (!ok) { complainIfBad( ok, 'FAILED to set ACL ' + newURI + ' : ' + message ) console.log('FAILED to set ACL ' + newURI + ' : ' + message) } else { agenda.shift()!() // beware too much nesting } }) } if (!store.fetcher) { throw new Error('Store has no fetcher') } store.fetcher .webCopy( base + item.local, newBase + item.local, item.contentType ) .then(() => authn.checkUser()) .then(webId => { me = webId setThatACL() }) .catch(err => { console.log( 'FAILED to copy ' + base + item.local + ' : ' + err.message ) complainIfBad( false, 'FAILED to copy ' + base + item.local + ' : ' + err.message ) }) }) } fun(item) } agenda.push(function createNewPadDataFile () { store.add(newInstance, ns.rdf('type'), PAD('Notepad'), newPadDoc) // TODO @@ Remove casting of add store.add( newInstance, ns.dc('created'), new Date() as any, // @@ TODO Remove casting newPadDoc ) if (me) { store.add(newInstance, ns.dc('author'), me, newPadDoc) } store.add(newInstance, PAD('next'), newInstance, newPadDoc) // linked list empty // Keep a paper trail @@ Revisit when we have non-public ones @@ Privacy store.add(newInstance, ns.space('inspiration'), thisInstance, padDoc) store.add(newInstance, ns.space('inspiration'), thisInstance, newPadDoc) if (!updater) { throw new Error('Have no updater') } updater.put( newPadDoc, store.statementsMatching(undefined, undefined, undefined, newPadDoc), 'text/turtle', function (_uri2, ok, message) { if (ok) { agenda.shift()!() } else { complainIfBad( ok, 'FAILED to save new notepad at: ' + newPadDoc.uri + ' : ' + message ) console.log( 'FAILED to save new notepad at: ' + newPadDoc.uri + ' : ' + message ) } } ) }) agenda.push(function () { setACL(newPadDoc.uri, true, function (ok: boolean, body: string) { complainIfBad( ok, 'Failed to set Read-Write ACL on pad data file: ' + body ) if (ok) agenda.shift()!() }) }) agenda.push(function () { // give the user links to the new app const p = div.appendChild(dom.createElement('p')) p.setAttribute('style', 'font-size: 140%;') p.innerHTML = "Your <a href='" + newIndexDoc.uri + "'><b>new notepad</b></a> is ready. " + "<br/><br/><a href='" + newIndexDoc.uri + "'>Go to new pad</a>" }) agenda.shift()!() // Created new data files. } // Update on incoming changes const showResults = function (exists: boolean) { console.log('showResults()') me = authn.currentUser() authn.checkUser().then((webId: unknown) => { me = webId as string }) const title = store.any(subject, ns.dc('title')) || store.any(subject, ns.vcard('fn')) if (paneOptions.solo && typeof window !== 'undefined' && title) { window.document.title = title.value } options.exists = exists padEle = pad.notepad(dom, padDoc, subject, me, options) naviMain.appendChild(padEle) const partipationTarget = store.any(subject, ns.meeting('parentMeeting')) || subject pad.manageParticipation( dom, naviMiddle2, padDoc, partipationTarget as any, me, options ) if (!store.updater) { throw new Error('Store has no updater') } store.updater.setRefreshHandler(padDoc, padEle.reloadAndSync) // initiated = } // Read or create empty data file const loadPadData = function () { if (!fetcher) { throw new Error('Have no fetcher') } fetcher.nowOrWhenFetched(padDoc.uri, undefined, function ( ok: boolean, body: string, response: any ) { if (!ok) { if (response.status === 404) { // / Check explicitly for 404 error console.log('Initializing results file ' + padDoc) if (!updater) { throw new Error('Have no updater') } updater.put(padDoc, [], 'text/turtle', function ( _uri2, ok, message ) { if (ok) { clearElement(naviMain) showResults(false) } else { complainIfBad( ok, 'FAILED to create results file at: ' + padDoc.uri + ' : ' + message ) console.log( 'FAILED to craete results file at: ' + padDoc.uri + ' : ' + message ) } }) } else { // Other error, not 404 -- do not try to overwite the file complainIfBad(ok, 'FAILED to read results file: ' + body) } } else { // Happy read clearElement(naviMain) if (store.holds(subject, ns.rdf('type'), ns.wf('TemplateInstance'))) { showBootstrap(subject, naviMain, 'pad') } showResults(true) naviMiddle3.appendChild(newInstanceButton()) } }) } // Body of Pane const appPathSegment = 'app-pad.timbl.com' // how to allocate this string and connect to const fetcher = store.fetcher const updater = store.updater let me: any const PAD = Namespace('http://www.w3.org/ns/pim/pad#') const thisInstance = subject const padDoc = subject.doc() let padEle const div = dom.createElement('div') // Build the DOM const structure = div.appendChild(dom.createElement('table')) // @@ make responsive style structure.setAttribute( 'style', 'background-color: white; min-width: 94%; margin-right:3% margin-left: 3%; min-height: 13em;' ) const naviLoginoutTR = structure.appendChild(dom.createElement('tr')) naviLoginoutTR.appendChild(dom.createElement('td')) // naviLoginout1 naviLoginoutTR.appendChild(dom.createElement('td')) naviLoginoutTR.appendChild(dom.createElement('td')) const naviTop = structure.appendChild(dom.createElement('tr')) // stuff const naviMain = naviTop.appendChild(dom.createElement('td')) naviMain.setAttribute('colspan', '3') const naviMiddle = structure.appendChild(dom.createElement('tr')) // controls const naviMiddle1 = naviMiddle.appendChild(dom.createElement('td')) const naviMiddle2 = naviMiddle.appendChild(dom.createElement('td')) const naviMiddle3 = naviMiddle.appendChild(dom.createElement('td')) const naviStatus = structure.appendChild(dom.createElement('tr')) // status etc const statusArea = naviStatus.appendChild(dom.createElement('div')) const naviSpawn = structure.appendChild(dom.createElement('tr')) // create new const spawnArea = naviSpawn.appendChild(dom.createElement('div')) const naviMenu = structure.appendChild(dom.createElement('tr')) naviMenu.setAttribute('class', 'naviMenu') // naviMenu.setAttribute('style', 'margin-top: 3em;'); naviMenu.appendChild(dom.createElement('td')) // naviLeft naviMenu.appendChild(dom.createElement('td')) naviMenu.appendChild(dom.createElement('td')) const options: any = { statusArea: statusArea, timingArea: naviMiddle1 } loadPadData() return div } } // ends export default paneDef
the_stack
import * as path from "path"; import { snake } from "case"; import { Component } from "../component"; import { Project } from "../project"; import { YamlFile } from "../yaml"; import { Artifacts, Cache, Default, Image, Include, Job, Retry, Service, VariableConfig, Workflow, } from "./configuration-model"; /** * Options for `CiConfiguration`. */ export interface CiConfigurationOptions { /** * Default settings for the CI Configuration. Jobs that do not define one or more of the listed keywords use the value defined in the default section. */ readonly default?: Default; /** * A special job used to upload static sites to Gitlab pages. Requires a `public/` directory * with `artifacts.path` pointing to it. */ readonly pages?: Job; /** * Used to control pipeline behavior. */ readonly workflow?: Workflow; /** * Groups jobs into stages. All jobs in one stage must complete before next stage is * executed. If no stages are specified. Defaults to ['build', 'test', 'deploy']. */ readonly stages?: string[]; /** * Global variables that are passed to jobs. * If the job already has that variable defined, the job-level variable takes precedence. */ readonly variables?: Record<string, any>; /** * An initial set of jobs to add to the configuration. */ readonly jobs?: Record<string, Job>; } /** * CI for GitLab. * A CI is a configurable automated process made up of one or more stages/jobs. * @see https://docs.gitlab.com/ee/ci/yaml/ */ export class CiConfiguration extends Component { /** * The project the configuration belongs to. */ public readonly project: Project; /** * The name of the configuration. */ public readonly name: string; /** * Path to CI file generated by the configuration. */ public readonly path: string; /** * The workflow YAML file. */ public readonly file: YamlFile; /** * Defines default scripts that should run *after* all jobs. Can be overriden by the job level `afterScript`. */ public readonly defaultAfterScript: string[] = []; /** * Default list of files and directories that should be attached to the job if it succeeds. Artifacts are sent to Gitlab where they can be downloaded. */ public readonly defaultArtifacts?: Artifacts; /** * Defines default scripts that should run *before* all jobs. Can be overriden by the job level `afterScript`. */ public readonly defaultBeforeScript: string[] = []; /** * A default list of files and directories to cache between jobs. You can only use paths that are in the local working copy. */ public readonly defaultCache?: Cache; /** * Specifies the default docker image to use globally for all jobs. */ public readonly defaultImage?: Image; /** * The default behavior for whether a job should be canceled when a newer pipeline starts before the job completes (Default: false). */ public readonly defaultInterruptible?: boolean; /** * How many times a job is retried if it fails. If not defined, defaults to 0 and jobs do not retry. */ public readonly defaultRetry?: Retry; /** * A default list of additional Docker images to run scripts in. The service image is linked to the image specified in the image parameter. */ private defaultServices: Service[] = []; /** * Used to select a specific runner from the list of all runners that are available for the project. */ readonly defaultTags: string[] = []; /** * A default timeout job written in natural language (Ex. one hour, 3600 seconds, 60 minutes). */ readonly defaultTimeout?: string; /** * Can be `Include` or `Include[]`. Each `Include` will be a string, or an * object with properties for the method if including external YAML file. The external * content will be fetched, included and evaluated along the `.gitlab-ci.yml`. */ private include: Include[] = []; /** * A special job used to upload static sites to Gitlab pages. Requires a `public/` directory * with `artifacts.path` pointing to it. */ public readonly pages?: Job; /** * Groups jobs into stages. All jobs in one stage must complete before next stage is * executed. Defaults to ['build', 'test', 'deploy']. */ public readonly stages: string[] = []; /** * Global variables that are passed to jobs. * If the job already has that variable defined, the job-level variable takes precedence. */ public readonly variables: Record<string, number | VariableConfig | string> = {}; /** * Used to control pipeline behavior. */ public readonly workflow?: Workflow; /** * The jobs in the CI configuration. */ public readonly jobs: Record<string, Job> = {}; constructor( project: Project, name: string, options?: CiConfigurationOptions ) { super(project); this.project = project; this.name = path.parse(name).name; this.path = this.name === "gitlab-ci" ? ".gitlab-ci.yml" : `.gitlab/ci-templates/${name.toLocaleLowerCase()}.yml`; this.file = new YamlFile(this.project, this.path, { obj: () => this.renderCI(), }); const defaults = options?.default; if (defaults) { this.defaultAfterScript.push(...(defaults.afterScript ?? [])); this.defaultArtifacts = defaults.artifacts; defaults.beforeScript && this.defaultBeforeScript.push(...defaults.beforeScript); this.defaultCache = defaults.cache; this.defaultImage = defaults.image; this.defaultInterruptible = defaults.interruptible; this.defaultRetry = defaults.retry; defaults.services && this.addServices(...defaults.services); defaults.tags && this.defaultTags.push(...defaults.tags); this.defaultTimeout = defaults.timeout; } this.pages = options?.pages; this.workflow = options?.workflow; if (options?.stages) { this.addStages(...options.stages); } if (options?.variables) { this.addJobs(options.variables); } if (options?.jobs) { this.addJobs(options.jobs); } } /** * Add additional yml/yaml files to the CI includes * @param includes The includes to add. */ public addIncludes(...includes: Include[]) { for (const additional of includes) { this.assertIsValidInclude(additional); for (const existing of this.include) { if (this.areEqualIncludes(existing, additional)) { throw new Error( `${this.name}: GitLab CI ${existing} already contains one or more templates specified in ${additional}.` ); } } this.include.push(additional); } } /** * Throw an error if the provided Include is invalid. * @see https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/config/external/mapper.rb * @param include the Include to validate. */ private assertIsValidInclude(include: Include) { const combos = [ include.local, include.file && include.project, include.remote, include.template, ]; const len = combos.filter((x) => Boolean(x)).length; if (len !== 1) { throw new Error( `${this.name}: GitLab CI include ${include} contains ${len} property combination(s). A valid include configuration specifies *one* of the following property combinations. * local * file, project * remote * template ` ); } } /** * Check if the equality of Includes. * @see https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/config/external/mapper.rb * @param x First include to compare. * @param y Second include to compare. * @returns Whether the includes are equal. */ private areEqualIncludes(x: Include, y: Include): boolean { if (x.local === y.local && x.local !== undefined) { return true; } else if (x.template === y.template && x.template !== undefined) { return true; } else if (x.remote === y.remote && x.remote !== undefined) { return true; } else if (x.project === y.project && x.ref === y.ref) { const xFiles = x.file ? x.file : []; const yFiles = y.file ? y.file : []; const allFiles = xFiles.concat(yFiles); return new Set(allFiles).size !== allFiles.length; } return false; } /** * Add additional services. * @param services The services to add. */ public addServices(...services: Service[]) { for (const additional of services) { for (const existing of this.defaultServices) { if ( additional.name === existing.name && additional.alias === existing.alias ) { throw new Error( `${this.name}: GitLab CI already contains service ${additional}.` ); } } this.defaultServices.push(additional); } } /** * Add a globally defined variable to the CI configuration. * @param variables The variables to add. */ public addGlobalVariables(variables: Record<string, any>) { for (const [key, value] of Object.entries(variables)) { if (this.variables[key] !== undefined) { throw new Error( `${this.name}: GitLab CI already contains variable ${key}.` ); } this.variables[key] = value; } } /** * Add stages to the CI configuration if not already present. * @param stages stages to add. */ public addStages(...stages: string[]) { for (const stage of stages) { if (!this.stages.includes(stage)) { this.stages.push(stage); } } } /** * Add jobs and their stages to the CI configuration. * @param jobs Jobs to add. */ public addJobs(jobs: Record<string, Job>) { for (const [key, value] of Object.entries(jobs)) { if (this.jobs[key] !== undefined) { throw new Error(`${this.name}: GitLab CI already contains job ${key}.`); } this.jobs[key] = value; if (value.stage) { this.addStages(value.stage); } } } private renderCI() { return { default: this.renderDefault(), include: this.include.length > 0 ? snakeCaseKeys(this.include) : undefined, pages: snakeCaseKeys(this.pages), services: this.defaultServices.length > 0 ? snakeCaseKeys(this.defaultServices) : undefined, variables: Object.entries(this.variables).length > 0 ? this.variables : undefined, workflow: snakeCaseKeys(this.workflow), stages: this.stages.length > 0 ? this.stages : undefined, ...snakeCaseKeys(this.jobs), }; } private renderDefault() { const defaults: Default = { afterScript: this.defaultAfterScript.length > 0 ? this.defaultAfterScript : undefined, artifacts: this.defaultArtifacts, beforeScript: this.defaultBeforeScript.length > 0 ? this.defaultBeforeScript : undefined, cache: this.defaultCache, image: this.defaultImage, interruptible: this.defaultInterruptible, retry: this.defaultRetry, services: this.defaultServices.length > 0 ? this.defaultServices : undefined, tags: this.defaultTags.length > 0 ? this.defaultTags : undefined, timeout: this.defaultTimeout, }; return Object.values(defaults).filter((x) => x).length ? snakeCaseKeys(defaults) : undefined; } } function snakeCaseKeys<T = unknown>(obj: T): T { if (typeof obj !== "object" || obj == null) { return obj; } if (Array.isArray(obj)) { return obj.map(snakeCaseKeys) as any; } const result: Record<string, unknown> = {}; for (let [k, v] of Object.entries(obj)) { if (typeof v === "object" && v != null && k !== "variables") { v = snakeCaseKeys(v); } result[snake(k)] = v; } return result as any; }
the_stack
declare namespace Multiaddr { type Code = number; type Size = number; interface Protocol { code: Code; size: Size; name: string; resolvable: boolean; path: boolean; } interface Protocols { (proto: string | number): Protocol; readonly lengthPrefixedVarSize: number; readonly V: number; readonly table: Array<[number, number, string]>; readonly names: { [index: string]: Protocol }; readonly codes: { [index: number]: Protocol }; object(code: Code, size: Size, name: string, resolvable: boolean): Protocol; } interface Options { family: string; host: string; transport: string; port: string; } interface NodeAddress { family: string; address: string; port: string; } } interface Multiaddr { /** * The raw bytes representing this multiaddress */ readonly buffer: Buffer; /** * Returns Multiaddr as a String * * @example * Multiaddr('/ip4/127.0.0.1/tcp/4001').toString() * // '/ip4/127.0.0.1/tcp/4001' */ toString(): string; /** * Returns Multiaddr as a JSON encoded object * * @example * JSON.stringify(Multiaddr('/ip4/127.0.0.1/tcp/4001')) * // '/ip4/127.0.0.1/tcp/4001' */ toJSON(): string; /** * Returns Multiaddr as a convenient options object to be used with net.createConnection * * @example * Multiaddr('/ip4/127.0.0.1/tcp/4001').toOptions() * // { family: 'ipv4', host: '127.0.0.1', transport: 'tcp', port: 4001 } */ toOptions(): Multiaddr.Options; /** * Returns Multiaddr as a human-readable string * * @example * Multiaddr('/ip4/127.0.0.1/tcp/4001').inspect() * // '<Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001>' */ inspect(): string; /** * Returns the protocols the Multiaddr is defined with, as an array of objects, in * left-to-right order. Each object contains the protocol code, protocol name, * and the size of its address space in bits. * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv) * * @example * Multiaddr('/ip4/127.0.0.1/tcp/4001').protos() * // [ { code: 4, size: 32, name: 'ip4' }, * // { code: 6, size: 16, name: 'tcp' } ] */ protos(): Multiaddr.Protocol[]; /** * Returns the codes of the protocols in left-to-right order. * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv) * * @example * Multiaddr('/ip4/127.0.0.1/tcp/4001').protoCodes() * // [ 4, 6 ] */ protoCodes(): Multiaddr.Code[]; /** * Returns the names of the protocols in left-to-right order. * [See list of protocols](https://github.com/multiformats/multiaddr/blob/master/protocols.csv) * * @example * Multiaddr('/ip4/127.0.0.1/tcp/4001').protoNames() * // [ 'ip4', 'tcp' ] */ protoNames(): string[]; /** * Returns a tuple of parts * * @example * Multiaddr("/ip4/127.0.0.1/tcp/4001").tuples() * // [ [ 4, <Buffer 7f 00 00 01> ], [ 6, <Buffer 0f a1> ] ] */ tuples(): Array<[Multiaddr.Code, Buffer]>; /** * Returns a tuple of string/number parts * * @example * Multiaddr("/ip4/127.0.0.1/tcp/4001").stringTuples() * // [ [ 4, '127.0.0.1' ], [ 6, 4001 ] ] */ stringTuples(): Array<[Multiaddr.Code, string | number | undefined]>; /** * Encapsulates a Multiaddr in another Multiaddr * * @param addr - Multiaddr to add into this Multiaddr * @example * const mh1 = Multiaddr('/ip4/8.8.8.8/tcp/1080') * // <Multiaddr 0408080808060438 - /ip4/8.8.8.8/tcp/1080> * * const mh2 = Multiaddr('/ip4/127.0.0.1/tcp/4001') * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001> * * const mh3 = mh1.encapsulate(mh2) * // <Multiaddr 0408080808060438047f000001060fa1 - /ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001> * * mh3.toString() * // '/ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001' */ encapsulate(addr: string | Buffer | Multiaddr): Multiaddr; /** * Decapsulates a Multiaddr from another Multiaddr * * @param addr - Multiaddr to remove from this Multiaddr * @example * const mh1 = Multiaddr('/ip4/8.8.8.8/tcp/1080') * // <Multiaddr 0408080808060438 - /ip4/8.8.8.8/tcp/1080> * * const mh2 = Multiaddr('/ip4/127.0.0.1/tcp/4001') * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001> * * const mh3 = mh1.encapsulate(mh2) * // <Multiaddr 0408080808060438047f000001060fa1 - /ip4/8.8.8.8/tcp/1080/ip4/127.0.0.1/tcp/4001> * * mh3.decapsulate(mh2).toString() * // '/ip4/8.8.8.8/tcp/1080' */ decapsulate(addr: string | Buffer | Multiaddr): Multiaddr; /** * A more reliable version of `decapsulate` if you are targeting a * specific code, such as 421 (the `p2p` protocol code). The last index of the code * will be removed from the `Multiaddr`, and a new instance will be returned. * If the code is not present, the original `Multiaddr` is returned. * * @param code The code of the protocol to decapsulate from this Multiaddr * @example * const addr = Multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC') * // <Multiaddr 0400... - /ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC> * * addr.decapsulateCode(421).toString() * // '/ip4/0.0.0.0/tcp/8080' * * Multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString() * // '/ip4/127.0.0.1/tcp/8080' */ decapsulateCode(code: Multiaddr.Code): Multiaddr; /** * Extract the peerId if the multiaddr contains one * * @example * const mh1 = Multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string') * // <Multiaddr 0408080808060438 - /ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string> * * // should return QmValidBase58string or null if the id is missing or invalid * const peerId = mh1.getPeerId() */ getPeerId(): string | null; /** * Extract the path if the multiaddr contains one * * @example * const mh1 = Multiaddr('/ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock') * // <Multiaddr 0408080808060438 - /ip4/8.8.8.8/tcp/1080/unix/tmp/p2p.sock> * * // should return utf8 string or null if the id is missing or invalid * const path = mh1.getPath() */ getPath(): string | null; /** * Checks if two Multiaddrs are the same * * @example * const mh1 = Multiaddr('/ip4/8.8.8.8/tcp/1080') * // <Multiaddr 0408080808060438 - /ip4/8.8.8.8/tcp/1080> * * const mh2 = Multiaddr('/ip4/127.0.0.1/tcp/4001') * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001> * * mh1.equals(mh1) * // true * * mh1.equals(mh2) * // false */ equals(other: Multiaddr): boolean; /** * Gets a Multiaddrs node-friendly address object. Note that protocol information * is left out: in Node (and most network systems) the protocol is unknowable * given only the address. * * Has to be a ThinWaist Address, otherwise throws error * * @example * Multiaddr('/ip4/127.0.0.1/tcp/4001').nodeAddress() * // {family: 'IPv4', address: '127.0.0.1', port: '4001'} */ nodeAddress(): Multiaddr.NodeAddress; /** * Returns if a Multiaddr is a Thin Waist address or not. * * Thin Waist is if a Multiaddr adheres to the standard combination of: * * `{IPv4, IPv6}/{TCP, UDP}` * * @example * const mh1 = Multiaddr('/ip4/127.0.0.1/tcp/4001') * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001> * const mh2 = Multiaddr('/ip4/192.168.2.1/tcp/5001') * // <Multiaddr 04c0a80201061389 - /ip4/192.168.2.1/tcp/5001> * const mh3 = mh1.encapsulate(mh2) * // <Multiaddr 047f000001060fa104c0a80201061389 - /ip4/127.0.0.1/tcp/4001/ip4/192.168.2.1/tcp/5001> * mh1.isThinWaistAddress() * // true * mh2.isThinWaistAddress() * // true * mh3.isThinWaistAddress() * // false */ isThinWaistAddress(addr?: Multiaddr): boolean; } interface MultiaddrConstructor { /** * Creates a [multiaddr](https://github.com/multiformats/multiaddr) from * a Buffer, String or another Multiaddr instance * public key. * @param addr - If String or Buffer, needs to adhere * to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format) * @example * Multiaddr('/ip4/127.0.0.1/tcp/4001') * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001> */ new(addr?: string | Buffer | Multiaddr | null): Multiaddr; /** * Creates a [multiaddr](https://github.com/multiformats/multiaddr) from * a Buffer, String or another Multiaddr instance * public key. * @param addr - If String or Buffer, needs to adhere * to the address format of a [multiaddr](https://github.com/multiformats/multiaddr#string-format) * @example * Multiaddr('/ip4/127.0.0.1/tcp/4001') * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001> */ (addr?: string | Buffer | Multiaddr | null): Multiaddr; /** * Object containing table, names and codes of all supported protocols. * To get the protocol values from a Multiaddr, you can use * [`.protos()`](#multiaddrprotos), * [`.protoCodes()`](#multiaddrprotocodes) or * [`.protoNames()`](#multiaddrprotonames) * */ protocols: Multiaddr.Protocols; fromStupidString(str: string): never; /** * Creates a Multiaddr from a node-friendly address object * * @example * Multiaddr.fromNodeAddress({address: '127.0.0.1', port: '4001'}, 'tcp') * // <Multiaddr 047f000001060fa1 - /ip4/127.0.0.1/tcp/4001> */ fromNodeAddress(addr: Multiaddr.NodeAddress, transport: string): Multiaddr; /** * Returns if something is a Multiaddr */ isMultiaddr(addr: any): boolean; /** * Returns if something is a Multiaddr that is a name */ isName(name: any): boolean; /** * Returns an array of multiaddrs, by resolving the multiaddr that is a name */ resolve(value: any, cb: (error: Error) => void): Promise<void>; } declare const Multiaddr: MultiaddrConstructor; export = Multiaddr;
the_stack
import * as fs from "fs"; import * as path from "path"; import * as ejs from "ejs"; import { indent, ComposeWithOptions, trailingComma, normalizeProjectInput, Project, RelationTypes, RuntimeLogLevel, RuntimeLogLevels, PluginMetadata, PluginRegistration, RuntimeProps, RuntimeAdapter, Runtime, ProjectBuild, RuntimeAdapterProps, GeneratorProps, Datatypes, PrettifyOptions, RuntimeLogBehaviors, FileOverwriteBehaviors, FileSystemAdapter, RuntimeLogBehavior, FileOverwriteBehavior, ConfigurationValue, } from "@codotype/core"; import { RuntimeProxyAdapter } from "./utils/runtimeProxyAdapter"; import { runGenerator } from "./utils/runGenerator"; import { prettify } from "./utils/prettify"; import { OUTPUT_DIRECTORY, TEMPLATES_DIRECTORY_NAME, PLUGIN_METADATA_FILENAME, PLUGIN_DISTRIBUTABLE_DIR, } from "./constants"; import { getPluginPath } from "./utils/getPluginPath"; import { prepareProjectBuildDestination } from "./utils/prepareProjectBuildDestination"; import { logger } from "./utils/logger"; import { getAllFiles } from "./utils/getAllFiles"; import { handlePluginImportError, handleExecuteImportError, } from "./utils/handleErrors"; import { getComposeWithModulePath } from "./utils/getComposeWithModulePath"; // // // // interface TemplateData { plugin: PluginMetadata; project: Project; configuration: ConfigurationValue; RelationTypes: typeof RelationTypes; Datatypes: typeof Datatypes; helpers: { indent: (text: string, depth: number) => string; trailingComma: (arr: any[], index: number) => string; }; [key: string]: any; } /** * NodeRuntime * Runtime for running Codotype plugins through Node.js * NOTE - this is called `NodeRuntime` because we may support a non-Node.js runtime * in the future (i.e. DenoRuntime, BrowserRuntime, etc.) */ export class NodeRuntime implements Runtime { private plugins: PluginRegistration[]; private options: { cwd: string; fileSystemAdapter: FileSystemAdapter; logBehavior: RuntimeLogBehavior; fileOverwriteBehavior: FileOverwriteBehavior; }; /** * constructor * Instantiates a new NodeRuntime and returns it * @param options - see `RuntimeProps` */ constructor(options: RuntimeProps) { // Assigns this.options + default values this.options = { ...options, fileOverwriteBehavior: options.fileOverwriteBehavior || FileOverwriteBehaviors.force, logBehavior: options.logBehavior || RuntimeLogBehaviors.verbose, }; // Assigns this.plugins this.plugins = []; // Returns the runtime instance return this; } /** * registerPlugin * Registers an individual Codotype Plugin with the runtime * This allows the runtime to execute a Build against the registered Codotype Plugin * @param props - see `getPluginPath` function */ registerPlugin(props: { modulePath?: string; relativePath?: string; absolutePath?: string; }): Promise<PluginRegistration | null> { // Resolves path to Codotype Plugin const pluginPath: string = getPluginPath({ ...props, cwd: this.options.cwd, }); // Construct path to the generator module const pluginDynamicImportPath: string = path.join( pluginPath, PLUGIN_DISTRIBUTABLE_DIR, ); // Path to PluginMetadata const pluginMetadataImportPath: string = path.join( pluginPath, PLUGIN_DISTRIBUTABLE_DIR, PLUGIN_METADATA_FILENAME, ); // Debug pluginPath this.log(`registerPlugin - pluginPath: ${pluginPath}`, { level: RuntimeLogLevels.verbose, }); // Debug pluginDynamicImportPath this.log( `registerPlugin - pluginDynamicImportPath: ${pluginDynamicImportPath}`, { level: RuntimeLogLevels.verbose }, ); // Debug pluginMetadataImportPath this.log( `registerPlugin - pluginMetadataImportPath: ${pluginMetadataImportPath}`, { level: RuntimeLogLevels.verbose }, ); // Attempt to load up plugin import and metadata, catch error on failure try { // Import the the class dynamically // QUESTION - can these be done with `import`? const pluginDynamicImport = require(pluginDynamicImportPath); // eslint-disable-line import/no-dynamic-require const pluginMetadataImport = require(pluginMetadataImportPath); // eslint-disable-line import/no-dynamic-require // Destructures the default export into pluginMetadata const pluginMetadata: PluginMetadata = { ...pluginMetadataImport.default, }; // Add Codotype Plugin to this.plugins if import paths resolve correctly are met if (pluginDynamicImport && pluginMetadata) { // Defines the new PluginRegistration const newPluginRegistration: PluginRegistration = { id: pluginMetadata.identifier, pluginPath, pluginMetadata, pluginDynamicImportPath, }; // Tracks newPluginRegistration in this.plugins this.plugins.push(newPluginRegistration); // Logs successful registration message this.log( `Registered ${pluginMetadata.content.label} Codotype Plugin`, { level: RuntimeLogLevels.verbose, }, ); // Resolves the promise with the newPluginRegistration return Promise.resolve(newPluginRegistration); } } catch (err) { // Invoke handlePluginImportError and return result return handlePluginImportError(err, this.options.logBehavior); } // Includes default Promise resolution to prevent invariant error return Promise.resolve(null); } /** * ensureDir * Ensures presence of directory for template compilation * @param dir - the directory whose existance is being ensured */ ensureDir(dir: string): Promise<boolean> { return this.options.fileSystemAdapter.ensureDir(dir); } /** * getPlugins * Returns an array of PluginRegistration instances currently to this runtime instance */ getPlugins(): Promise<PluginRegistration[]> { return Promise.resolve(this.plugins); } /** * findPlugin * Finds a PluginRegistration based on PluginRegistration.id * @param pluginID - the ID of the Plugin that's being looked-up */ async findPlugin( pluginID: string, ): Promise<PluginRegistration | undefined> { // Gets array of PluginRegistrations from this.getPlugins() const plugins = await this.getPlugins(); // Finds the pluginRegistration associated with the ProjectBuild // FEATURE - check version here, use semver if possible const pluginRegistration: PluginRegistration | undefined = plugins.find( (g) => g.id === pluginID, ); // Returns Promise<PluginRegistration | undefined> return Promise.resolve(pluginRegistration); } /** * execute * Executes a single ProjectBuild against a Codotype Plugin * QUESTION - accept OUTPUT_DIRECTORY override here? * @param props.build - ProjectBuild */ async execute({ build }: { build: ProjectBuild }): Promise<void> { // Logs "Start Execution" statement this.log("NodeRuntime - start execute({ build })", { level: RuntimeLogLevels.verbose, }); // Pulls id, projectInput from build object let { id, projectInput } = build; // Inflates Project from ProjectInput const project: Project = normalizeProjectInput({ projectInput, }); // Provisions the output directory and writes the Codotype Project JSON to the output directory await prepareProjectBuildDestination({ build, runtime: this, cwd: this.options.cwd, }); // Performs lookup to gind Plugin based on ProjectInput.pluginID const pluginRegistration = await this.findPlugin(project.pluginID); // If pluginRegistration is not found -> log error message and short-circuit execution if (pluginRegistration === undefined) { // Logs error message this.log( "NodeRuntime.execute - Codotype Plugin not found. Please ensure that Codotype Plugin has been correctly registered with Runtime.registerPlugin", { level: RuntimeLogLevels.verbose }, ); // Resolves Promise<void> return Promise.resolve(); } // Pulls pluginDynamicImportPath from pluginRegistration const { pluginDynamicImportPath } = pluginRegistration; // Sets buildOutputDirectory default to build ID by default // NOTE - if `build.id` is an empty string, the project is placed directly inside OUTPUT_DIRECTORY const buildOutputDirectory: string = id || ""; // Constructs RuntimeAdapterProps.destinationPath const destinationPath: string = path.join( this.options.cwd, OUTPUT_DIRECTORY, buildOutputDirectory, project.identifiers.snake, ); // Attempt to load the Generator from pluginDynamicImportPath, handle error try { // Defines generator and it's associated absolute filepath for module resolution const generator: GeneratorProps = require(pluginDynamicImportPath); // eslint-disable-line import/no-dynamic-require const generatorResolvedPath: string = require.resolve( pluginDynamicImportPath, ); // Defines options for generator instance const runtimeAdapterProps: RuntimeAdapterProps = { project, destinationPath, generatorResolvedPath, plugin: pluginRegistration.pluginMetadata, runtime: this, }; // Log "Running Plugin Generator" statement this.log(`Running Plugin Generator: ${generator.name}`, { level: RuntimeLogLevels.verbose, }); // Creates RuntimeProxyAdapter instance const runtimeProxyAdapter = new RuntimeProxyAdapter( generator, runtimeAdapterProps, ); // Invokes runGenerator w/ Project + RuntimeProxyAdapter await runGenerator({ project, runtimeAdapter: runtimeProxyAdapter, }); } catch (err) { return handleExecuteImportError(err, this.options.logBehavior); } // Logs "Thank you" message this.log( "\nBuild complete\nThank you for using Codotype :)\nFollow us on github.com/codotype\n", { level: RuntimeLogLevels.verbose }, ); // Resolves with Promise<void> return Promise.resolve(); } /** * getTemplatePath * Generates the full path to a specific template file, relative to the filepath of the generator in-which the template is compiled * @param {string} generatorResolved * @param {string} template_path */ getTemplatePath( generatorResolvedPath: string, templateRelativePath: string, ): string { return path.join( generatorResolvedPath, TEMPLATES_DIRECTORY_NAME, templateRelativePath, ); } /** * getDestinationPath * Takes the destination name for a template and Generates */ getDestinationPath( outputDirAbsolutePath: string, destinationRelativePath: string, ): string { return path.join(outputDirAbsolutePath, destinationRelativePath); } /** * renderTemplate * Compiles an EJS template and returns the result * @param generatorInstance * @param src * @param options */ renderTemplate( generatorInstance: RuntimeAdapter, src: string, data?: { [key: string]: any }, options?: { prettify?: PrettifyOptions }, ): Promise<string> { return new Promise((resolve, reject) => { // default options padded into the renderFile let renderOptions = {}; // Defines data + options objects if none are passed in const dataObj: { [key: string]: any } = data || {}; const optionsObj: { prettify?: PrettifyOptions } = options || {}; // Pulls references to plugin + project from generatorInstance.props const { plugin, project } = generatorInstance.props; // Assembles the data object passed into each template file that that gets rendered const templateData: TemplateData = { plugin, project, configuration: generatorInstance.props.project.configuration, helpers: { indent, trailingComma, }, RelationTypes, Datatypes, ...dataObj, }; // Compiles EJS template return ejs.renderFile( src, templateData, renderOptions, (err, str) => { // Handles template compilation error if (err) return reject(err); // Prettify if desired if (optionsObj.prettify !== undefined) { str = prettify({ source: str, parser: optionsObj.prettify.parser, semi: optionsObj.prettify.semi, }); } // Resolves with compiled template return resolve(str); }, ); }); } /** * compareFile * Compares an existing file against a compiled template, returns true/false * @param destinationFilepath - the destination file being compared against compiledTemplate * @param compiledTemplate - the text being compared against the contents of the file at destinationFilepath */ async compareFile( destinationFilepath: string, compiledTemplate: string, ): Promise<boolean> { // Reads the file from FS const existingFile: | string | null = await this.options.fileSystemAdapter.readFile( destinationFilepath, ); // If exists, and it's the same, SKIP if (existingFile === null) { return Promise.resolve(false); } return Promise.resolve(compiledTemplate === existingFile); } /** * writeFile * Writes a compiled template to a file * @param dest - the destination where the compiledTemplate is being written * @param compiledTemplate - the text being written inside `dest` */ writeFile( dest: string, compiledTemplate: string, options?: { prettify?: PrettifyOptions; }, ): Promise<boolean> { let fileContents: string = compiledTemplate; // Run prettify against compiledTemplate if (options && options.prettify) { fileContents = prettify({ source: compiledTemplate, semi: options.prettify.semi, parser: options.prettify.parser, }); } return this.options.fileSystemAdapter.writeFile(dest, fileContents); } /** * copyDir * Copy a directory from src to dest * @param src - the name of the directory being copied inside the `templates` directory relative to the Codotype Generator invoking this method * @param dest - the name of the destination directory */ async copyDir(params: { src: string; dest: string }): Promise<boolean> { const { src, dest } = params; // CHORE - update allFiles to produce contents + destination pairs const allFiles = getAllFiles(src, []); for (const i in allFiles) { const sourcePath = allFiles[i]; let destPath: string | undefined = sourcePath .split(`/${TEMPLATES_DIRECTORY_NAME}/`) .pop(); if (destPath === undefined) { this.log("Runtime Error - destination path not found!", { level: RuntimeLogLevels.error, }); continue; } // Builds destination path destPath = path.resolve(dest, destPath); // Builds path to parent directory of destination // This is necessary to ensure that the parent directory has been created const destinationFragments = destPath.split("/"); destinationFragments.pop(); const destDirectoryPath = destinationFragments.join("/"); // Safely reads in file contents + create parent directory + write file try { const contents: string = fs.readFileSync(sourcePath, "utf8"); await this.options.fileSystemAdapter.ensureDir( destDirectoryPath, ); await this.options.fileSystemAdapter.writeFile( destPath, contents, ); } catch (e) { // Logs error message this.log( `Runtime Error: copyDir file not found: ${sourcePath}`, { level: RuntimeLogLevels.error, }, ); continue; } } // Resolves true return Promise.resolve(true); } copyFile(params: { src: string; dest: string }) { // Define values for src + dest const { src, dest } = params; // Read in file contents + write to destination const contents: string = fs.readFileSync(src, "utf8"); return this.options.fileSystemAdapter.writeFile(dest, contents); } /** * log * A logging function used internally by the Runtime * Invokes logger function with args, options, and Runtime.options.logLevel * @param args - see logger.ts */ log(args: any, options: { level: RuntimeLogLevel }) { logger(args, options, this.options.logBehavior); } /** * composeWith * Enables one generator to fire off several child generators * @param parentRuntimeAdapter * @param generatorModulePath * @param options - @see ComposeWithOptions */ async composeWith( parentRuntimeAdapter: RuntimeAdapter, generatorModulePath: string, options: ComposeWithOptions = {}, ): Promise<void> { // Log composeWith debug statement this.log(`Composing Generator: ${generatorModulePath}`, { level: RuntimeLogLevels.verbose, }); // Looks up actively-used Plugin const activePlugin = await this.findPlugin( parentRuntimeAdapter.props.plugin.identifier, ); if (activePlugin === undefined) { console.log("MODULE NOT FOUND"); throw new Error("NodeRuntime - composeWith - plugin not found"); } // Gets path to generator module using getComposeWithModulePath function const modulePath = getComposeWithModulePath( generatorModulePath, parentRuntimeAdapter, activePlugin, ); // Attempt to load the Generator from pluginDynamicImportPath, handle error try { // Defines generator and it's associated absolute filepath for module resolution const generator: GeneratorProps = require(modulePath); // eslint-disable-line import/no-dynamic-require const resolved: string = require.resolve(modulePath); // CHORE - document this, clean it all up // CHORE - move into independent function, `getResolvedGeneratorPath`, perhaps let resolvedGeneratorPath = resolved; let resolvedGeneratorPathParts = resolvedGeneratorPath.split("/"); resolvedGeneratorPathParts.pop(); resolvedGeneratorPath = resolvedGeneratorPathParts.join("/"); // Resolve the absoluate path to the destination directory for this generator let resolvedDestination = parentRuntimeAdapter.props.destinationPath; // Handle ComposeWithOptions.outputDirectoryScope // Scope the output of the composed Generator inside a different directory within OUTPUT_DIRECTORY/my_project if (options.outputDirectoryScope) { // Updates resolvedDestination to include the additional outputDirectoryScope resolvedDestination = path.resolve( parentRuntimeAdapter.props.destinationPath, options.outputDirectoryScope, ); } // Debug statements this.log( `Runtime.composeWith - resolvedDestination: ${resolvedDestination}`, { level: RuntimeLogLevels.verbose }, ); this.log( `Runtime.composeWith - resolvedGeneratorPath: ${resolvedGeneratorPath}`, { level: RuntimeLogLevels.verbose }, ); // // // // // Gets project from parentRuntimeAdapter.options const project = parentRuntimeAdapter.props.project; // Creates new CodotypeGenerator const runtimeProxyAdapter = new RuntimeProxyAdapter(generator, { ...parentRuntimeAdapter.props, destinationPath: resolvedDestination, generatorResolvedPath: resolvedGeneratorPath, }); // Invokes runGenerator w/ generatorInstance + project await runGenerator({ project, runtimeAdapter: runtimeProxyAdapter, }); // Logs output this.log(`Generated ${generator.name}.\n`, { level: RuntimeLogLevels.info, }); } catch (err) { return handleExecuteImportError(err, this.options.logBehavior); } } /** * writeTemplateToFile * Compiles a template and writes to the dest location * @param runtimeAdapter * @param src * @param dest * @param options */ writeTemplateToFile( runtimeAdapter: RuntimeAdapter, src: string, dest: string, data: object = {}, options: object = {}, ): Promise<boolean> { // DEBUG // console.log('Copying:' + dest) return new Promise(async (resolve, reject) => { // DEBUG // this.log('Rendering:' + dest) // Compiles the template through CodotypeRuntime.renderTemplate const compiledTemplate: string = await this.renderTemplate( runtimeAdapter, src, data, options, ); // DEBUG // this.log('Rendered:' + dest) // // // // // FEATURE - re-introduce based on FileOverwriteBehavior // // Does the destination already exist? // const exists = await this.options.fileSystemAdapter.fileExists( // dest, // ); // // If it doesn't exist, OKAY TO WRITE // if (exists) { // console.log("EXISTS"); // if (this.compareFile(dest, compiledTemplate)) { // return resolve(); // } else { // // NOTE - input checking will vary depending on environment // // If exists, and it's different, WRITE (add PROMPT option later, for safety) // } // } // // // // // Writes the compiled template to the dest location return this.writeFile(dest, compiledTemplate).then(() => { return resolve(); }); }); } }
the_stack
/// <reference path="../../elements.d.ts" /> import { MonacoEditor, MonacoEditorScriptMetaMods } from '../../options/editpages/monaco-editor/monaco-editor'; import { Polymer } from '../../../../tools/definitions/polymer'; import { I18NKeys } from '../../../_locales/i18n-keys'; declare const browserAPI: browserAPI; declare const BrowserAPI: BrowserAPI; namespace InstallConfirmElement { export const installConfirmProperties: { script: string; permissions: CRM.Permission[]; } = { script: { type: String, notify: true, value: '' }, permissions: { type: Array, notify: true, value: [] } } as any; export class IC { static is: string = 'install-confirm'; /** * The synced settings of the app */ private static _settings: CRM.SettingsStorage; /** * The metatags for the script */ private static _metaTags: CRM.MetaTags = {}; /** * The manager for the main code editor */ private static _editorManager: MonacoEditor; static properties = installConfirmProperties; static lengthIs(this: InstallConfirm, arr: any[], length: number): boolean { if (arr.length === 1 && arr[0] === 'none') { return length === 0; } return arr.length === length; } private static _getCheckboxes(this: InstallConfirm): HTMLPaperCheckboxElement[] { return Array.prototype.slice.apply(this.shadowRoot.querySelectorAll('paper-checkbox')); } private static _setChecked(this: InstallConfirm, checked: boolean) { this._getCheckboxes().forEach((checkbox) => { checkbox.checked = checked; }); } static toggleAll(this: InstallConfirm) { this.async(() => { this._setChecked(this.$.permissionsToggleAll.checked); }, 0); } private static _createArray(this: InstallConfirm, length: number): void[] { const arr = []; for (let i = 0; i < length; i++) { arr[i] = undefined; } return arr; } private static async _loadSettings(this: InstallConfirm) { return new Promise(async (resolve) => { const local: CRM.StorageLocal & { settings?: CRM.SettingsStorage; } = await browserAPI.storage.local.get() as any; if (local.useStorageSync && 'sync' in BrowserAPI.getSrc().storage && 'get' in BrowserAPI.getSrc().storage.sync) { //Parse the data before sending it to the callback const storageSync: { [key: string]: string } & { indexes: number|string[]; } = await browserAPI.storage.sync.get() as any; let indexes = storageSync.indexes; if (indexes === null || indexes === -1 || indexes === undefined) { browserAPI.storage.local.set({ useStorageSync: false }); this._settings = local.settings; } else { const settingsJsonArray: string[] = []; const indexesLength = typeof indexes === 'number' ? indexes : (Array.isArray(indexes) ? indexes.length : 0); this._createArray(indexesLength).forEach((_, index) => { settingsJsonArray.push(storageSync[`section${index}`]); }); const jsonString = settingsJsonArray.join(''); this._settings = JSON.parse(jsonString); } } else { //Send the "settings" object on the storage.local to the callback if (!local.settings) { browserAPI.storage.local.set({ useStorageSync: true }); const storageSync: { [key: string]: string } & { indexes: string[]|number; } = await browserAPI.storage.sync.get() as any; const indexes = storageSync.indexes; const settingsJsonArray: string[] = []; const indexesLength = typeof indexes === 'number' ? indexes : (Array.isArray(indexes) ? indexes.length : 0); this._createArray(indexesLength).forEach((_, index) => { settingsJsonArray.push(storageSync[`section${index}`]); }); const jsonString = settingsJsonArray.join(''); this._settings = JSON.parse(jsonString); } else { this._settings = local.settings; } } resolve(null); }); }; static getDescription(this: InstallConfirm, permission: CRM.Permission): string { const descriptions = { alarms: this.___(I18NKeys.permissions.alarms), activeTab: this.___(I18NKeys.permissions.activeTab), background: this.___(I18NKeys.permissions.background), bookmarks: this.___(I18NKeys.permissions.bookmarks), browsingData: this.___(I18NKeys.permissions.browsingData), clipboardRead: this.___(I18NKeys.permissions.clipboardRead), clipboardWrite: this.___(I18NKeys.permissions.clipboardWrite), cookies: this.___(I18NKeys.permissions.cookies), contentSettings: this.___(I18NKeys.permissions.contentSettings), contextMenus: this.___(I18NKeys.permissions.contextMenus), declarativeContent: this.___(I18NKeys.permissions.declarativeContent), desktopCapture: this.___(I18NKeys.permissions.desktopCapture), downloads: this.___(I18NKeys.permissions.downloads), history: this.___(I18NKeys.permissions.history), identity: this.___(I18NKeys.permissions.identity), idle: this.___(I18NKeys.permissions.idle), management: this.___(I18NKeys.permissions.management), notifications: this.___(I18NKeys.permissions.notifications), pageCapture: this.___(I18NKeys.permissions.pageCapture), power: this.___(I18NKeys.permissions.power), privacy: this.___(I18NKeys.permissions.privacy), printerProvider: this.___(I18NKeys.permissions.printerProvider), sessions: this.___(I18NKeys.permissions.sessions), "system.cpu": this.___(I18NKeys.permissions.systemcpu), "system.memory": this.___(I18NKeys.permissions.systemmemory), "system.storage": this.___(I18NKeys.permissions.systemstorage), topSites: this.___(I18NKeys.permissions.topSites), tabCapture: this.___(I18NKeys.permissions.tabCapture), tabs: this.___(I18NKeys.permissions.tabs), tts: this.___(I18NKeys.permissions.tts), webNavigation: this.___(I18NKeys.permissions.webNavigation) + ' (https://developer.chrome.com/extensions/webNavigation)', webRequest: this.___(I18NKeys.permissions.webRequest), webRequestBlocking: this.___(I18NKeys.permissions.webRequestBlocking), //Script-specific descriptions crmGet: this.___(I18NKeys.permissions.crmGet), crmWrite: this.___(I18NKeys.permissions.crmWrite), crmRun: this.___(I18NKeys.permissions.crmRun), crmContextmenu: this.___(I18NKeys.permissions.crmContextmenu), chrome: this.___(I18NKeys.permissions.chrome), browser: this.___(I18NKeys.permissions.browser), //Tampermonkey APIs GM_addStyle: this.___(I18NKeys.permissions.GMAddStyle), GM_deleteValue: this.___(I18NKeys.permissions.GMDeleteValue), GM_listValues: this.___(I18NKeys.permissions.GMListValues), GM_addValueChangeListener: this.___(I18NKeys.permissions.GMAddValueChangeListener), GM_removeValueChangeListener: this.___(I18NKeys.permissions.GMRemoveValueChangeListener), GM_setValue: this.___(I18NKeys.permissions.GMSetValue), GM_getValue: this.___(I18NKeys.permissions.GMGetValue), GM_log: this.___(I18NKeys.permissions.GMLog), GM_getResourceText: this.___(I18NKeys.permissions.GMGetResourceText), GM_getResourceURL: this.___(I18NKeys.permissions.GMGetResourceURL), GM_registerMenuCommand: this.___(I18NKeys.permissions.GMRegisterMenuCommand), GM_unregisterMenuCommand: this.___(I18NKeys.permissions.GMUnregisterMenuCommand), GM_openInTab: this.___(I18NKeys.permissions.GMOpenInTab), GM_xmlhttpRequest: this.___(I18NKeys.permissions.GMXmlhttpRequest), GM_download: this.___(I18NKeys.permissions.GMDownload), GM_getTab: this.___(I18NKeys.permissions.GMGetTab), GM_saveTab: this.___(I18NKeys.permissions.GMSaveTab), GM_getTabs: this.___(I18NKeys.permissions.GMGetTabs), GM_notification: this.___(I18NKeys.permissions.GMNotification), GM_setClipboard: this.___(I18NKeys.permissions.GMSetClipboard), GM_info: this.___(I18NKeys.permissions.GMInfo), unsafeWindow: this.___(I18NKeys.permissions.unsafeWindow) }; return descriptions[permission as keyof typeof descriptions]; }; static showPermissionDescription(this: InstallConfirm, e: Polymer.ClickEvent) { let el = e.target; if (el.tagName.toLowerCase() === 'div') { el = el.children[0] as HTMLElement; } else if (el.tagName.toLowerCase() === 'path') { el = el.parentElement; } const children = el.parentElement.parentElement.parentElement.children; const description = children[children.length - 1]; if (el.classList.contains('shown')) { $(description).stop().animate({ height: 0 }, { duration: 250, complete: () => { window.installConfirm._editorManager.editor.layout(); } }); } else { $(description).stop().animate({ height: (description.scrollHeight + 7) + 'px' }, { duration: 250, complete: () => { window.installConfirm._editorManager.editor.layout(); } }); } el.classList.toggle('shown'); }; private static _isManifestPermissions(this: InstallConfirm, permission: CRM.Permission): boolean { const permissions = [ 'alarms', 'activeTab', 'background', 'bookmarks', 'browsingData', 'clipboardRead', 'clipboardWrite', 'contentSettings', 'cookies', 'contentSettings', 'contextMenus', 'declarativeContent', 'desktopCapture', 'downloads', 'history', 'identity', 'idle', 'management', 'pageCapture', 'power', 'privacy', 'printerProvider', 'sessions', 'system.cpu', 'system.memory', 'system.storage', 'topSites', 'tabs', 'tabCapture', 'tts', 'webNavigation', 'webRequest', 'webRequestBlocking' ]; return permissions.indexOf(permission) > -1; }; static async checkPermission(this: InstallConfirm, e: Polymer.ClickEvent) { let el = e.target; while (el.tagName.toLowerCase() !== 'paper-checkbox') { el = el.parentElement; } const checkbox = el as HTMLPaperCheckboxElement; if (checkbox.checked) { const permission = checkbox.getAttribute('permission'); if (this._isManifestPermissions(permission as CRM.Permission)) { const { permissions } = browserAPI.permissions ? await browserAPI.permissions.getAll() : { permissions: [] }; if (permissions.indexOf(permission as _browser.permissions.Permission) === -1) { try { if (!(browserAPI.permissions)) { window.app.util.showToast(this.___(I18NKeys.install.confirm.notAsking, permission)); return; } const granted = await browserAPI.permissions.request({ permissions: [permission as _browser.permissions.Permission] }); if (!granted) { checkbox.checked = false; } } catch (e) { //Is not a valid requestable permission } } } } }; static cancelInstall(this: InstallConfirm) { window.close(); }; static completeInstall(this: InstallConfirm) { const allowedPermissions: CRM.Permission[] = []; this._getCheckboxes().forEach((checkbox) => { checkbox.checked && allowedPermissions.push(checkbox.getAttribute('permission') as CRM.Permission); }); browserAPI.runtime.sendMessage({ type: 'installUserScript', data: { metaTags: this._metaTags, script: this.script, downloadURL: window.installPage.getInstallSource(), allowedPermissions: allowedPermissions } }); this.$.installButtons.classList.add('installed'); this.$.scriptInstalled.classList.add('visible'); }; static acceptAndCompleteInstall(this: InstallConfirm) { this._setChecked(true); this.$.permissionsToggleAll.checked = true; this.async(() => { this.completeInstall(); }, 250); } private static _setMetaTag(this: InstallConfirm, name: keyof ModuleMap['install-confirm'], values: (string|number)[]) { let value; if (values) { value = values[values.length - 1]; } else { value = '-'; } this.$[name].innerText = value + ''; }; private static _setMetaInformation(this: InstallConfirm, tags: CRM.MetaTags) { this._setMetaTag('descriptionValue', tags['description']); this._setMetaTag('authorValue', tags['author']); window.installPage.$.title.innerHTML = `Installing <b>${(tags['name'] && tags['name'][0])}</b>`; this.$.sourceValue.innerText = window.installPage.userscriptUrl; const permissions = tags['grant'] as CRM.Permission[]; this.permissions = permissions; this._metaTags = tags; this._editorManager.editor.layout(); }; private static _editorLoaded(this: InstallConfirm, editor: MonacoEditor) { const el = document.createElement('style'); el.id = 'editorZoomStyle'; el.innerText = `.CodeMirror, .CodeMirror-focused { font-size: ${1.25 * ~~window.installConfirm._settings.editor.zoom}'%!important; }`; //Show info about the script, if available const interval = window.setInterval( () => { const typeHandler = (editor.getTypeHandler()[0] as MonacoEditorScriptMetaMods); if (typeHandler.getMetaBlock) { window.clearInterval(interval); const metaBlock = typeHandler.getMetaBlock(); if (metaBlock && metaBlock.content) { this._setMetaInformation(metaBlock.content); } } }, 25); }; private static async _loadEditor(this: InstallConfirm) { !this._settings.editor && (this._settings.editor = { theme: 'dark', zoom: '100', keyBindings: { goToDef: 'Ctrl-F12', rename: 'Ctrl-F2' }, cssUnderlineDisabled: false, disabledMetaDataHighlight: false }); const editorManager = this._editorManager = await this.$.editorCont.create(this.$.editorCont.EditorMode.JS_META, { value: this.script, language: 'javascript', theme: this._settings.editor.theme === 'dark' ? 'vs-dark' : 'vs', wordWrap: 'off', readOnly: true, fontSize: (~~this._settings.editor.zoom / 100) * 14, folding: true }); window.addEventListener('resize', () => { editorManager.editor.layout(); }); this._editorLoaded(editorManager); }; static ready(this: InstallConfirm) { this._loadSettings().then(() => { this._loadEditor(); }); window.installConfirm = this; } } if (window.objectify) { window.register(IC); } else { window.addEventListener('RegisterReady', () => { window.register(IC); }); } } export type InstallConfirm = Polymer.El<'install-confirm', typeof InstallConfirmElement.IC & typeof InstallConfirmElement.installConfirmProperties>;
the_stack
import contract = require('truffle-contract'); import { W3 } from './'; import SolidityCoder = require('web3/lib/solidity/coder.js'); /** * Base contract for all Soltsice contracts */ export class SoltsiceContract { public static silent: boolean = false; public transactionHash: Promise<string>; public w3: W3; protected _Contract: any; /** Truffle-contract instance. Use it if Soltsice doesn't support some features yet */ protected _instance: any; protected _instancePromise: Promise<any>; protected _sendParams: W3.TX.TxParams; protected static newDataImpl(w3?: W3, tokenArtifacts?: any, constructorParams?: W3.TX.ContractDataType[]): string { if (!w3) { w3 = W3.default; } let ct = w3.web3.eth.contract(tokenArtifacts.abi); let data = ct.new.getData(...constructorParams!, { data: tokenArtifacts.bytecode }); return data; } protected constructor( web3?: W3, tokenArtifacts?: any, constructorParams?: W3.TX.ContractDataType[], deploymentParams?: string | W3.TX.TxParams | object, link?: SoltsiceContract[] ) { if (!web3) { web3 = W3.default; } this.w3 = web3; if ( typeof deploymentParams === 'string' && deploymentParams !== '' && !W3.isValidAddress(deploymentParams as string) ) { throw 'Invalid deployed contract address'; } this._Contract = contract(tokenArtifacts); this._Contract.setProvider(web3.currentProvider); function instanceOfTxParams(obj: any): obj is W3.TX.TxParams { return 'from' in obj && 'gas' in obj && 'gasPrice' in obj && 'value' in obj; } let linkage = new Promise<any>(async (resolve, reject) => { if (link && link.length > 0) { let network = +(await this.w3.networkId); this._Contract.setNetwork(network); link.forEach(async element => { let inst = await element._instancePromise; this._Contract.link(element._Contract.contractName, inst.address); }); resolve(true); } else { resolve(true); } }); let instance = new Promise<any>(async (resolve, reject) => { await linkage; if (this.w3.defaultAccount) { this._sendParams = W3.TX.txParamsDefaultSend(this.w3.defaultAccount); if ((await this.w3.networkId) !== '1') { this._sendParams.gasPrice = 20000000000; // 20 Gwei, tests are too slow with the 2 Gwei default one } } let useDeployed = async () => { let network = +(await this.w3.networkId); this._Contract.setNetwork(network); this._Contract .deployed() .then(inst => { this.transactionHash = inst.transactionHash; if (!SoltsiceContract.silent) { console.log('SOLTSICE: USING DEPLOYED CONTRACT', this.constructor.name, ' at ', deploymentParams!); } resolve(inst); }) .catch(err => { reject(err); }); }; let useExisting = (address: string) => { if (!SoltsiceContract.silent) { console.log('SOLTSICE: USING EXISTING CONTRACT', this.constructor.name, ' at ', deploymentParams!); } this._Contract .at(address) .then(inst => { this.transactionHash = inst.transactionHash; resolve(inst); }) .catch(err => { reject(err); }); }; if (!deploymentParams) { useDeployed(); } else if (typeof deploymentParams === 'string') { useExisting(deploymentParams!); } else if (instanceOfTxParams(deploymentParams)) { this._Contract .new(...constructorParams!, deploymentParams) .then(inst => { if (!SoltsiceContract.silent) { console.log('SOLTSICE: DEPLOYED NEW CONTRACT ', this.constructor.name, ' at ', inst.address); } this.transactionHash = inst.transactionHash; resolve(inst); }) .catch(err => { reject(err); }); } else if ((<any>deploymentParams).address && typeof (<any>deploymentParams).address === 'string') { // support any object with address property useExisting((<any>deploymentParams).address); } }); this._instancePromise = instance.then(i => { this._instance = i; return i; }); } public get address(): string { return this._instance.address; } public get instance(): any { return this._instance; } /** Default tx params for sending transactions. */ public get sendTxParams() { return this._sendParams; } /** Send a transaction to the fallback function */ public async sendTransaction(txParams?: W3.TX.TxParams): Promise<W3.TX.TransactionResult> { txParams = txParams || this._sendParams; if (!txParams) { throw new Error('Default tx parameters are not set.'); } let instance = await this.instance; return instance.sendTransaction(txParams); } public async parseLogs(logs: W3.Log[]): Promise<W3.Log[]> { let web3 = this.w3; let inst = await this.instance; let abi = inst.abi; return logs! .map(log => { let logABI: any = null; for (let i = 0; i < abi.length; i++) { let item = abi[i]; if (item.type !== 'event') { continue; } // tslint:disable-next-line:max-line-length let signature = item.name + '(' + item.inputs .map(function(input: any) { return input.type; }) .join(',') + ')'; let hash = this.w3.web3.sha3(signature); if (hash === log.topics![0]) { logABI = item; break; } } if (logABI != null) { // Adapted from truffle-contract let copy = Object.assign({}, log); let decode = (fullABI, indexed, data) => { let _inputs = fullABI.inputs.filter(function(input: any) { return input.indexed === indexed; }); let partial = { inputs: _inputs, name: fullABI.name, type: fullABI.type, anonymous: fullABI.anonymous }; let types = partial.inputs.map(x => x.type); let params = SolidityCoder.decodeParams(types, data); let temp = {}; for (let index = 0; index < _inputs.length; index++) { temp[_inputs[index].name] = params[index]; } return temp; }; let argTopics = logABI.anonymous ? copy.topics : copy.topics!.slice(1); let indexedData = argTopics! .map(function(topics: string) { return topics.slice(2); }) .join(''); // tslint:disable-next-line:max-line-length let indexedParams = decode(logABI, true, indexedData); let notIndexedData = copy.data!.replace('0x', ''); // tslint:disable-next-line:max-line-length let notIndexedParams = decode(logABI, false, notIndexedData); copy.event = logABI.name; copy.args = logABI.inputs.reduce(function(acc: any, current: any) { let val = indexedParams[current.name]; if (val === undefined) { val = notIndexedParams[current.name]; } acc[current.name] = val; return acc; }, {}); Object.keys(copy.args).forEach(function(key: any) { let val = copy.args[key]; // We have BN. Convert it to BigNumber if (val.constructor.isBN) { copy.args[key] = web3.toBigNumber('0x' + val.toString(16)); } }); delete copy.data; delete copy.topics; return copy; } else { return undefined; } }) .filter(d => d) as W3.Log[]; } public async parseReceipt(receipt: W3.TransactionReceipt): Promise<W3.Log[]> { if (!receipt.logs) { return []; } return this.parseLogs(receipt.logs); } /** Get transaction result by hash. Returns receipt + parsed logs. */ public getTransactionResult(txHash: string): Promise<W3.TX.TransactionResult> { return new Promise<W3.TX.TransactionResult>((resolve, reject) => { this.w3.web3.eth.getTransactionReceipt(txHash, async (err, receipt) => { if (err) { reject(err); } else { if (!receipt) { reject('Receipt is falsy, transaction does not exists or was not mined yet.'); } else { try { let result: W3.TX.TransactionResult = {} as W3.TX.TransactionResult; result.tx = receipt.transactionHash; result.receipt = receipt; result.logs = await this.parseReceipt(receipt); resolve(result); } catch (e) { reject({ error: e, description: 'Unhandled exception' }); } } } }); }); } public async waitTransactionReceipt(hashString: string): Promise<W3.TX.TransactionResult> { return new Promise<W3.TX.TransactionResult>((accept, reject) => { var timeout = 240000; var start = new Date().getTime(); let makeAttempt = () => { this.w3.web3.eth.getTransactionReceipt(hashString, async (err, receipt) => { if (err) { return reject(err); } if (receipt != null) { try { let result: W3.TX.TransactionResult = {} as W3.TX.TransactionResult; result.tx = receipt.transactionHash; result.receipt = receipt; result.logs = await this.parseReceipt(receipt); accept(result); } catch (e) { reject({ error: e, description: 'Unhandled exception' }); } } if (timeout > 0 && new Date().getTime() - start > timeout) { return reject( new Error('Transaction ' + hashString + " wasn't processed in " + timeout / 1000 + ' seconds!') ); } setTimeout(makeAttempt, 1000); }); }; makeAttempt(); }); } public async newFilter(fromBlock: number, toBlock?: number): Promise<number> { let toBlock1 = toBlock ? this.w3.fromDecimal(toBlock) : 'latest'; const id = 'W3:' + W3.getNextCounter(); let filter = await this.w3 .sendRPC({ jsonrpc: '2.0', method: 'eth_newFilter', params: [ { fromBlock: this.w3.fromDecimal(fromBlock), toBlock: toBlock1, address: await this.address } ], id: id }) .then(async r => { if (r.error) { throw 'Cannot set filter'; } return r.result as number; }); return this.w3.toBigNumber(filter).toNumber(); // filter } public async uninstallFilter(filter: number): Promise<boolean> { const id = 'W3:' + W3.getNextCounter(); let ret = await this.w3 .sendRPC({ jsonrpc: '2.0', method: 'eth_uninstallFilter', params: [this.w3.fromDecimal(filter)], id: id }) .then(async r => { if (r.error) { throw 'Cannot uninstall filter'; } return r.result as boolean; }); return ret; } public async getFilterChanges(filter: number): Promise<W3.Log[]> { const id = 'W3:' + W3.getNextCounter(); let logs = this.w3 .sendRPC({ jsonrpc: '2.0', method: 'eth_getFilterChanges', params: [this.w3.fromDecimal(filter)], id: id }) .then(async r => { if (r.error) { console.log('FILTER ERR: ', r); return []; } console.log('FILTER: ', r); let parsed = await this.parseLogs(r.result as W3.Log[]); return parsed; }); return logs; } public async getFilterLogs(filter: number): Promise<W3.Log[]> { const id = 'W3:' + W3.getNextCounter(); let logs = this.w3 .sendRPC({ jsonrpc: '2.0', method: 'eth_getFilterLogs', params: [this.w3.fromDecimal(filter)], id: id }) .then(async r => { if (r.error) { return []; } let parsed = await this.parseLogs(r.result as W3.Log[]); return parsed; }); return logs; } public async getLogs(fromBlock: number, toBlock?: number): Promise<W3.Log[]> { let toBlock1 = toBlock ? this.w3.fromDecimal(toBlock) : 'latest'; return new Promise<W3.Log[]>(async (resolve, reject) => { (await this.instance).allEvents({ fromBlock: fromBlock, toBlock: toBlock1 }).get((error, log) => { if (error) { reject(error); } resolve(log); }); }); } }
the_stack
import type { IParser } from '@yozora/core-parser' import invariant from '@yozora/invariant' import fs from 'fs-extra' import globby from 'globby' import path from 'path' import type { ITokenizerUseCase, ITokenizerUseCaseGroup } from './types' /** * Params for construct TokenizerTester */ export interface ITokenizerTesterProps { /** * Root directory of the use cases located */ caseRootDirectory: string /** * Parser */ parser: IParser } export class TokenizerTester<T = unknown> { public readonly parser: IParser protected readonly caseRootDirectory: string protected readonly formattedCaseRootDirectory: string protected readonly caseGroups: Array<ITokenizerUseCaseGroup<T>> protected readonly visitedFilepathSet: Set<string> constructor(props: ITokenizerTesterProps) { const { caseRootDirectory, parser } = props this.parser = parser this.caseRootDirectory = path.normalize(caseRootDirectory) this.formattedCaseRootDirectory = this._formatDirpath(caseRootDirectory) this.caseGroups = [] this.visitedFilepathSet = new Set<string>() } /** * Get the list of TestCaseGroup */ public collect(): Array<ITokenizerUseCaseGroup<T>> { return this.caseGroups.slice() } public reset(): this { this.caseGroups.splice(0, this.caseGroups.length) this.visitedFilepathSet.clear() return this } /** * Scan filepath for generating use-case group * * @param patterns glob patterns * @param isDesiredFilepath test whether a filepath is desired */ public scan( patterns: string | string[], caseRootDirectory = this.caseRootDirectory, isDesiredFilepath: (filepath: string) => boolean = () => true, ): this { const filepaths: string[] = globby .sync(patterns, { cwd: caseRootDirectory, absolute: true, onlyDirectories: false, onlyFiles: true, markDirectories: true, unique: true, braceExpansion: true, caseSensitiveMatch: true, dot: true, extglob: true, globstar: true, objectMode: false, stats: false, }) .sort() for (const filepath of filepaths) { if (!isDesiredFilepath(filepath)) continue this._scanForUseCaseGroup(filepath) } return this } /** * Create answers for all use cases */ public runAnswer(): Promise<void | void[]> { const answerUseCaseGroup = async ( parentDir: string, caseGroup: ITokenizerUseCaseGroup<T>, ): Promise<void> => { if (caseGroup.dirpath === caseGroup.filepath) { // Test sub groups for (const subGroup of caseGroup.subGroups) { await answerUseCaseGroup(caseGroup.dirpath, subGroup) } return } const result = { title: caseGroup.title || caseGroup.dirpath.slice(parentDir.length), cases: caseGroup.cases.map(c => ({ ...c, ...this._answerCase(c, caseGroup.filepath), })), } const content = this.stringify(result) await fs.writeFile(caseGroup.filepath, content, 'utf-8') } // Generate answers const tasks: Array<Promise<void>> = [] for (const caseGroup of this.collect()) { const task = answerUseCaseGroup(this.formattedCaseRootDirectory, caseGroup) tasks.push(task) } // Wait all tasks completed return Promise.all(tasks) } /** * Run all use cases */ public runTest(): void { const testUseCaseGroup = (parentDir: string, caseGroup: ITokenizerUseCaseGroup<T>): void => { const self = this const title = caseGroup.title || caseGroup.dirpath.slice(parentDir.length) describe(title, function () { // Test current group use cases for (const kase of caseGroup.cases) { self._testCase(kase, caseGroup.filepath) } // Test sub groups for (const subGroup of caseGroup.subGroups) { testUseCaseGroup(caseGroup.dirpath, subGroup) } }) } // Run test for (const caseGroup of this.collect()) { testUseCaseGroup(this.formattedCaseRootDirectory, caseGroup) } } /** * Format result data before saved to file * @param data */ public stringify(data: unknown): string { const filter = (key: string, value: unknown): unknown => { if (value instanceof RegExp) return value.source return value } return JSON.stringify(data, filter, 2) } /** * Format data * @param data */ public format<T = unknown>(data: T): Partial<T> { const stringified = JSON.stringify(data, (key: string, val: any) => { if (val && val.type && val.position) { const { type, position, ...restData } = val return { type, position, ...restData } } switch (key) { default: return val } }) return JSON.parse(stringified) } /** * Print filepath info when the handling failed * * @param filepath * @param fn */ public trackHandle<T = unknown>(filepath: string, fn: () => T): T { try { const result = fn() return result } catch (error) { console.error(`[handle failed] ${filepath}`) throw error } } /** * Extract ITokenizerUseCaseGroup from json file that holds the content of * the use case * * @param filepath absolute filepath of json file */ protected _scanForUseCaseGroup(filepath: string): void { // Avoid duplicated scan if (this.visitedFilepathSet.has(filepath)) { console.warn(`[scan] ${filepath} has been scanned`) return } this.visitedFilepathSet.add(filepath) const data = fs.readJSONSync(filepath) const cases: Array<ITokenizerUseCase<T>> = (data.cases || []).map( (c: ITokenizerUseCase<T>, index: number): ITokenizerUseCase<T> => ({ description: c.description || 'case#' + index, input: c.input, htmlAnswer: c.htmlAnswer, parseAnswer: c.parseAnswer, }), ) const dirpath = this._formatDirpath(path.dirname(filepath)) const createCaseGroup = (parentDirpath: string): ITokenizerUseCaseGroup<T> => { const caseGroup: ITokenizerUseCaseGroup<T> = { dirpath, filepath, title: data.title, cases, subGroups: [], } if (caseGroup.dirpath === parentDirpath) return caseGroup const wrapper: ITokenizerUseCaseGroup<T> = { dirpath: caseGroup.dirpath, filepath: caseGroup.dirpath, title: undefined, cases: [], subGroups: [caseGroup], } return wrapper } // Try to merge `result` into existing caseGroup const traverseCaseGroup = ( parentDirpath: string, caseGroups: Array<ITokenizerUseCaseGroup<T>>, ): boolean => { for (const caseGroup of caseGroups) { if (caseGroup.dirpath !== caseGroup.filepath) continue if (!dirpath.startsWith(caseGroup.dirpath)) continue if (!traverseCaseGroup(caseGroup.dirpath, caseGroup.subGroups)) { const result = createCaseGroup(caseGroup.dirpath) caseGroup.subGroups.push(result) } return true } // Find the caseGroup which has the longest common dirpath with `dirpath` let longestCommonDirpath = parentDirpath let LCDIds: number[] = [] for (let i = 0; i < caseGroups.length; ++i) { const caseGroup = caseGroups[i] const commonDirpath = this._calcCommonDirpath(caseGroup.dirpath, dirpath) if (commonDirpath.length > longestCommonDirpath.length) { longestCommonDirpath = commonDirpath LCDIds = [i] } else if (commonDirpath.length === longestCommonDirpath.length) { LCDIds.push(i) } } if (longestCommonDirpath <= parentDirpath) return false invariant( LCDIds.length > 0 && LCDIds.every((x, i, A) => i === 0 || x - 1 === A[i - 1]), 'LCDIds should be continuously increasing integers', ) // try to create a new common parent const parentGroup: ITokenizerUseCaseGroup<T> = { dirpath: longestCommonDirpath, filepath: longestCommonDirpath, title: undefined, cases, subGroups: [...LCDIds.map(i => caseGroups[i]), createCaseGroup(longestCommonDirpath)], } caseGroups.splice(LCDIds[0], LCDIds.length, parentGroup) return true } // If not belong to any existing case group, // regard it as one of the top level group if (!traverseCaseGroup(this.formattedCaseRootDirectory, this.caseGroups)) { const result = createCaseGroup(this.formattedCaseRootDirectory) this.caseGroups.push(result) } } /** * Format dir path * * @param dirpath */ protected _formatDirpath(dirpath: string): string { const result = path.normalize(dirpath).replace(/[\\/]$/, '') + path.sep return result } /** * Calc common dirpath of two formatted dirpath * * @param p1 * @param p2 */ protected _calcCommonDirpath(p1: string, p2: string): string { const x: string[] = p1.split(/[\\/]+/g) const y: string[] = p2.split(/[\\/]+/g) const z: string[] = [] for (let i = 0; i < x.length && i < y.length; ++i) { if (x[i] !== y[i]) break z.push(x[i]) } return this._formatDirpath(z.join(path.sep)) } /** * Create test for a single use case * * @param useCase * @param filepath */ protected _testCase(useCase: ITokenizerUseCase<T>, filepath: string): void { const self = this const { description, input } = useCase test(description, async function () { const parseAnswer = self._parseAndFormat(input, filepath) expect(useCase.parseAnswer).toEqual(parseAnswer) }) } /** * Create an answer for a single use case * * @param useCase * @param filepath */ protected _answerCase( useCase: ITokenizerUseCase<T>, filepath: string, ): Partial<ITokenizerUseCase<T>> { const parseAnswer = this._parseAndFormat(useCase.input, filepath) return { parseAnswer } } /** * Parse and format. * Print case filepath when it failed. * * @param input * @param filepath */ protected _parseAndFormat(input: string, filepath: string): any { return this.trackHandle<any>(filepath, () => { const output = this.parser.parse(input) const formattedOutput = this.format(output) return formattedOutput }) } }
the_stack
import * as Common from '../../core/common/common.js'; import * as i18n from '../../core/i18n/i18n.js'; import * as Platform from '../../core/platform/platform.js'; import * as SDK from '../../core/sdk/sdk.js'; import * as Bindings from '../../models/bindings/bindings.js'; import type * as Workspace from '../../models/workspace/workspace.js'; import * as UI from '../../ui/legacy/legacy.js'; const UIStrings = { /** * @description A context menu item/command in the Media Query Inspector of the Device Toolbar. * Takes the user to the source code where this media query actually came from. */ revealInSourceCode: 'Reveal in source code', }; const str_ = i18n.i18n.registerUIStrings('panels/emulation/MediaQueryInspector.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class MediaQueryInspector extends UI.Widget.Widget implements SDK.TargetManager.SDKModelObserver<SDK.CSSModel.CSSModel> { private readonly mediaThrottler: Common.Throttler.Throttler; private readonly getWidthCallback: () => number; private readonly setWidthCallback: (arg0: number) => void; private scale: number; elementsToMediaQueryModel: WeakMap<Element, MediaQueryUIModel>; elementsToCSSLocations: WeakMap<Element, SDK.CSSModel.CSSLocation[]>; private cssModel?: SDK.CSSModel.CSSModel; private cachedQueryModels?: MediaQueryUIModel[]; constructor(getWidthCallback: () => number, setWidthCallback: (arg0: number) => void) { super(true); this.registerRequiredCSS('panels/emulation/mediaQueryInspector.css'); this.contentElement.classList.add('media-inspector-view'); this.contentElement.addEventListener('click', this.onMediaQueryClicked.bind(this), false); this.contentElement.addEventListener('contextmenu', this.onContextMenu.bind(this), false); this.mediaThrottler = new Common.Throttler.Throttler(0); this.getWidthCallback = getWidthCallback; this.setWidthCallback = setWidthCallback; this.scale = 1; this.elementsToMediaQueryModel = new WeakMap(); this.elementsToCSSLocations = new WeakMap(); SDK.TargetManager.TargetManager.instance().observeModels(SDK.CSSModel.CSSModel, this); UI.ZoomManager.ZoomManager.instance().addEventListener( UI.ZoomManager.Events.ZoomChanged, this.renderMediaQueries.bind(this), this); } modelAdded(cssModel: SDK.CSSModel.CSSModel): void { // FIXME: adapt this to multiple targets. if (this.cssModel) { return; } this.cssModel = cssModel; this.cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetAdded, this.scheduleMediaQueriesUpdate, this); this.cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetRemoved, this.scheduleMediaQueriesUpdate, this); this.cssModel.addEventListener(SDK.CSSModel.Events.StyleSheetChanged, this.scheduleMediaQueriesUpdate, this); this.cssModel.addEventListener(SDK.CSSModel.Events.MediaQueryResultChanged, this.scheduleMediaQueriesUpdate, this); } modelRemoved(cssModel: SDK.CSSModel.CSSModel): void { if (cssModel !== this.cssModel) { return; } this.cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetAdded, this.scheduleMediaQueriesUpdate, this); this.cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetRemoved, this.scheduleMediaQueriesUpdate, this); this.cssModel.removeEventListener(SDK.CSSModel.Events.StyleSheetChanged, this.scheduleMediaQueriesUpdate, this); this.cssModel.removeEventListener( SDK.CSSModel.Events.MediaQueryResultChanged, this.scheduleMediaQueriesUpdate, this); delete this.cssModel; } setAxisTransform(scale: number): void { if (Math.abs(this.scale - scale) < 1e-8) { return; } this.scale = scale; this.renderMediaQueries(); } private onMediaQueryClicked(event: Event): void { const mediaQueryMarker = (event.target as Node).enclosingNodeOrSelfWithClass('media-inspector-bar'); if (!mediaQueryMarker) { return; } const model = this.elementsToMediaQueryModel.get(mediaQueryMarker); if (!model) { return; } const modelMaxWidth = model.maxWidthExpression(); const modelMinWidth = model.minWidthExpression(); if (model.section() === Section.Max) { this.setWidthCallback(modelMaxWidth ? modelMaxWidth.computedLength() || 0 : 0); return; } if (model.section() === Section.Min) { this.setWidthCallback(modelMinWidth ? modelMinWidth.computedLength() || 0 : 0); return; } const currentWidth = this.getWidthCallback(); if (modelMinWidth && currentWidth !== modelMinWidth.computedLength()) { this.setWidthCallback(modelMinWidth.computedLength() || 0); } else { this.setWidthCallback(modelMaxWidth ? modelMaxWidth.computedLength() || 0 : 0); } } private onContextMenu(event: Event): void { if (!this.cssModel || !this.cssModel.isEnabled()) { return; } const mediaQueryMarker = (event.target as Node).enclosingNodeOrSelfWithClass('media-inspector-bar'); if (!mediaQueryMarker) { return; } const locations = this.elementsToCSSLocations.get(mediaQueryMarker) || []; const uiLocations = new Map<string, Workspace.UISourceCode.UILocation>(); for (let i = 0; i < locations.length; ++i) { const uiLocation = Bindings.CSSWorkspaceBinding.CSSWorkspaceBinding.instance().rawLocationToUILocation(locations[i]); if (!uiLocation) { continue; } const descriptor = typeof uiLocation.columnNumber === 'number' ? Platform.StringUtilities.sprintf( '%s:%d:%d', uiLocation.uiSourceCode.url(), uiLocation.lineNumber + 1, uiLocation.columnNumber + 1) : Platform.StringUtilities.sprintf('%s:%d', uiLocation.uiSourceCode.url(), uiLocation.lineNumber + 1); uiLocations.set(descriptor, uiLocation); } const contextMenuItems = [...uiLocations.keys()].sort(); const contextMenu = new UI.ContextMenu.ContextMenu(event); const subMenuItem = contextMenu.defaultSection().appendSubMenuItem(i18nString(UIStrings.revealInSourceCode)); for (let i = 0; i < contextMenuItems.length; ++i) { const title = contextMenuItems[i]; subMenuItem.defaultSection().appendItem( title, this.revealSourceLocation.bind(this, (uiLocations.get(title) as Workspace.UISourceCode.UILocation))); } contextMenu.show(); } private revealSourceLocation(location: Workspace.UISourceCode.UILocation): void { Common.Revealer.reveal(location); } private scheduleMediaQueriesUpdate(): void { if (!this.isShowing()) { return; } this.mediaThrottler.schedule(this.refetchMediaQueries.bind(this)); } private refetchMediaQueries(): Promise<void> { if (!this.isShowing() || !this.cssModel) { return Promise.resolve(); } return this.cssModel.mediaQueriesPromise().then(this.rebuildMediaQueries.bind(this)); } private squashAdjacentEqual(models: MediaQueryUIModel[]): MediaQueryUIModel[] { const filtered = []; for (let i = 0; i < models.length; ++i) { const last = filtered[filtered.length - 1]; if (!last || !last.equals(models[i])) { filtered.push(models[i]); } } return filtered; } private rebuildMediaQueries(cssMedias: SDK.CSSMedia.CSSMedia[]): void { let queryModels: MediaQueryUIModel[] = []; for (let i = 0; i < cssMedias.length; ++i) { const cssMedia = cssMedias[i]; if (!cssMedia.mediaList) { continue; } for (let j = 0; j < cssMedia.mediaList.length; ++j) { const mediaQuery = cssMedia.mediaList[j]; const queryModel = MediaQueryUIModel.createFromMediaQuery(cssMedia, mediaQuery); if (queryModel) { queryModels.push(queryModel); } } } queryModels.sort(compareModels); queryModels = this.squashAdjacentEqual(queryModels); let allEqual: (boolean|undefined) = this.cachedQueryModels && this.cachedQueryModels.length === queryModels.length; for (let i = 0; allEqual && i < queryModels.length; ++i) { allEqual = allEqual && this.cachedQueryModels && this.cachedQueryModels[i].equals(queryModels[i]); } if (allEqual) { return; } this.cachedQueryModels = queryModels; this.renderMediaQueries(); function compareModels(model1: MediaQueryUIModel, model2: MediaQueryUIModel): number { return model1.compareTo(model2); } } private renderMediaQueries(): void { if (!this.cachedQueryModels || !this.isShowing()) { return; } const markers = []; let lastMarker: { active: boolean, model: MediaQueryUIModel, locations: SDK.CSSModel.CSSLocation[], }|null = null; for (let i = 0; i < this.cachedQueryModels.length; ++i) { const model = this.cachedQueryModels[i]; if (lastMarker && lastMarker.model.dimensionsEqual(model)) { lastMarker.active = lastMarker.active || model.active(); } else { lastMarker = { active: model.active(), model, locations: ([] as SDK.CSSModel.CSSLocation[]), }; markers.push(lastMarker); } const rawLocation = model.rawLocation(); if (rawLocation) { lastMarker.locations.push(rawLocation); } } this.contentElement.removeChildren(); let container: HTMLElement|null = null; for (let i = 0; i < markers.length; ++i) { if (!i || markers[i].model.section() !== markers[i - 1].model.section()) { container = this.contentElement.createChild('div', 'media-inspector-marker-container'); } const marker = markers[i]; const bar = this.createElementFromMediaQueryModel(marker.model); this.elementsToMediaQueryModel.set(bar, marker.model); this.elementsToCSSLocations.set(bar, marker.locations); bar.classList.toggle('media-inspector-marker-inactive', !marker.active); if (!container) { throw new Error('Could not find container to render media queries into.'); } container.appendChild(bar); } } private zoomFactor(): number { return UI.ZoomManager.ZoomManager.instance().zoomFactor() / this.scale; } wasShown(): void { super.wasShown(); this.scheduleMediaQueriesUpdate(); } private createElementFromMediaQueryModel(model: MediaQueryUIModel): Element { const zoomFactor = this.zoomFactor(); const minWidthExpression = model.minWidthExpression(); const maxWidthExpression = model.maxWidthExpression(); const minWidthValue = minWidthExpression ? (minWidthExpression.computedLength() || 0) / zoomFactor : 0; const maxWidthValue = maxWidthExpression ? (maxWidthExpression.computedLength() || 0) / zoomFactor : 0; const result = document.createElement('div'); result.classList.add('media-inspector-bar'); if (model.section() === Section.Max) { result.createChild('div', 'media-inspector-marker-spacer'); const markerElement = result.createChild('div', 'media-inspector-marker media-inspector-marker-max-width'); markerElement.style.width = maxWidthValue + 'px'; UI.Tooltip.Tooltip.install(markerElement, model.mediaText()); appendLabel(markerElement, model.maxWidthExpression(), false, false); appendLabel(markerElement, model.maxWidthExpression(), true, true); result.createChild('div', 'media-inspector-marker-spacer'); } if (model.section() === Section.MinMax) { result.createChild('div', 'media-inspector-marker-spacer'); const leftElement = result.createChild('div', 'media-inspector-marker media-inspector-marker-min-max-width'); leftElement.style.width = (maxWidthValue - minWidthValue) * 0.5 + 'px'; UI.Tooltip.Tooltip.install(leftElement, model.mediaText()); appendLabel(leftElement, model.maxWidthExpression(), true, false); appendLabel(leftElement, model.minWidthExpression(), false, true); result.createChild('div', 'media-inspector-marker-spacer').style.flex = '0 0 ' + minWidthValue + 'px'; const rightElement = result.createChild('div', 'media-inspector-marker media-inspector-marker-min-max-width'); rightElement.style.width = (maxWidthValue - minWidthValue) * 0.5 + 'px'; UI.Tooltip.Tooltip.install(rightElement, model.mediaText()); appendLabel(rightElement, model.minWidthExpression(), true, false); appendLabel(rightElement, model.maxWidthExpression(), false, true); result.createChild('div', 'media-inspector-marker-spacer'); } if (model.section() === Section.Min) { const leftElement = result.createChild( 'div', 'media-inspector-marker media-inspector-marker-min-width media-inspector-marker-min-width-left'); UI.Tooltip.Tooltip.install(leftElement, model.mediaText()); appendLabel(leftElement, model.minWidthExpression(), false, false); result.createChild('div', 'media-inspector-marker-spacer').style.flex = '0 0 ' + minWidthValue + 'px'; const rightElement = result.createChild( 'div', 'media-inspector-marker media-inspector-marker-min-width media-inspector-marker-min-width-right'); UI.Tooltip.Tooltip.install(rightElement, model.mediaText()); appendLabel(rightElement, model.minWidthExpression(), true, true); } function appendLabel( marker: Element, expression: SDK.CSSMedia.CSSMediaQueryExpression|null, atLeft: boolean, leftAlign: boolean): void { if (!expression) { return; } marker .createChild( 'div', 'media-inspector-marker-label-container ' + (atLeft ? 'media-inspector-marker-label-container-left' : 'media-inspector-marker-label-container-right')) .createChild( 'span', 'media-inspector-marker-label ' + (leftAlign ? 'media-inspector-label-left' : 'media-inspector-label-right')) .textContent = expression.value() + expression.unit(); } return result; } } export const enum Section { Max = 0, MinMax = 1, Min = 2, } export class MediaQueryUIModel { private cssMedia: SDK.CSSMedia.CSSMedia; private readonly minWidthExpressionInternal: SDK.CSSMedia.CSSMediaQueryExpression|null; private readonly maxWidthExpressionInternal: SDK.CSSMedia.CSSMediaQueryExpression|null; private readonly activeInternal: boolean; private readonly sectionInternal: Section; private rawLocationInternal?: SDK.CSSModel.CSSLocation|null; constructor( cssMedia: SDK.CSSMedia.CSSMedia, minWidthExpression: SDK.CSSMedia.CSSMediaQueryExpression|null, maxWidthExpression: SDK.CSSMedia.CSSMediaQueryExpression|null, active: boolean) { this.cssMedia = cssMedia; this.minWidthExpressionInternal = minWidthExpression; this.maxWidthExpressionInternal = maxWidthExpression; this.activeInternal = active; if (maxWidthExpression && !minWidthExpression) { this.sectionInternal = Section.Max; } else if (minWidthExpression && maxWidthExpression) { this.sectionInternal = Section.MinMax; } else { this.sectionInternal = Section.Min; } } static createFromMediaQuery(cssMedia: SDK.CSSMedia.CSSMedia, mediaQuery: SDK.CSSMedia.CSSMediaQuery): MediaQueryUIModel|null { let maxWidthExpression: SDK.CSSMedia.CSSMediaQueryExpression|null = null; let maxWidthPixels: number = Number.MAX_VALUE; let minWidthExpression: SDK.CSSMedia.CSSMediaQueryExpression|null = null; let minWidthPixels: number = Number.MIN_VALUE; const expressions = mediaQuery.expressions(); if (!expressions) { return null; } for (let i = 0; i < expressions.length; ++i) { const expression = expressions[i]; const feature = expression.feature(); if (feature.indexOf('width') === -1) { continue; } const pixels = expression.computedLength(); if (feature.startsWith('max-') && pixels && pixels < maxWidthPixels) { maxWidthExpression = expression; maxWidthPixels = pixels; } else if (feature.startsWith('min-') && pixels && pixels > minWidthPixels) { minWidthExpression = expression; minWidthPixels = pixels; } } if (minWidthPixels > maxWidthPixels || (!maxWidthExpression && !minWidthExpression)) { return null; } return new MediaQueryUIModel(cssMedia, minWidthExpression, maxWidthExpression, mediaQuery.active()); } equals(other: MediaQueryUIModel): boolean { return this.compareTo(other) === 0; } dimensionsEqual(other: MediaQueryUIModel): boolean { const thisMinWidthExpression = this.minWidthExpression(); const otherMinWidthExpression = other.minWidthExpression(); const thisMaxWidthExpression = this.maxWidthExpression(); const otherMaxWidthExpression = other.maxWidthExpression(); const sectionsEqual = this.section() === other.section(); // If there isn't an other min width expression, they aren't equal, so the optional chaining operator is safe to use here. const minWidthEqual = !thisMinWidthExpression || thisMinWidthExpression.computedLength() === otherMinWidthExpression?.computedLength(); const maxWidthEqual = !thisMaxWidthExpression || thisMaxWidthExpression.computedLength() === otherMaxWidthExpression?.computedLength(); return sectionsEqual && minWidthEqual && maxWidthEqual; } compareTo(other: MediaQueryUIModel): number { if (this.section() !== other.section()) { return this.section() - other.section(); } if (this.dimensionsEqual(other)) { const myLocation = this.rawLocation(); const otherLocation = other.rawLocation(); if (!myLocation && !otherLocation) { return Platform.StringUtilities.compare(this.mediaText(), other.mediaText()); } if (myLocation && !otherLocation) { return 1; } if (!myLocation && otherLocation) { return -1; } if (this.active() !== other.active()) { return this.active() ? -1 : 1; } if (!myLocation || !otherLocation) { // This conditional never runs, because it's dealt with above, but // TypeScript can't follow that by this point both myLocation and // otherLocation must exist. return 0; } return Platform.StringUtilities.compare(myLocation.url, otherLocation.url) || myLocation.lineNumber - otherLocation.lineNumber || myLocation.columnNumber - otherLocation.columnNumber; } const thisMaxWidthExpression = this.maxWidthExpression(); const otherMaxWidthExpression = other.maxWidthExpression(); const thisMaxLength = thisMaxWidthExpression ? thisMaxWidthExpression.computedLength() || 0 : 0; const otherMaxLength = otherMaxWidthExpression ? otherMaxWidthExpression.computedLength() || 0 : 0; const thisMinWidthExpression = this.minWidthExpression(); const otherMinWidthExpression = other.minWidthExpression(); const thisMinLength = thisMinWidthExpression ? thisMinWidthExpression.computedLength() || 0 : 0; const otherMinLength = otherMinWidthExpression ? otherMinWidthExpression.computedLength() || 0 : 0; if (this.section() === Section.Max) { return otherMaxLength - thisMaxLength; } if (this.section() === Section.Min) { return thisMinLength - otherMinLength; } return thisMinLength - otherMinLength || otherMaxLength - thisMaxLength; } section(): Section { return this.sectionInternal; } mediaText(): string { return this.cssMedia.text || ''; } rawLocation(): SDK.CSSModel.CSSLocation|null { if (!this.rawLocationInternal) { this.rawLocationInternal = this.cssMedia.rawLocation(); } return this.rawLocationInternal; } minWidthExpression(): SDK.CSSMedia.CSSMediaQueryExpression|null { return this.minWidthExpressionInternal; } maxWidthExpression(): SDK.CSSMedia.CSSMediaQueryExpression|null { return this.maxWidthExpressionInternal; } active(): boolean { return this.activeInternal; } }
the_stack
import path from 'path'; import { Table, AttributeType, BillingMode } from 'aws-cdk-lib/aws-dynamodb'; import { App, Stack, RemovalPolicy } from 'aws-cdk-lib'; import * as AWS from 'aws-sdk'; import { v4 } from 'uuid'; import { deployStack, destroyStack } from '../../../commons/tests/utils/cdk-cli'; import { getTraces, getInvocationSubsegment, splitSegmentsByName, invokeAllTestCases, createTracerTestFunction, getFunctionArn, getFirstSubsegment, } from '../helpers/tracesUtils'; import { generateUniqueName, isValidRuntimeKey, } from '../../../commons/tests/utils/e2eUtils'; import { RESOURCE_NAME_PREFIX, SETUP_TIMEOUT, TEARDOWN_TIMEOUT, TEST_CASE_TIMEOUT, expectedCustomAnnotationKey, expectedCustomAnnotationValue, expectedCustomMetadataKey, expectedCustomMetadataValue, expectedCustomResponseValue, expectedCustomErrorMessage, } from './constants'; import { assertAnnotation, assertErrorAndFault, } from '../helpers/traceAssertions'; const runtime: string = process.env.RUNTIME || 'nodejs16x'; if (!isValidRuntimeKey(runtime)) { throw new Error(`Invalid runtime key value: ${runtime}`); } /** * We will create a stack with 3 Lambda functions: * 1. With all flags enabled (capture both response and error) * 2. Do not capture error or response * 3. Do not enable tracer * Each stack must use a unique `serviceName` as it's used to for retrieving the trace. * Using the same one will result in traces from different test cases mixing up. */ const stackName = generateUniqueName(RESOURCE_NAME_PREFIX, v4(), runtime, 'AllFeatures-Middy'); const lambdaFunctionCodeFile = 'allFeatures.middy.test.functionCode.ts'; let startTime: Date; /** * Function #1 is with all flags enabled. */ const uuidFunction1 = v4(); const functionNameWithAllFlagsEnabled = generateUniqueName(RESOURCE_NAME_PREFIX, uuidFunction1, runtime, 'AllFeatures-Middy-AllFlagsEnabled'); const serviceNameWithAllFlagsEnabled = functionNameWithAllFlagsEnabled; /** * Function #2 doesn't capture error or response */ const uuidFunction2 = v4(); const functionNameWithNoCaptureErrorOrResponse = generateUniqueName(RESOURCE_NAME_PREFIX, uuidFunction2, runtime, 'AllFeatures-Middy-NoCaptureErrorOrResponse'); const serviceNameWithNoCaptureErrorOrResponse = functionNameWithNoCaptureErrorOrResponse; /** * Function #3 disables tracer */ const uuidFunction3 = v4(); const functionNameWithTracerDisabled = generateUniqueName(RESOURCE_NAME_PREFIX, uuidFunction3, runtime, 'AllFeatures-Middy-TracerDisabled'); const serviceNameWithTracerDisabled = functionNameWithNoCaptureErrorOrResponse; const xray = new AWS.XRay(); const invocations = 3; const integTestApp = new App(); let stack: Stack; describe(`Tracer E2E tests, all features with middy instantiation for runtime: ${runtime}`, () => { beforeAll(async () => { // Prepare startTime = new Date(); const ddbTableName = stackName + '-table'; stack = new Stack(integTestApp, stackName); const ddbTable = new Table(stack, 'Table', { tableName: ddbTableName, partitionKey: { name: 'id', type: AttributeType.STRING }, billingMode: BillingMode.PAY_PER_REQUEST, removalPolicy: RemovalPolicy.DESTROY }); const entry = path.join(__dirname, lambdaFunctionCodeFile); const functionWithAllFlagsEnabled = createTracerTestFunction({ stack, functionName: functionNameWithAllFlagsEnabled, entry, expectedServiceName: serviceNameWithAllFlagsEnabled, environmentParams: { TEST_TABLE_NAME: ddbTableName, POWERTOOLS_TRACER_CAPTURE_RESPONSE: 'true', POWERTOOLS_TRACER_CAPTURE_ERROR: 'true', POWERTOOLS_TRACE_ENABLED: 'true', }, runtime }); ddbTable.grantWriteData(functionWithAllFlagsEnabled); const functionThatDoesNotCapturesErrorAndResponse = createTracerTestFunction({ stack, functionName: functionNameWithNoCaptureErrorOrResponse, entry, expectedServiceName: serviceNameWithNoCaptureErrorOrResponse, environmentParams: { TEST_TABLE_NAME: ddbTableName, POWERTOOLS_TRACER_CAPTURE_RESPONSE: 'false', POWERTOOLS_TRACER_CAPTURE_ERROR: 'false', POWERTOOLS_TRACE_ENABLED: 'true', }, runtime }); ddbTable.grantWriteData(functionThatDoesNotCapturesErrorAndResponse); const functionWithTracerDisabled = createTracerTestFunction({ stack, functionName: functionNameWithTracerDisabled, entry, expectedServiceName: serviceNameWithTracerDisabled, environmentParams: { TEST_TABLE_NAME: ddbTableName, POWERTOOLS_TRACER_CAPTURE_RESPONSE: 'true', POWERTOOLS_TRACER_CAPTURE_ERROR: 'true', POWERTOOLS_TRACE_ENABLED: 'false', }, runtime }); ddbTable.grantWriteData(functionWithTracerDisabled); await deployStack(integTestApp, stack); // Act await Promise.all([ invokeAllTestCases(functionNameWithAllFlagsEnabled), invokeAllTestCases(functionNameWithNoCaptureErrorOrResponse), invokeAllTestCases(functionNameWithTracerDisabled), ]); }, SETUP_TIMEOUT); afterAll(async () => { if (!process.env.DISABLE_TEARDOWN) { await destroyStack(integTestApp, stack); } }, TEARDOWN_TIMEOUT); it('should generate all custom traces', async () => { const tracesWhenAllFlagsEnabled = await getTraces(xray, startTime, await getFunctionArn(functionNameWithAllFlagsEnabled), invocations, 5); expect(tracesWhenAllFlagsEnabled.length).toBe(invocations); // Assess for (let i = 0; i < invocations; i++) { const trace = tracesWhenAllFlagsEnabled[i]; /** * Expect the trace to have 5 segments: * 1. Lambda Context (AWS::Lambda) * 2. Lambda Function (AWS::Lambda::Function) * 3. DynamoDB (AWS::DynamoDB) * 4. DynamoDB Table (AWS::DynamoDB::Table) * 5. Remote call (httpbin.org) */ expect(trace.Segments.length).toBe(5); const invocationSubsegment = getInvocationSubsegment(trace); /** * Invocation subsegment should have a subsegment '## index.handler' (default behavior for PowerTool tracer) * '## index.handler' subsegment should have 3 subsegments * 1. DynamoDB (PutItem on the table) * 2. DynamoDB (PutItem overhead) * 3. httpbin.org (Remote call) */ const handlerSubsegment = getFirstSubsegment(invocationSubsegment); expect(handlerSubsegment.name).toBe('## index.handler'); expect(handlerSubsegment?.subsegments).toHaveLength(3); if (!handlerSubsegment.subsegments) { fail('"## index.handler" subsegment should have subsegments'); } const subsegments = splitSegmentsByName(handlerSubsegment.subsegments, [ 'DynamoDB', 'httpbin.org' ]); expect(subsegments.get('DynamoDB')?.length).toBe(2); expect(subsegments.get('httpbin.org')?.length).toBe(1); expect(subsegments.get('other')?.length).toBe(0); const shouldThrowAnError = (i === (invocations - 1)); if (shouldThrowAnError) { assertErrorAndFault(invocationSubsegment, expectedCustomErrorMessage); } } }, TEST_CASE_TIMEOUT); it('should have correct annotations and metadata', async () => { const tracesWhenAllFlagsEnabled = await getTraces(xray, startTime, await getFunctionArn(functionNameWithAllFlagsEnabled), invocations, 5); for (let i = 0; i < invocations; i++) { const trace = tracesWhenAllFlagsEnabled[i]; const invocationSubsegment = getInvocationSubsegment(trace); const handlerSubsegment = getFirstSubsegment(invocationSubsegment); const { annotations, metadata } = handlerSubsegment; const isColdStart = (i === 0); assertAnnotation({ annotations, isColdStart, expectedServiceName: serviceNameWithAllFlagsEnabled, expectedCustomAnnotationKey, expectedCustomAnnotationValue, }); if (!metadata) { fail('metadata is missing'); } expect(metadata[serviceNameWithAllFlagsEnabled][expectedCustomMetadataKey]) .toEqual(expectedCustomMetadataValue); const shouldThrowAnError = (i === (invocations - 1)); if (!shouldThrowAnError) { // Assert that the metadata object contains the response expect(metadata[serviceNameWithAllFlagsEnabled]['index.handler response']) .toEqual(expectedCustomResponseValue); } } }, TEST_CASE_TIMEOUT); it('should not capture error nor response when the flags are false', async () => { const tracesWithNoCaptureErrorOrResponse = await getTraces(xray, startTime, await getFunctionArn(functionNameWithNoCaptureErrorOrResponse), invocations, 5); expect(tracesWithNoCaptureErrorOrResponse.length).toBe(invocations); // Assess for (let i = 0; i < invocations; i++) { const trace = tracesWithNoCaptureErrorOrResponse[i]; /** * Expect the trace to have 5 segments: * 1. Lambda Context (AWS::Lambda) * 2. Lambda Function (AWS::Lambda::Function) * 3. DynamoDB (AWS::DynamoDB) * 4. DynamoDB Table (AWS::DynamoDB::Table) * 5. Remote call (httpbin.org) */ expect(trace.Segments.length).toBe(5); const invocationSubsegment = getInvocationSubsegment(trace); /** * Invocation subsegment should have a subsegment '## index.handler' (default behavior for PowerTool tracer) * '## index.handler' subsegment should have 3 subsegments * 1. DynamoDB (PutItem on the table) * 2. DynamoDB (PutItem overhead) * 3. httpbin.org (Remote call) */ const handlerSubsegment = getFirstSubsegment(invocationSubsegment); expect(handlerSubsegment.name).toBe('## index.handler'); expect(handlerSubsegment?.subsegments).toHaveLength(3); if (!handlerSubsegment.subsegments) { fail('"## index.handler" subsegment should have subsegments'); } const subsegments = splitSegmentsByName(handlerSubsegment.subsegments, [ 'DynamoDB', 'httpbin.org' ]); expect(subsegments.get('DynamoDB')?.length).toBe(2); expect(subsegments.get('httpbin.org')?.length).toBe(1); expect(subsegments.get('other')?.length).toBe(0); const shouldThrowAnError = (i === (invocations - 1)); if (shouldThrowAnError) { // Assert that the subsegment has the expected fault expect(invocationSubsegment.error).toBe(true); expect(handlerSubsegment.error).toBe(true); // Assert that no error was captured on the subsegment expect(handlerSubsegment.hasOwnProperty('cause')).toBe(false); } } }, TEST_CASE_TIMEOUT); it('should not capture any custom traces when disabled', async () => { const expectedNoOfTraces = 2; const tracesWithTracerDisabled = await getTraces(xray, startTime, await getFunctionArn(functionNameWithTracerDisabled), invocations, expectedNoOfTraces); expect(tracesWithTracerDisabled.length).toBe(invocations); // Assess for (let i = 0; i < invocations; i++) { const trace = tracesWithTracerDisabled[i]; expect(trace.Segments.length).toBe(2); /** * Expect no subsegment in the invocation */ const invocationSubsegment = getInvocationSubsegment(trace); expect(invocationSubsegment?.subsegments).toBeUndefined(); const shouldThrowAnError = (i === (invocations - 1)); if (shouldThrowAnError) { expect(invocationSubsegment.error).toBe(true); } } }, TEST_CASE_TIMEOUT); });
the_stack
import { Flac, DestroyedEvent, decoder_read_callback_fn, decoder_write_callback_fn, decoder_error_callback_fn, metadata_callback_fn, StreamMetadata , ReadResult , FLAC__StreamDecoderState, CompletedReadResult , CodingOptions } from '../index.d'; import { interleave } from './utils/wav-utils'; import { mergeBuffers , getLength } from './utils/data-utils'; import { BeforeReadyHandler } from './before-ready-handler'; export interface DecoderOptions extends CodingOptions { verify?: boolean; isOgg?: boolean autoOnReady?: boolean; } type ChacheableDecoderCalls = '_init' | 'decode' | 'decodeChunk' | 'reset'; export class Decoder { private _id: number | undefined; private _isError: boolean = false; private _isInitialized: boolean = false; private _isFinished: boolean = false; private _beforeReadyHandler?: BeforeReadyHandler<Decoder, ChacheableDecoderCalls>; /** * input cache for decoding-chunk modus */ private _inputCache: Uint8Array[] = []; /** * the current reading offset within the current input chache chunk */ private _currentInputCacheOffset: number = -1; /** * indicates that not enough data is cached for decoding the next chunk or * decoding is currently in progress */ private _decodingChunkPaused: boolean = true; /** * threshold for minimal amount of data (in bytes) that need to be cached, * before triggering decoding the next data chunk */ private _min_data_decode_threshold: number = (4096 / 2);// NOTE: should be somewhat greater than 1024 /** * cache for the decoded data */ protected data: Uint8Array[][] = []; /** * metadata for the decoded data */ private _metadata: StreamMetadata | undefined; private readonly _onDestroyed: (evt: DestroyedEvent) => void; private readonly _onRead: decoder_read_callback_fn; private readonly _onWrite: decoder_write_callback_fn; private readonly _onError: decoder_error_callback_fn; private readonly _onMetaData: metadata_callback_fn; /** * will be (re-)set depending on decoding mode: * either reading data as a whole, or reading data chunk-by-chunk */ private _onReadData?: decoder_read_callback_fn; public get initialized(): boolean { return this._isInitialized; } public get finished(): boolean { return this._isFinished; } public get metadata(): StreamMetadata | undefined { return this._metadata; } public get rawData(): Uint8Array[][] { return this.data; } public get isWaitOnReady(): boolean { return this._beforeReadyHandler?.isWaitOnReady || false; } constructor(private Flac: Flac, private _options: DecoderOptions = {}){ this._id = Flac.create_libflac_decoder(_options.verify); this._onDestroyed = (evt: DestroyedEvent) => { if(evt.target.id === this._id){ this._id = void(0); this._isInitialized = false; this._isFinished = false; Flac.off('destroyed', this._onDestroyed); if(this._beforeReadyHandler?.enabled){ this._beforeReadyHandler.enabled = false; } } }; Flac.on('destroyed', this._onDestroyed); this._onRead = (bufferSize: number): (ReadResult | CompletedReadResult) => { if(this._onReadData){ return this._onReadData(bufferSize); } //if no read function is set, return error result: return {buffer: undefined, readDataLength: 0, error: true}; } this._onWrite = (data: Uint8Array[]) => { this.addData(data); }; this._onMetaData = (m?: StreamMetadata) => { if(m){ this._metadata = m; } }; this._onError = (code, description) => { this._isError = true; // TODO emit error instead! console.error(`Decoder[${this._id}] encoutered error (${code}): ${description}`); }; if(this._options?.autoOnReady){ this._beforeReadyHandler = new BeforeReadyHandler<Decoder, ChacheableDecoderCalls>(this, true, this.Flac); } if(this._id === 0){ this._isError = true; } else { if(this._isAnalyse(this._options)){ Flac.setOptions(this._id, this._options); } this._init(this._options.isOgg); } } private _init(isDecodeOgg?: boolean) : void { if(this._id){ const state = isDecodeOgg? this.Flac.init_decoder_ogg_stream(this._id, this._onRead, this._onWrite, this._onError, this._onMetaData): this.Flac.init_decoder_stream(this._id, this._onRead, this._onWrite, this._onError, this._onMetaData); this._isError = state !== 0; if(state === 0){ this._isInitialized = true; this._isFinished = false; } }else { this._handleBeforeReady('_init', arguments); } } /** * reset decoder: * resets internal state and clears cached input/output data. */ public reset(options?: DecoderOptions): boolean { if(this._id && !!this.Flac.FLAC__stream_decoder_reset(this._id)){ if(options){ Object.assign(this._options, options); this.Flac.setOptions(this._id, this._options); const isVerify = this.Flac.FLAC__stream_decoder_get_md5_checking(this._id); if(typeof this._options.verify !== 'undefined' && isVerify != /*non-exact comparision*/ this._options.verify){ this.Flac.FLAC__stream_decoder_set_md5_checking(this._id, !!this._options.verify); } } this._resetInputCache(); this.clearData(); this._metadata = undefined; this._onReadData = undefined; this._isInitialized = false; this._isFinished = false; this._init(this._options.isOgg); return this._isError; } return this._handleBeforeReady('reset', arguments); } /** * decode all data at once (will automatically finishes decoding) * * **NOTE**: do not mix with [[decodeChunk]] calls! * * @param flacData the (complete) FLAC data to decode * @return `true` if encoding was successful */ public decode(flacData: Uint8Array): boolean { if(this._id && this._isInitialized && !this._isFinished){ this._onReadData = this._createReadFunc(flacData); if(!!this.Flac.FLAC__stream_decoder_process_until_end_of_stream(this._id)){ return this._finish(); }; return false; } return this._handleBeforeReady('decode', arguments); } /** finish decoding */ public decodeChunk(): boolean; /** * decode next chunk of data: * if not enough data for decoding is cached, will pause until enough data * is cached, or flushing of the cache is forced. * * @param flacData the data chunk to decode: * if omitted, will finish the decoding (any cached data will be flushed). * @return `true` if encoding was successful */ public decodeChunk(flacData: Uint8Array): boolean; /** * decode next chunk of data: * if not enough data for decoding is cached, will pause until enough data * is cached, or flushing of the cache is forced. * * **NOTE**: do not mix with [[decode]] calls! * * @param [flacData] the data chunk to decode: * if omitted, will finish the decoding (any cached data will be flushed). * @param [flushCache] flush the cached data and finalize decoding * @return `true` if encoding was successful */ public decodeChunk(flacData?: Uint8Array, flushCache?: boolean): boolean { if (this._id && this._isInitialized && !this._isFinished) { if (!this._onReadData) { this._onReadData = this._createReadChunkFunc(); } if(typeof flacData === 'boolean'){ flushCache = true; flacData = void(0); } if(flacData){ this._addInputChunk(flacData); } else { flushCache = true; } if(!flushCache && !this._decodingChunkPaused){ //decoding in progress -> do nothing return true; } if (!flushCache && !this._canReadChunk()) { //if there is not enough buffered data yet, do wait return true; } // console.log('decodingPaused ' + this._decodingChunkPaused);//debug this._decodingChunkPaused = false; //request to decode data chunks until end-of-stream is reached (or decoding is paused): let decState: FLAC__StreamDecoderState = 0; while (!this._decodingChunkPaused && decState <= 3) { if(!this.Flac.FLAC__stream_decoder_process_single(this._id)){ return false; } decState = this.Flac.FLAC__stream_decoder_get_state(this._id); } if(flushCache){ return this._finish(); } else { return true; } } return this._handleBeforeReady('decodeChunk', arguments); } /** * get non-interleaved (WAV) samples: * the returned array length corresponds to the number of channels */ public getSamples(): Uint8Array[]; /** * get non-interleaved (raw PCM) samples: * the returned array length corresponds to the number of channels */ public getSamples(isInterleaved: false): Uint8Array[]; /** * get interleaved samples: * the returned array contains the data of all channels interleaved */ public getSamples(isInterleaved: true): Uint8Array; /** * get the decoded samples * @param isInterleaved if `true` interleaved WAV samples are returned, * otherwise, an array of the (raw) PCM samples will be returned * where the length of the array corresponds to the number of channels * @return the samples: either interleaved as `Uint8Array` or non-interleaved * as `Uint8Array[]` with the array's length corresponding to the number of channels */ public getSamples(isInterleaved?: boolean): Uint8Array[] | Uint8Array { if(this.metadata){ isInterleaved = !!isInterleaved; const channels = this.metadata.channels; if(isInterleaved){ return interleave(this.data, channels, this.metadata.bitsPerSample); } const data: Uint8Array[] = new Array(channels); for(let i=channels-1; i >= 0; --i){ const chData = this.mapData(d => d[i]); data[i] = mergeBuffers(chData, getLength(chData)); } return data; } throw new Error('Metadata not available'); } public getState(): FLAC__StreamDecoderState | -1 { if(this._id){ return this.Flac.FLAC__stream_decoder_get_state(this._id); } return -1; } public destroy(): void { if(this._id){ this.Flac.FLAC__stream_decoder_delete(this._id); } this._beforeReadyHandler && (this._beforeReadyHandler.enabled = false); this._metadata = void(0); this.clearData(); this._inputCache.splice(0); } protected addData(decData: Uint8Array[]): void { this.data.push(decData); } protected clearData(): void { this.data.splice(0); } protected mapData(mapFunc: (val: Uint8Array[], index: number, list: Uint8Array[][]) => Uint8Array): Uint8Array[] { return this.data.map(mapFunc); } private _isAnalyse(opt: DecoderOptions){ return opt.analyseResiduals || opt.analyseSubframes; } private _finish(): boolean { if(this._id && this._isInitialized && !this._isFinished){ if(!!this.Flac.FLAC__stream_decoder_finish(this._id)){ this._isFinished = true; return true; }; } return false; } private _createReadFunc(binData: Uint8Array): decoder_read_callback_fn { this._resetInputCache(); const size = binData.buffer.byteLength; let currentDataOffset: number = 0; return (bufferSize: number): (ReadResult | CompletedReadResult) => { const end = currentDataOffset === size? -1 : Math.min(currentDataOffset + bufferSize, size); if(end !== -1){ const _buffer = binData.subarray(currentDataOffset, end); const numberOfReadBytes = end - currentDataOffset; currentDataOffset = end; return {buffer: _buffer, readDataLength: numberOfReadBytes, error: false}; } return {buffer: undefined, readDataLength: 0}; } } private _addInputChunk(data: Uint8Array): void { this._inputCache.push(data) } private _canReadChunk(): boolean { return getLength(this._inputCache) >= this._min_data_decode_threshold; } private _resetInputCache(): void { this._decodingChunkPaused = true; this._currentInputCacheOffset = -1; if(this._inputCache.length > 0){ this._inputCache.splice(0); } } private _createReadChunkFunc(): decoder_read_callback_fn { this._resetInputCache(); this._currentInputCacheOffset = 0; return (bufferSize: number): (ReadResult | CompletedReadResult) => { // console.log('_readChunk: '+bufferSize, this._inputCache); if (!this._inputCache.length) { return { buffer: undefined, readDataLength: 0, error: false }; } const chunk = this._inputCache[0]; const size = chunk.buffer.byteLength; const start = this._currentInputCacheOffset; const end = start === size ? -1 : Math.min(start + bufferSize, size); let _buffer: Uint8Array | undefined; let numberOfReadBytes: number; if (end !== -1) { // console.log('_readChunk: reading ['+start+', '+end+'] '); _buffer = chunk.subarray(start, end); numberOfReadBytes = end - start; this._currentInputCacheOffset = end; } else { numberOfReadBytes = 0; } // console.log('numberOfReadBytes', numberOfReadBytes); if (numberOfReadBytes < bufferSize) { //use next buffered data-chunk for decoding: this._inputCache.shift(); //<- remove first (i.e. active) data-chunk from buffer const nextSize = this._inputCache.length > 0 ? this._inputCache[0].buffer.byteLength : 0; this._currentInputCacheOffset = 0; if (nextSize === 0) { // console.log('_readChunk: setting canDecodeNextChunk -> false');// debug this._decodingChunkPaused = true; //<- set to "pause" if no more data is available } } // console.log('_readChunk: returning ', numberOfReadBytes, _buffer); return { buffer: _buffer as unknown as Uint8Array, readDataLength: numberOfReadBytes, error: false }; } } private _handleBeforeReady(funcName: ChacheableDecoderCalls, args: ArrayLike<any>): boolean { if(this._beforeReadyHandler){ return this._beforeReadyHandler.handleBeforeReady(funcName, args); } return false; } }
the_stack
import localVarRequest from 'request'; import http from 'http'; /* tslint:disable:no-unused-locals */ import { SettingsPatchRequest } from '../model/settingsPatchRequest'; import { SettingsRequest } from '../model/settingsRequest'; import { SettingsResponse } from '../model/settingsResponse'; import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; import { HttpBasicAuth, HttpBearerAuth, ApiKeyAuth, OAuth } from '../model/models'; import { HttpError, RequestFile } from './apis'; let defaultBasePath = 'https://api.hubapi.com'; // =============================================== // This file is autogenerated - Please do not edit // =============================================== export enum SettingsApiApiKeys { developer_hapikey, } export class SettingsApi { protected _basePath = defaultBasePath; protected _defaultHeaders : any = {}; protected _useQuerystring : boolean = false; protected authentications = { 'default': <Authentication>new VoidAuth(), 'developer_hapikey': new ApiKeyAuth('query', 'hapikey'), } protected interceptors: Interceptor[] = []; constructor(basePath?: string); constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { if (basePath) { this.basePath = basePath; } } else { if (basePathOrUsername) { this.basePath = basePathOrUsername } } } set useQuerystring(value: boolean) { this._useQuerystring = value; } set basePath(basePath: string) { this._basePath = basePath; } set defaultHeaders(defaultHeaders: any) { this._defaultHeaders = defaultHeaders; } get defaultHeaders() { return this._defaultHeaders; } get basePath() { return this._basePath; } public setDefaultAuthentication(auth: Authentication) { this.authentications.default = auth; } public setApiKey(key: SettingsApiApiKeys, value: string) { (this.authentications as any)[SettingsApiApiKeys[key]].apiKey = value; } public addInterceptor(interceptor: Interceptor) { this.interceptors.push(interceptor); } /** * Deletes this calling extension. This will remove your service as an option for all connected accounts. * @summary Delete calling settings * @param appId The ID of the target app. */ public async archive (appId: number, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/crm/v3/extensions/calling/{appId}/settings' .replace('{' + 'appId' + '}', encodeURIComponent(String(appId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders); const produces = ['*/*']; // give precedence to 'application/json' if (produces.indexOf('application/json') >= 0) { localVarHeaderParams.Accept = 'application/json'; } else { localVarHeaderParams.Accept = produces.join(','); } let localVarFormParams: any = {}; // verify required parameter 'appId' is not null or undefined if (appId === null || appId === undefined) { throw new Error('Required parameter appId was null or undefined when calling archive.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); if (this.authentications.developer_hapikey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.developer_hapikey.applyToRequest(localVarRequestOptions)); } authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); let interceptorPromise = authenticationPromise; for (const interceptor of this.interceptors) { interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); } return interceptorPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); } } }); }); }); } /** * Used to set the menu label, target iframe URL, and dimensions for your calling extension. * @summary Configure a calling extension * @param appId The ID of the target app. * @param settingsRequest Settings state to create with. */ public async create (appId: number, settingsRequest: SettingsRequest, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: SettingsResponse; }> { const localVarPath = this.basePath + '/crm/v3/extensions/calling/{appId}/settings' .replace('{' + 'appId' + '}', encodeURIComponent(String(appId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders); const produces = ['application/json', '*/*']; // give precedence to 'application/json' if (produces.indexOf('application/json') >= 0) { localVarHeaderParams.Accept = 'application/json'; } else { localVarHeaderParams.Accept = produces.join(','); } let localVarFormParams: any = {}; // verify required parameter 'appId' is not null or undefined if (appId === null || appId === undefined) { throw new Error('Required parameter appId was null or undefined when calling create.'); } // verify required parameter 'settingsRequest' is not null or undefined if (settingsRequest === null || settingsRequest === undefined) { throw new Error('Required parameter settingsRequest was null or undefined when calling create.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(settingsRequest, "SettingsRequest") }; let authenticationPromise = Promise.resolve(); if (this.authentications.developer_hapikey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.developer_hapikey.applyToRequest(localVarRequestOptions)); } authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); let interceptorPromise = authenticationPromise; for (const interceptor of this.interceptors) { interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); } return interceptorPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: SettingsResponse; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "SettingsResponse"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); } } }); }); }); } /** * Returns the calling extension settings configured for your app. * @summary Get calling settings * @param appId The ID of the target app. */ public async getById (appId: number, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: SettingsResponse; }> { const localVarPath = this.basePath + '/crm/v3/extensions/calling/{appId}/settings' .replace('{' + 'appId' + '}', encodeURIComponent(String(appId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders); const produces = ['application/json', '*/*']; // give precedence to 'application/json' if (produces.indexOf('application/json') >= 0) { localVarHeaderParams.Accept = 'application/json'; } else { localVarHeaderParams.Accept = produces.join(','); } let localVarFormParams: any = {}; // verify required parameter 'appId' is not null or undefined if (appId === null || appId === undefined) { throw new Error('Required parameter appId was null or undefined when calling getById.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); if (this.authentications.developer_hapikey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.developer_hapikey.applyToRequest(localVarRequestOptions)); } authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); let interceptorPromise = authenticationPromise; for (const interceptor of this.interceptors) { interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); } return interceptorPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: SettingsResponse; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "SettingsResponse"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); } } }); }); }); } /** * Updates existing calling extension settings. * @summary Update settings * @param appId The ID of the target app. * @param settingsPatchRequest Updated details for the settings. */ public async update (appId: number, settingsPatchRequest: SettingsPatchRequest, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: SettingsResponse; }> { const localVarPath = this.basePath + '/crm/v3/extensions/calling/{appId}/settings' .replace('{' + 'appId' + '}', encodeURIComponent(String(appId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders); const produces = ['application/json', '*/*']; // give precedence to 'application/json' if (produces.indexOf('application/json') >= 0) { localVarHeaderParams.Accept = 'application/json'; } else { localVarHeaderParams.Accept = produces.join(','); } let localVarFormParams: any = {}; // verify required parameter 'appId' is not null or undefined if (appId === null || appId === undefined) { throw new Error('Required parameter appId was null or undefined when calling update.'); } // verify required parameter 'settingsPatchRequest' is not null or undefined if (settingsPatchRequest === null || settingsPatchRequest === undefined) { throw new Error('Required parameter settingsPatchRequest was null or undefined when calling update.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'PATCH', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(settingsPatchRequest, "SettingsPatchRequest") }; let authenticationPromise = Promise.resolve(); if (this.authentications.developer_hapikey.apiKey) { authenticationPromise = authenticationPromise.then(() => this.authentications.developer_hapikey.applyToRequest(localVarRequestOptions)); } authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); let interceptorPromise = authenticationPromise; for (const interceptor of this.interceptors) { interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); } return interceptorPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: SettingsResponse; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "SettingsResponse"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); } } }); }); }); } }
the_stack
import { EnvVarKeys, getEnvVars, getStartingPositionsForTests } from "./utils/testUtils"; import { EventHubConsumerClient, EventHubProducerClient, EventPosition, ReceivedEventData, Subscription } from "../../src"; import { AmqpAnnotatedMessage } from "@azure/core-amqp"; import { BodyTypes } from "../../src/dataTransformer"; import { Buffer } from "buffer"; import chai from "chai"; import chaiAsPromised from "chai-as-promised"; import chaiExclude from "chai-exclude"; import { createMockServer } from "./utils/mockService"; import { testWithServiceTypes } from "./utils/testWithServiceTypes"; import { v4 } from "uuid"; const should = chai.should(); chai.use(chaiAsPromised); chai.use(chaiExclude); const assert = chai.assert; testWithServiceTypes((serviceVersion) => { const env = getEnvVars(); if (serviceVersion === "mock") { let service: ReturnType<typeof createMockServer>; before("Starting mock service", () => { service = createMockServer(); return service.start(); }); after("Stopping mock service", () => { return service?.stop(); }); } describe("AmqpAnnotatedMessage", function(): void { let producerClient: EventHubProducerClient; let consumerClient: EventHubConsumerClient; const service = { connectionString: env[EnvVarKeys.EVENTHUB_CONNECTION_STRING], path: env[EnvVarKeys.EVENTHUB_NAME] }; before("validate environment", function(): void { should.exist( env[EnvVarKeys.EVENTHUB_CONNECTION_STRING], "define EVENTHUB_CONNECTION_STRING in your environment before running integration tests." ); should.exist( env[EnvVarKeys.EVENTHUB_NAME], "define EVENTHUB_NAME in your environment before running integration tests." ); }); beforeEach(async () => { producerClient = new EventHubProducerClient(service.connectionString, service.path); consumerClient = new EventHubConsumerClient( EventHubConsumerClient.defaultConsumerGroupName, service.connectionString, service.path ); }); afterEach("close the connection", async function(): Promise<void> { await producerClient.close(); await consumerClient.close(); }); function getSampleAmqpAnnotatedMessage(): AmqpAnnotatedMessage { const randomTag = Math.random().toString(); return { body: `message body ${randomTag}`, bodyType: "data", applicationProperties: { propOne: 1, propTwo: "two", propThree: true, propFour: Date() }, footer: { propFooter: "foot" }, messageAnnotations: { propMsgAnnotate: "annotation" }, properties: { contentEncoding: "application/json; charset=utf-8", correlationId: randomTag, messageId: v4() } } as AmqpAnnotatedMessage; } /** * Helper function that will receive a single event that comes after the starting positions. * * Note: Call this after sending a single event to Event Hubs to validate * @internal */ async function receiveEvent(startingPositions: { [partitionId: string]: EventPosition; }): Promise<ReceivedEventData> { return new Promise<ReceivedEventData>((resolve, reject) => { const subscription: Subscription = consumerClient.subscribe( { async processError(err) { reject(err); return subscription.close(); }, async processEvents(events) { if (events.length) { resolve(events[0]); return subscription.close(); } } }, { startPosition: startingPositions } ); }); } async function sendEvents( messages: AmqpAnnotatedMessage[], { useBatch }: { useBatch: boolean } ) { if (!useBatch) { return producerClient.sendBatch(messages); } const batch = await producerClient.createBatch(); for (const message of messages) { assert.isTrue(batch.tryAdd(message)); } return producerClient.sendBatch(batch); } describe("round-tripping AMQP encoding/decoding", () => { [{ useBatch: true }, { useBatch: false }].forEach(({ useBatch }) => { it(`props (useBatch: ${useBatch})`, async () => { const startingPositions = await getStartingPositionsForTests(consumerClient); const testMessage = getSampleAmqpAnnotatedMessage(); await sendEvents([testMessage], { useBatch }); const event = await receiveEvent(startingPositions); should.equal(event.body, testMessage.body, "Unexpected body on the received event."); should.equal( event.getRawAmqpMessage().messageAnnotations!["propMsgAnnotate"], testMessage.messageAnnotations!["propMsgAnnotate"], "Unexpected messageAnnotations on the received event." ); assert.deepEqualExcluding( event.getRawAmqpMessage(), testMessage, ["deliveryAnnotations", "body", "messageAnnotations", "header", "properties"], "Unexpected on the AmqpAnnotatedMessage" ); assert.deepEqualExcluding( event.getRawAmqpMessage().footer!, testMessage.footer!, ["deliveryCount"], "Unexpected header on the AmqpAnnotatedMessage" ); assert.deepEqualExcluding( event.getRawAmqpMessage().properties!, testMessage.properties!, ["creationTime", "absoluteExpiryTime", "groupId"], "Unexpected properties on the AmqpAnnotatedMessage" ); assert.equal( event.getRawAmqpMessage().properties!.groupId, testMessage.properties!.groupId, "Unexpected session-id on the AmqpAnnotatedMessage" ); }); it(`values (useBatch: ${useBatch})`, async () => { const valueTypes = [[1, 2, 3], 1, 1.5, "hello", { hello: "world" }]; for (const valueType of valueTypes) { const startingPositions = await getStartingPositionsForTests(consumerClient); await sendEvents( [ { body: valueType, bodyType: "value" } ], { useBatch } ); const event = await receiveEvent(startingPositions); assert.deepEqual( event.getRawAmqpMessage().bodyType, "value", `Should be identified as a value: ${valueType.toString()}` ); assert.deepEqual( event.body, valueType, `Deserialized body should be equal: ${valueType.toString()}` ); } }); it(`sequences (useBatch: ${useBatch})`, async () => { const sequenceTypes = [ [[1], [2], [3]], [1, 2, 3] ]; for (const sequenceType of sequenceTypes) { const startingPositions = await getStartingPositionsForTests(consumerClient); await sendEvents( [ { body: sequenceType, bodyType: "sequence" } ], { useBatch } ); const event = await receiveEvent(startingPositions); assert.deepEqual( event.getRawAmqpMessage().bodyType, "sequence", `Should be identified as a value: ${sequenceType.toString()}` ); assert.deepEqual( event.body, sequenceType, `Deserialized body should be equal: ${sequenceType.toString()}` ); } }); it(`data (useBatch: ${useBatch})`, async () => { const buff = Buffer.from("hello", "utf8"); const dataTypes = [1, 1.5, "hello", { hello: "world" }, buff, [1, 2, 3]]; for (const dataType of dataTypes) { const startingPositions = await getStartingPositionsForTests(consumerClient); await sendEvents( [ { body: dataType, bodyType: "data" } ], { useBatch } ); const event = await receiveEvent(startingPositions); assert.deepEqual( event.getRawAmqpMessage().bodyType, "data", `Should be identified as data: ${dataType.toString()}` ); assert.deepEqual( event.body, dataType, `Deserialized body should be equal: : ${dataType.toString()}` ); } }); ([ ["sequence", [1, 2, 3]], ["value", "hello"], ["data", "hello"] ] as [BodyTypes, any][]).forEach(([expectedBodyType, expectedBody]) => { it(`receive ${expectedBodyType} EventData and resend (useBatch: ${useBatch})`, async () => { let startingPositions = await getStartingPositionsForTests(consumerClient); // if we receive an event that was encoded to a non-data section // and then re-send it (again, as an EventData) we should // respect it. await sendEvents( [ { body: expectedBody, bodyType: expectedBodyType } ], { useBatch } ); const event = await receiveEvent(startingPositions); assert.equal(event.getRawAmqpMessage().bodyType, expectedBodyType); startingPositions = await getStartingPositionsForTests(consumerClient); // now let's just resend it, unaltered await sendEvents([event], { useBatch }); const reencodedEvent = await receiveEvent(startingPositions); assert.equal(reencodedEvent.getRawAmqpMessage().bodyType, expectedBodyType); assert.deepEqual(reencodedEvent.body, expectedBody); }); }); }); }); }); });
the_stack
import { INodeProperties } from 'n8n-workflow'; export const userOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', displayOptions: { show: { resource: [ 'user', ], }, }, options: [ { name: 'Create', value: 'create', description: 'Create a user', }, // { // name: 'Delete', // value: 'delete', // description: 'Delete a user', // }, { name: 'Get', value: 'get', description: 'Get a user', }, { name: 'Get All', value: 'getAll', description: 'Get all users', }, { name: 'Update', value: 'update', description: 'Update a user', }, ], default: 'create', description: 'The operation to perform.', }, ]; export const userFields: INodeProperties[] = [ /* -------------------------------------------------------------------------- */ /* user:create */ /* -------------------------------------------------------------------------- */ { displayName: 'Username', name: 'username', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'create', ], }, }, description: 'Login name for the user.', }, { displayName: 'Name', name: 'name', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'create', ], }, }, description: 'Display name for the user.', }, { displayName: 'First Name', name: 'firstName', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'create', ], }, }, description: 'First name for the user.', }, { displayName: 'Last Name', name: 'lastName', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'create', ], }, }, description: 'Last name for the user.', }, { displayName: 'Email', name: 'email', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'create', ], }, }, description: 'The email address for the user.', }, { displayName: 'Password', name: 'password', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'create', ], }, }, description: 'Password for the user (never included)', }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'user', ], operation: [ 'create', ], }, }, options: [ { displayName: 'URL', name: 'url', type: 'string', default: '', description: 'URL of the user.', }, { displayName: 'Description', name: 'description', typeOptions: { alwaysOpenEditWindow: true, }, type: 'string', default: '', description: 'Description of the user.', }, { displayName: 'Nickname', name: 'nickname', type: 'string', default: '', description: 'The nickname for the user.', }, { displayName: 'Slug', name: 'slug', type: 'string', default: '', description: 'An alphanumeric identifier for the user.', }, ], }, /* -------------------------------------------------------------------------- */ /* user:update */ /* -------------------------------------------------------------------------- */ { displayName: 'User ID', name: 'userId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'update', ], }, }, description: 'Unique identifier for the user.', }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'user', ], operation: [ 'update', ], }, }, options: [ { displayName: 'Username', name: 'username', type: 'string', default: '', description: 'Login name for the user.', }, { displayName: 'Name', name: 'name', type: 'string', default: '', description: 'Display name for the user.', }, { displayName: 'First Name', name: 'firstName', type: 'string', default: '', description: 'First name for the user.', }, { displayName: 'Last Name', name: 'lastName', type: 'string', default: '', description: 'Last name for the user.', }, { displayName: 'Email', name: 'email', type: 'string', default: '', description: 'The email address for the user.', }, { displayName: 'Password', name: 'password', type: 'string', default: '', description: 'Password for the user (never included)', }, { displayName: 'URL', name: 'url', type: 'string', default: '', description: 'URL of the user.', }, { displayName: 'Description', name: 'description', typeOptions: { alwaysOpenEditWindow: true, }, type: 'string', default: '', description: 'Description of the user.', }, { displayName: 'Nickname', name: 'nickname', type: 'string', default: '', description: 'The nickname for the user.', }, { displayName: 'Slug', name: 'slug', type: 'string', default: '', description: 'An alphanumeric identifier for the user.', }, ], }, /* -------------------------------------------------------------------------- */ /* user:get */ /* -------------------------------------------------------------------------- */ { displayName: 'User ID', name: 'userId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'get', ], }, }, description: 'Unique identifier for the user.', }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Option', default: {}, displayOptions: { show: { resource: [ 'user', ], operation: [ 'get', ], }, }, options: [ { displayName: 'Context', name: 'context', type: 'options', options: [ { name: 'View', value: 'view', }, { name: 'Embed', value: 'embed', }, { name: 'Edit', value: 'edit', }, ], default: 'view', description: 'Scope under which the request is made; determines fields present in response.', }, ], }, /* -------------------------------------------------------------------------- */ /* user:getAll */ /* -------------------------------------------------------------------------- */ { displayName: 'Return All', name: 'returnAll', type: 'boolean', displayOptions: { show: { resource: [ 'user', ], operation: [ 'getAll', ], }, }, default: false, description: 'If all results should be returned or only up to a given limit.', }, { displayName: 'Limit', name: 'limit', type: 'number', displayOptions: { show: { resource: [ 'user', ], operation: [ 'getAll', ], returnAll: [ false, ], }, }, typeOptions: { minValue: 1, maxValue: 10, }, default: 5, description: 'How many results to return.', }, { displayName: 'Options', name: 'options', type: 'collection', placeholder: 'Add Option', default: {}, displayOptions: { show: { resource: [ 'user', ], operation: [ 'getAll', ], }, }, options: [ { displayName: 'Context', name: 'context', type: 'options', options: [ { name: 'View', value: 'view', }, { name: 'Embed', value: 'embed', }, { name: 'Edit', value: 'edit', }, ], default: 'view', description: 'Scope under which the request is made; determines fields present in response.', }, { displayName: 'Order By', name: 'orderBy', type: 'options', options: [ { name: 'Email', value: 'email', }, { name: 'ID', value: 'id', }, { name: 'Include', value: 'include', }, { name: 'Include Slugs', value: 'include_slugs', }, { name: 'Name', value: 'name', }, { name: 'Registered Date', value: 'registered_date', }, { name: 'Slug', value: 'slug', }, { name: 'URL', value: 'url', }, ], default: 'id', description: 'Sort collection by object attribute.', }, { displayName: 'Order', name: 'order', type: 'options', options: [ { name: 'ASC', value: 'asc', }, { name: 'DESC', value: 'desc', }, ], default: 'desc', description: 'Order sort attribute ascending or descending.', }, { displayName: 'Search', name: 'search', type: 'string', default: '', description: 'Limit results to those matching a string.', }, { displayName: 'Who', name: 'who', type: 'options', options: [ { name: 'Authors', value: 'authors', }, ], default: 'authors', description: 'Limit result set to users who are considered authors.', }, ], }, /* -------------------------------------------------------------------------- */ /* user:delete */ /* -------------------------------------------------------------------------- */ { displayName: 'Reassign', name: 'reassign', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'user', ], operation: [ 'delete', ], }, }, description: `Reassign the deleted user's posts and links to this user ID.`, }, ];
the_stack
import {TypedNode, BaseNodeType} from '../../../nodes/_Base'; import {SceneJsonImporter} from '../../../io/json/import/Scene'; import {NodeContext} from '../../../poly/NodeContext'; import {NodeJsonExporterData} from '../export/Node'; import {ParamJsonImporter} from './Param'; import {Poly} from '../../../Poly'; import {OperationsComposerSopNode} from '../../../nodes/sop/OperationsComposer'; import {SopOperationContainer} from '../../../../engine/operations/container/sop'; import {OPERATIONS_COMPOSER_NODE_TYPE} from '../../../operations/_Base'; import {CoreType} from '../../../../core/Type'; import {PolyDictionary} from '../../../../types/GlobalTypes'; type BaseNodeTypeWithIO = TypedNode<NodeContext, any>; interface RootNodeGenericData { outputs_count: number; non_optimized_count: number; } export class OptimizedNodesJsonImporter<T extends BaseNodeTypeWithIO> { constructor(protected _node: T) {} private _nodes: BaseNodeTypeWithIO[] = []; private _optimized_root_node_names: Set<string> = new Set(); private _operation_containers_by_name: Map<string, SopOperationContainer> = new Map(); nodes() { return this._nodes; } process_data(scene_importer: SceneJsonImporter, data?: PolyDictionary<NodeJsonExporterData>) { if (!data) { return; } if (!(this._node.childrenAllowed() && this._node.childrenController)) { return; } const {optimized_names} = OptimizedNodesJsonImporter.child_names_by_optimized_state(data); this._nodes = []; this._optimized_root_node_names = new Set(); for (let node_name of optimized_names) { if (OptimizedNodesJsonImporter.is_optimized_root_node(data, node_name)) { this._optimized_root_node_names.add(node_name); } } for (let node_name of this._optimized_root_node_names) { const node_data = data[node_name]; const node = this._node.createNode(OPERATIONS_COMPOSER_NODE_TYPE); if (node) { node.setName(node_name); this._nodes.push(node); // ensure the display flag is set accordingly if (node_data.flags?.display) { node.flags?.display?.set(true); } const operation_container = this._create_operation_container( scene_importer, node as OperationsComposerSopNode, node_data, node.name() ); (node as OperationsComposerSopNode).set_output_operation_container( operation_container as SopOperationContainer ); } } for (let node of this._nodes) { const operation_container = (node as OperationsComposerSopNode).output_operation_container(); if (operation_container) { this._node_inputs = []; this._add_optimized_node_inputs( scene_importer, node as OperationsComposerSopNode, data, node.name(), operation_container ); node.io.inputs.setCount(this._node_inputs.length); for (let i = 0; i < this._node_inputs.length; i++) { node.setInput(i, this._node_inputs[i]); } } } } private _node_inputs: BaseNodeType[] = []; private _add_optimized_node_inputs( scene_importer: SceneJsonImporter, node: OperationsComposerSopNode, data: PolyDictionary<NodeJsonExporterData>, node_name: string, current_operation_container: SopOperationContainer ) { const node_data: NodeJsonExporterData = data[node_name]; const inputs_data = node_data['inputs']; if (!inputs_data) { return; } for (let input_data of inputs_data) { if (CoreType.isString(input_data)) { const input_node_data = data[input_data]; if (input_node_data) { if ( OptimizedNodesJsonImporter.is_node_optimized(input_node_data) && !this._optimized_root_node_names.has(input_data) // ensure it is not a root ) { // ensure we do not create multiple operation containers from the same node let operation_container = this._operation_containers_by_name.get(input_data); if (!operation_container) { // if the input is an optimized node, we create an operation and go recursive operation_container = this._create_operation_container( scene_importer, node, input_node_data, input_data ) as SopOperationContainer; if (operation_container) { this._add_optimized_node_inputs( scene_importer, node, data, input_data, operation_container ); } } current_operation_container.add_input(operation_container); } else { // if the input is NOT an optimized node, we set the input to the node const input_node = node.parent()?.node(input_data); if (input_node) { this._node_inputs.push(input_node); const node_input_index = this._node_inputs.length - 1; // node.setInput(node_input_index, input_node as BaseSopNodeType); node.add_input_config(current_operation_container, { operation_input_index: current_operation_container.current_input_index(), node_input_index: node_input_index, }); current_operation_container.increment_input_index(); } } } } } // once the inputs have been set, we can initialize the inputs_clone_state if (node_data.cloned_state_overriden == true) { current_operation_container.override_input_clone_state(node_data.cloned_state_overriden); } } static child_names_by_optimized_state(data: PolyDictionary<NodeJsonExporterData>) { const node_names = Object.keys(data); const optimized_names: string[] = []; const non_optimized_names: string[] = []; for (let node_name of node_names) { const node_data = data[node_name]; const optimized_state = Poly.playerMode() && this.is_node_optimized(node_data); if (optimized_state) { optimized_names.push(node_name); } else { non_optimized_names.push(node_name); } } return {optimized_names, non_optimized_names}; } // private _optimized_names_for_root( // data: PolyDictionary<NodeJsonExporterData>, // current_node_name: string, // current_node_data: NodeJsonExporterData, // input_names: string[] = [] // ) { // input_names.push(current_node_name); // const inputs = current_node_data['inputs']; // if (inputs) { // for (let input_data of inputs) { // if (CoreType.isString(input_data)) { // const input_node_name = input_data; // // if (input_node_name != current_node_name) { // const input_node_data = data[input_node_name]; // if (input_node_data) { // if ( // OptimizedNodesJsonImporter.is_node_optimized(input_node_data) && // !this._is_optimized_root_node(data, input_node_name, input_node_data) // ) { // this._optimized_names_for_root(data, input_node_name, input_node_data, input_names); // } // } // // } // } // } // } // return input_names; // } // a node will be considered optimized root node if: // - it has no output // - at least one output is not optimized (as it if it has 2 outputs, and only 1 is optimized, it will not be considered root) static is_optimized_root_node_generic(data: RootNodeGenericData): boolean { if (data.outputs_count == 0) { return true; } if (data.non_optimized_count > 0) { return true; } return false; } static is_optimized_root_node(data: PolyDictionary<NodeJsonExporterData>, current_node_name: string) { const output_names = this.node_outputs(data, current_node_name); let non_optimized_count = 0; output_names.forEach((node_name) => { const node_data = data[node_name]; if (!this.is_node_optimized(node_data)) { non_optimized_count++; } }); return this.is_optimized_root_node_generic({ outputs_count: output_names.size, non_optimized_count: non_optimized_count, }); } // same algo as is_optimized_root_node, but for a node static is_optimized_root_node_from_node<NC extends NodeContext>(node: TypedNode<NC, any>) { if (!node.flags?.optimize?.active()) { return false; } const output_nodes = node.io.connections.outputConnections().map((c) => c.node_dest); let non_optimized_count = 0; for (let output_node of output_nodes) { if (!output_node.flags?.optimize?.active()) { non_optimized_count++; } } return this.is_optimized_root_node_generic({ outputs_count: output_nodes.length, non_optimized_count: non_optimized_count, }); } static node_outputs( data: PolyDictionary<NodeJsonExporterData>, current_node_name: string // current_node_data: NodeJsonExporterData ) { const node_names = Object.keys(data); const output_node_names: Set<string> = new Set(); for (let node_name of node_names) { if (node_name != current_node_name) { const node_data = data[node_name]; const inputs = node_data['inputs']; if (inputs) { for (let input_data of inputs) { if (CoreType.isString(input_data)) { const input_node_name = input_data; if (input_node_name == current_node_name) { output_node_names.add(node_name); } } } } } } return output_node_names; } private _create_operation_container( scene_importer: SceneJsonImporter, node: OperationsComposerSopNode, node_data: NodeJsonExporterData, node_name: string ) { const non_spare_params_data = ParamJsonImporter.non_spare_params_data_value(node_data['params']); const operation_type = OptimizedNodesJsonImporter.operation_type(node_data); const operation_container = this._node.create_operation_container( operation_type, node_name, non_spare_params_data ) as SopOperationContainer; if (operation_container) { // ensure we do not create another operation container from the same node this._operation_containers_by_name.set(node_name, operation_container); // store for path_param resolve when all nodes are created if (operation_container.path_param_resolve_required()) { node.add_operation_container_with_path_param_resolve_required(operation_container); scene_importer.add_operations_composer_node_with_path_param_resolve_required(node); } } return operation_container; } static operation_type(node_data: NodeJsonExporterData) { if (OptimizedNodesJsonImporter.is_node_bypassed(node_data)) { return 'null'; } return node_data['type']; } static is_node_optimized(node_data: NodeJsonExporterData) { const node_flags = node_data['flags']; if (node_flags && node_flags['optimize']) { return true; } return false; } static is_node_bypassed(node_data: NodeJsonExporterData) { const node_flags = node_data['flags']; if (node_flags && node_flags['bypass']) { return true; } return false; } }
the_stack
import { Vec3, v3, IVec3, IVec2 } from '../math/Vec3'; import { Vec2 } from '../math/Vec2'; import { quat, Quat } from '../math/Quat'; import { Path } from '../struct/3d/Path'; import { clone, rotateByUnitVectors, angle } from './common'; import { applyMat4, translate } from './pointset'; import { indexable } from '../render/mesh'; import { AxisPlane, triangulation } from './trianglution'; import { flat, unique } from '../utils/array'; import { isDefined, isUndefined } from '../utils/types'; import { m4 } from '../math/Mat4'; import { IGeometry } from '../render/geometry'; import { RADIANS_PER_DEGREE } from '../math/Math'; import vector from '../math/vector'; import { ArrayList } from '../struct/data/ArrayList'; import { Distance } from '../basic/distance'; export interface ILinkSideOption { side0: { x: number, y: number, z: number, index?: number }[] | number[];//可能是点 也可能是索引 side1: { x: number, y: number, z: number, index?: number }[] | number[]; holes0?: Array<Array<Vec3>>; holes1?: Array<Array<Vec3>>; shapeClosed?: boolean; autoUV?: boolean; uvScalars?: number[], segs?: [] } /** * 常用shape几何操作 */ /** * @description : 缝合两个边 不提供uv生成 uv有@linkSides 生成 * @param { ILinkSideOption } options * @returns { Array<Vec3>} 三角形数组,每三个为一个三角形 * @example : */ export function linkSide(options: ILinkSideOption) { options = { shapeClosed: true, autoUV: true, ...options }; const side0: any = options.side0; const side1: any = options.side1; const shapeClosed = options.shapeClosed; if (side0.length !== side1.length) throw ("拉伸两边的点数量不一致 linkSide"); if (side0.length < 2 || side1.length < 2) return []; var orgLen = side0.length; var length = shapeClosed ? side0.length : side0.length - 1; var triangles: number[] = []; if (side0[0] instanceof Number) { //索引三角形 for (var i = 0; i < length; i++) { var v00 = side0[i]; var v01 = side0[(i + 1) % orgLen]; var v10 = side1[i]; var v11 = side1[(i + 1) % orgLen]; triangles.push(v00); triangles.push(v01); triangles.push(v11); triangles.push(v00); triangles.push(v11); triangles.push(v10); } } else { if (isDefined(side0[0].index)) { //含索引的顶点 for (var i = 0; i < length; i++) { var v00 = side0[i]; var v01 = side0[(i + 1) % orgLen]; var v10 = side1[i]; var v11 = side1[(i + 1) % orgLen]; triangles.push(v00.index); triangles.push(v01.index); triangles.push(v11.index); triangles.push(v00.index); triangles.push(v11.index); triangles.push(v10.index); } } else { //三角形顶点 for (var i = 0; i < length; i++) { var v00 = side0[i]; var v01 = side0[(i + 1) % orgLen]; var v10 = side1[i]; var v11 = side1[(i + 1) % orgLen]; triangles.push(v00); triangles.push(v01); triangles.push(v11); triangles.push(v00); triangles.push(v11); triangles.push(v10); } } } if (options.holes0 && options.holes1) { const holes0 = options.holes0; const holes1 = options.holes1; for (let h = 0; h < holes0.length; h++) { const holeTriangles: any = linkSide({ side0: holes0[h], side1: holes1[h] }) holeTriangles.reverse(); triangles.push(...holeTriangles); } } return triangles; } /** * 缝合shape集合 * @param {Array<Array<Point|Vec3>} shapes 路基 点集的集合, 每个shape的点数量一致 * @param {Boolean} sealStart 每一个shape是否是封闭的界面 默认false * @param {Boolean} isClosed 每一个shape是否是封闭的界面 默认false * @param {Boolean} isClosed2 每一个shape是否是封闭的首尾 默认false * @returns {Array} 返回三角形集合 如果有所用范围索引,否则返回顶点 */ export interface ILinkSideOptions { shapes: Array<Array<IVec3 | any | IVec3>>; orgShape?: Array<IVec3 | any | IVec3>; orgHoles?: any; sealStart?: boolean,//开始封面 sealEnd?: boolean;//结束封面 shapeClosed?: boolean,//shape是否闭合 pathClosed?: boolean,//路径是否闭合 index?: { index: number }, autoIndex?: boolean generateUV?: boolean axisPlane?: AxisPlane holes?: Array<Array<IVec3 | any | IVec3>>[] } /** * @description : 链接多个shape 生成几何体 * @param {ILinkSideOptions} optionsILinkSideOptions { * shapes: Array<Array<IVec3 | number | any>>; * sealStart?: boolean,//开始封面 * sealEnd?: boolean;//结束封面 * shapeClosed?: boolean,//shape是否闭合 * pathClosed?: boolean,//路径是否闭合 * index?: { index: number }, * generateUV?: boolean * } * * @return {*} * @example : * */ export function linkSides(options: ILinkSideOptions): IGeometry { options = { sealEnd: true, sealStart: true, shapeClosed: true, pathClosed: false, generateUV: true, autoIndex: true, axisPlane: AxisPlane.XY, ...options } if (options.autoIndex) options.index = options.index || { index: 0 }; const shapes = options.shapes; const holess = options.holes; const hasHole: boolean = !!(holess && holess.length > 0); var length = options.pathClosed ? shapes.length : shapes.length - 1; var triangles: any = []; const index = options.index; var allVertics = [shapes]; if (hasHole) allVertics.push(holess as any); var orgShape = options.orgShape || shapes[0]; var orgHoles = options.orgHoles || (holess && holess[0]); if (index) indexable(allVertics, index); for (var i = 0; i < length; i++) { if (holess) triangles.push(...linkSide({ side0: shapes[i], side1: shapes[(i + 1) % shapes.length], holes0: holess[i], holes1: holess[(i + 1) % shapes.length], shapeClosed: options.shapeClosed })); else triangles.push(...linkSide({ side0: shapes[i], side1: shapes[(i + 1) % shapes.length], shapeClosed: options.shapeClosed })); } if (options.sealStart) { const startShape = clone(shapes[0]); allVertics.push(startShape); if (holess && holess[0]) { var startHoles = clone(holess[0]) allVertics.push(startHoles) } var startTris = triangulation(orgShape, orgHoles, { feature: AxisPlane.XYZ }); if (index) { startTris.forEach((v: number, i: number) => { startTris[i] = v + index?.index; }) index.index += startShape.length if (holess && holess[0]) startHoles.forEach((h: any) => { index.index += h.length }) } triangles.push(...startTris.reverse()); } if (options.sealEnd) { const endShape = clone(shapes[shapes.length - 1]); allVertics.push(endShape); if (holess && holess[0]) { var endHoles = clone(clone(holess[holess.length - 1])); allVertics.push(endHoles) } var endTris = triangulation(orgShape, orgHoles, { feature: AxisPlane.XYZ }); if (index) { endTris.forEach((v: number, i: number) => { endTris[i] = v + index?.index; }) index.index += endShape.length if (holess && holess[0]) endHoles.forEach((h: any) => { index.index += h.length }) } triangles.push(...endTris); } triangles.shapes = allVertics; var uvs = [] if (options.generateUV) { //生成UV // let uBasicScalar = new Array(shapes[0].length).fill(0); let uBasicScalar = 0; for (let i = 0; i < shapes.length; i++) { const shape: Vec3[] = shapes[i] as unknown as Vec3[]; const lastshape: Vec3[] = shapes[i - 1] as unknown as Vec3[]; if (isNaN(shape[0] as any)) { //不是索引才生产纹理,其他都是顶点 var vScalar = Path.getPerMileages(shape, false); var uScalar = 0; // if (i > 0) // uScalar = uBasicScalar.map((e, k) => { // return e + shape[k].distanceTo(lastshape[k]); // }); // else // uScalar = new Array(shapes[0].length).fill(0); if (i > 0) uScalar = uBasicScalar + shape[0].distanceTo(lastshape[0]); for (let l = 0; l < shape.length; l++) { uvs.push(uScalar, vScalar[l]); } uBasicScalar = uScalar; } else console.error("索引无法生成纹理") } if (holess) { uBasicScalar = 0; for (let i = 0; i < holess.length; i++) { const holes = holess[i]; const lastHole: any = holess[i - 1]; var uScalar = 0; if (i > 0) uScalar = uBasicScalar + holes[0][0].distanceTo(lastHole[0][0]); for (let j = 0; j < holes.length; j++) { const hole: any = holes[j]; var vScalar = Path.getPerMileages(hole, false); for (let l = 0; l < hole.length; l++) { uvs.push(uScalar, vScalar[l]); } } uBasicScalar = uScalar; } } //前后纹理 var sealUvs: any = [] switch (options.axisPlane) { case AxisPlane.XY: orgShape.map(e => { sealUvs.push(e.x, e.y) }) if (orgHoles) orgHoles.forEach((h: any) => { h.forEach((e: any) => { sealUvs.push(e.x, e.y) }) }) break; case AxisPlane.XZ: orgShape.map(e => { sealUvs.push(e.x, e.z) }) if (orgHoles) orgHoles.forEach((h: any) => { h.forEach((e: any) => { sealUvs.push(e.x, e.z) }) }) break; case AxisPlane.YZ: orgShape.map(e => { sealUvs.push(e.y, e.z) }) if (orgHoles) orgHoles.forEach((h: any) => { h.forEach((e: any) => { sealUvs.push(e.y, e.z) }) }) break; default: break; } uvs.push(...sealUvs, ...sealUvs); } var indices = triangles || []; // if (isDefined(shapes[0][0].index)) { // //收集索引 // for (let i = 0; i < shapes.length; i++) { // const shape = shapes[i]; // for (let j = 0; j < shape.length; j++) { // const v = shape[j]; // indices.push(v.index); // } // } // } const positions = vector.verctorToNumbers(allVertics); shapes.pop(); shapes.pop(); return { position: positions, index: indices, uv: uvs }; } export interface IExtrudeOptions { fixedY?: boolean; shapeClosed?: boolean;//闭合为多边形 界面 isClosed2?: boolean;//首尾闭合为圈 textureEnable?: boolean; textureScale?: Vec2; smoothAngle?: number; sealStart?: boolean; sealEnd?: boolean; normal?: Vec3, } const defaultExtrudeOption: IExtrudeOptions = { textureEnable: true, textureScale: new Vec2(1, 1), smoothAngle: Math.PI / 180 * 30, sealStart: false, sealEnd: false, normal: Vec3.UnitZ, } export interface IExtrudeOptionsEx { shape: Array<Vec3 | IVec3 | Vec2 | IVec2>;//shape默认的矩阵为正交矩阵 path: Array<Vec3 | IVec3>; ups?: Array<Vec3 | IVec3>; up?: Vec3 | IVec3; right?: Vec3; shapeClosed?: boolean;//闭合为多边形 界面 pathClosed?: boolean;//首尾闭合为圈 textureEnable?: boolean; smoothAngle?: number; enableSmooth?: boolean; sealStart?: boolean; sealEnd?: boolean; normal?: Vec3, autoIndex?: boolean, axisPlane?: AxisPlane, generateUV?: boolean, index?: { index: number }, holes?: Array<Vec3 | IVec3 | Vec2 | IVec2>[] } const _matrix = m4(); const _matrix1 = m4(); const _quat = quat(); const _quat1 = quat(); const _vec1 = v3(); const _vec2 = v3(); /** * @description : 挤压形状生成几何体 * @param {IExtrudeOptionsEx} options * IExtrudeOptionsEx { * shape: Array<Vec3 | IVec3 | Vec2 | IVec2>;//shape默认的矩阵为正交矩阵 * path: Array<Vec3 | IVec3>;//挤压路径 * ups?: Array<Vec3 | IVec3>; * up?: Vec3 | IVec3; * shapeClosed?: boolean;//闭合为多边形 界面 * pathClosed?: boolean;//首尾闭合为圈 * textureEnable?: boolean; * smoothAngle?: number; * sealStart?: boolean; * sealEnd?: boolean; * normal?: Vec3,//面的法线 * autoIndex?: boolean, * index?: { index: number } * holes?: Array<Vec3 | IVec3 | Vec2 | IVec2>[] *} * @return {IGeometry} * @example : * */ export function extrude(options: IExtrudeOptionsEx): IGeometry { options = { sealEnd: true, sealStart: true, shapeClosed: true, pathClosed: false, generateUV: true, autoIndex: true, axisPlane: AxisPlane.XY, up: Vec3.Up, smoothAngle: 30 * RADIANS_PER_DEGREE, enableSmooth: false, ...options } if (!vector.isCCW(options.shape)) options.shape.reverse(); if (options.holes) options.holes.forEach((hole) => { if (!vector.isCCW(hole)) hole.reverse(); }) const path = new Path(options.path as any); const shapes = []; let shape: any = options.shape; if (options.shapeClosed && !shape[0].equals(shape[shape.length - 1])) shape.push(shape[0].clone()) let shapePath: Path<Vec3> | any = new Path(shape, options.shapeClosed); if (options.enableSmooth) for (let i = 1; i < shapePath.length; i++) { //大角度插入点 角度过大为了呈现flat shader的效果 if (shapePath.get(i).direction.dot(shapePath.get((i + 1) % shapePath.length).direction) < Math.cos(options.smoothAngle!)) { shapePath.splice(i + 1, 0, shapePath.get(i).clone()); i++; } } const ups = options.ups || []; if (isUndefined(shapePath.first.z)) { shapePath.array = shapePath.array.map((e: any) => v3(e.x, e.y, 0)); options.normal = options.normal || Vec3.UnitZ; } var up: Vec3 = options.up as Vec3; var right: Vec3 = options.right as Vec3; var newholes = []; for (let i = 0; i < options.path.length; i++) { const point = path.get(i); const direction = (point as any).direction; let upi: any; upi = ups[i] || up || v3().crossVecs(right, direction); let righti = right; if (!right) righti = v3().crossVecs(upi, direction).normalize(); _matrix.makeBasis(righti, upi, direction); _matrix.setPosition(point); var new_shape = shapePath.clone(); new_shape.applyMat4(_matrix); shapes.push(new_shape); if (options.holes) { const mholes = applyMat4(options.holes, _matrix, false); newholes.push(mholes); } } const geo: IGeometry = linkSides({ shapes: shapes.map(e => e._array), holes: newholes, orgShape: shapePath._array, orgHoles: options.holes, sealStart: options.sealStart, sealEnd: options.sealEnd, shapeClosed: options.shapeClosed, pathClosed: options.pathClosed, axisPlane: options.axisPlane, autoIndex: options.autoIndex, generateUV: options.generateUV, }) return geo; } /** * 挤压 * @param {Polygon|Array<Point|Vec3> } shape 多边形或顶点数组 * @param {Path|Array<Point|Vec3> } path 路径或者或顶点数组 * @param {Object} options { * isClosed: false,闭合为多边形 界面 * isClosed2: false, 闭合为圈 * textureEnable: true, 计算纹理坐标 * textureScale: new Vec2(1, 1),纹理坐标缩放 * smoothAngle: Math.PI / 180 * 30,大于这个角度则不平滑 * sealStart: true, 是否密封开始面 * sealEnd: true,是否密封结束面} */ export function extrude_obsolete<T extends Vec3>(shape: ArrayList<T>, arg_path: Array<Vec3> | any, options: IExtrudeOptions = defaultExtrudeOption) { options = { ...defaultExtrudeOption, ...options } if (arg_path.length < 2) { throw ("路径节点数必须大于2") } var isCCW = vector.isCCW(shape); if (!isCCW) shape.reverse(); var normal = options.normal; var startSeal = clone(shape); var shapepath = new Path(shape as any); var insertNum = 0; for (let i = 1; i < shapepath.length - 1; i++) { //大角度插入点 角度过大为了呈现flat shader的效果 if (Math.acos(shapepath.get(i).tangent.dot(shapepath.get(i + 1).tangent)) > options.smoothAngle!) shape.splice(i + insertNum++, 0, shapepath.get(i).clone()); } if (options.shapeClosed) { var dir1 = shapepath.get(-1).clone().sub(shapepath.get(-2)).normalize(); var dir2 = shapepath.get(0).clone().sub(shapepath.get(-1)).normalize(); if (Math.acos(dir1.dot(dir2)) > options.smoothAngle!) shape.push((<any>shape).get(-1).clone()); //新加起始点纹理拉伸 shape.unshift(shape.first.clone()); } let path = arg_path; if (!(path instanceof Path) && path instanceof Array) path = new Path(arg_path); const shapeArray = []; for (let i = 0; i < path.length; i++) { const node = path[i]; var dir = node.tangent; var newShape = clone(shape); rotateByUnitVectors(newShape, normal!, dir); if (options.fixedY) { var v = Vec3.UnitX; rotateByUnitVectors([v], normal!, dir); var v1 = v.clone(); v1.y = 0; rotateByUnitVectors(newShape, v, v1); } translate(newShape, node); shapeArray.push(newShape); } const gindex = { index: 0 }; var vertices = flat(shapeArray); indexable(vertices, gindex); var { index } = linkSides({ shapes: shapeArray, shapeClosed: options.shapeClosed, pathClosed: options.isClosed2, orgShape: shape as any }); shapepath = new Path(shape as any); var uvs = []; for (let i = 0; i < path.length; i++) { for (let j = 0; j < shapepath.length; j++) { uvs.push(shapepath.get(j).tlen * options.textureScale!.x, path.get(i).tlen * options.textureScale!.y); } } var sealUv = clone(startSeal); if (normal!.dot(Vec3.UnitZ) < 1 - 1e-4) rotateByUnitVectors(sealUv, normal!, Vec3.UnitZ); var endSeal = clone(startSeal); rotateByUnitVectors(startSeal, normal!, path[0].tangent); if (options.fixedY) { var v = Vec3.UnitX; rotateByUnitVectors([v], normal!, path[0].tangent); var v1 = v.clone(); v1.y = 0; rotateByUnitVectors(startSeal, v, v1); } translate(startSeal, path[0]) rotateByUnitVectors(endSeal, normal!, path.get(-1).tangent); if (options.fixedY) { var v = Vec3.UnitX; rotateByUnitVectors([v], normal!, path.get(-1).tangent); var v1 = v.clone(); v1.y = 0; rotateByUnitVectors(endSeal, v, v1); } translate(endSeal, path.get(-1)); var sealStartTris = triangulation(sealUv, [], { normal: normal! }); sealStartTris.reverse(); if (options.sealStart) indexable(startSeal, gindex); if (options.sealEnd) indexable(endSeal, gindex); var sealEndTris = [] var hasVLen = vertices.length; if (options.sealStart) for (let i = 0; i < sealStartTris.length; i++) { sealStartTris[i] += hasVLen; } if (options.sealEnd && !options.sealStart) for (let i = 0; i < sealStartTris.length; i++) { sealEndTris[i] = sealStartTris[i] + hasVLen; } if (options.sealEnd && options.sealStart) { for (let i = 0; i < sealStartTris.length; i++) { sealEndTris[i] = sealStartTris[i] + startSeal.length; } } if (options.sealStart) { vertices.push(...startSeal); index!.push(...sealStartTris); for (let i = 0; i < sealUv.length; i++) uvs.push(sealUv[i].x, sealUv[i].y); } if (options.sealEnd) { vertices.push(...endSeal); sealEndTris.reverse(); index!.push(...sealEndTris); for (let i = 0; i < sealUv.length; i++) uvs.push(sealUv[i].x, sealUv[i].y); } return { vertices, index, uvs }; } export enum JoinType { Square = 0, Round, Miter, Bevel = 0, } export enum EndType { Square, Round, Butt, etClosedLine, etClosedPolygon, etOpenButt, etOpenSquare } export interface IExtrudeOptionsNext { shape: Array<Vec3>;//shape默认的矩阵为正交矩阵 path: Array<Vec3 | IVec3>; up?: Array<Vec3 | IVec3> | Vec3 | IVec3; right?: Array<Vec3> | Vec3; shapeClosed?: boolean;//闭合为多边形 界面 pathClosed?: boolean;//首尾闭合为圈 textureEnable?: boolean; shapeCenter?: Vec3; //shape的中心点 模型是零点 smoothAngle?: number; enableSmooth?: boolean; sealStart?: boolean; sealEnd?: boolean; normal?: Vec3, autoIndex?: boolean, axisPlane?: AxisPlane, generateUV?: boolean, index?: { index: number }, holes?: Array<Vec3 | IVec3 | Vec2 | IVec2>[] jtType?: JoinType; etType?: EndType bevelSize?: any; } /** * 将路径看做挤压操作中心 * * @param shape * @param followPath * @param options */ export function extrudeNext(options: IExtrudeOptionsNext) { options = { sealEnd: true, sealStart: true, shapeClosed: true, pathClosed: false, generateUV: true, autoIndex: true, axisPlane: AxisPlane.XY, smoothAngle: 30 * RADIANS_PER_DEGREE, enableSmooth: false, ...options } const path = options.shapeCenter ? translate(options.path, options.shapeCenter!, false) : options.path; const shape = options.shape; unique(path, (a, b) => a.equals(b)); unique(shape, (a, b) => a.equals(b)); const pathPath: Path<Vec3> = new Path(path, options.pathClosed, true); const starti = options.shapeClosed ? 0 : 1; let shapePath: Path<Vec3> | any = new Path(shape, options.shapeClosed); if (options.enableSmooth) for (let i = 1; i < shapePath.length; i++) { //大角度插入点 角度过大为了呈现flat shader的效果 if (shapePath.get(i).direction.dot(shapePath.get((i + 1) % shapePath.length).direction) < options.smoothAngle!) { shapePath.splice(i + 1, 0, shapePath.get(i).clone()); i++; } } options.normal = options.normal || Vec3.UnitZ; if (isUndefined(shapePath.first.z)) { shapePath.array = shapePath.array.map((e: any) => v3(e.x, e.y, 0)); } var up = options.up; var right = options.right; const shapes = [], newholes: any = []; const accMat = m4(); /** * 如果路径闭合 要考虑首尾shape矩阵变化后还能一致吻合 */ switch (options.jtType) { case JoinType.Square: //切角 break; case JoinType.Round://圆角 /** * 原理,计算所有交点处的平分面, * 两条相接不共线的的线段可以确定一个平面,平面法线与 */ for (let i = 0; i < pathPath.length; i++) { const p: Vec3 = pathPath.get(i); const pLast: Vec3 = pathPath.get(i - 1); const pNext: Vec3 = pathPath.get(i + 1); const dir: Vec3 = (p as any).direction; //两个外向 const bdir: Vec3 = (p as any).bdirection; const bnormal: Vec3 = (p as any).bnormal; const normal: Vec3 = (p as any).normal; //相邻两个向量发生的旋转 if (i === 0) { _quat.setFromUnitVecs(Vec3.UnitZ, dir); } else { _quat.setFromUnitVecs(pathPath.get(i - 1).direction, dir); } let new_shape: Path<Vec3> = shapePath.clone(); //旋转 _quat.setFromUnitVecs(dir, bdir); _matrix.makeRotationFromQuat(_quat); _matrix.multiply(accMat); //位置 _matrix.setPosition(p); new_shape.applyMat4(_matrix); // 找出最近一个点 绕此点旋转 let min = Infinity; let anchor = 0; for (let i = 0; i < new_shape.array.length; i++) { const p = new_shape.get(i); let tdot = bdir.dot(_vec1.copy(p).sub(new_shape.get(0))); if (tdot < min) { min = tdot; anchor = i; } } const minPoint = new_shape.get(anchor); //找出距离连个线段最近的点 // 垂直的两个点 这两个点与 if (i !== 0 && i !== pathPath.length - 1) { const P0 = Distance.Point2Line_Vec3(minPoint, pLast, _vec1.copy(p).sub(pLast).normalize()); const P1 = Distance.Point2Line_Vec3(minPoint, p, _vec1.copy(pNext).sub(p).normalize()); _vec1.copy(P0).sub(minPoint); _vec2.copy(P1).sub(minPoint); const angle = _vec1.angleTo(_vec2, normal); const seg = Math.ceil(angle / 0.1); const perAngle = angle / seg; for (let i = 0; i <= seg; i++) { const cAngle = i * perAngle; for (let j = 0; j < new_shape.length; j++) { const np = new_shape.get(j); const v = new Vec3().slerpVecs(_vec1, _vec2, cAngle); const t = np.clone().sub(minPoint); } } // if (options.holes) { // const mholes = applyMat4(options.holes, _matrix1, false); // applyMat4(mholes, _matrix, true); // newholes.push(mholes); // } } shapes.push(new_shape); } break; case JoinType.Miter://直角 for (let i = 0; i < pathPath.length; i++) { const p: Vec3 = pathPath.get(i); const dir: Vec3 = (p as any).direction; const bdir: Vec3 = (p as any).bdirection; const bnormal: Vec3 = (p as any).bnormal; const normal: Vec3 = (p as any).normal; //相邻两个向量发生的旋转 if (i === 0) { _quat.setFromUnitVecs(Vec3.UnitZ, dir); } else { _quat.setFromUnitVecs(pathPath.get(i - 1).direction, dir); } let new_shape: Path<Vec3> = shapePath.clone(); //旋转 _matrix.makeRotationFromQuat(_quat); accMat.premultiply(_matrix); _quat.setFromUnitVecs(dir, bdir); _matrix.makeRotationFromQuat(_quat); _matrix.multiply(accMat); // /旋转到原地缩放----开始----------------------- let cosA = dir.dot(bdir); const shear = 1 / cosA; _vec1.crossVecs(normal, bdir); _matrix1.copy(_matrix); _matrix1.invert(); _vec1.applyMat4(_matrix1); _quat.setFromUnitVecs(_vec1, Vec3.Up) _matrix1.makeRotationFromQuat(_quat); new_shape.applyMat4(_matrix1); new_shape.scale(1, shear, 1); new_shape.applyMat4(_matrix1.invert()); // /旋转到原地缩放----结束----------------------- //位置 _matrix.setPosition(p); new_shape.applyMat4(_matrix); // if (options.holes) { // const mholes = applyMat4(options.holes, _matrix1, false); // applyMat4(mholes, _matrix, true); // newholes.push(mholes); // } shapes.push(new_shape); } break; default: break; } const geo: IGeometry = linkSides({ shapes: shapes.map((e: Path<Vec3>) => e.array), holes: newholes, orgShape: shapePath._array, orgHoles: options.holes, sealStart: options.sealStart, sealEnd: options.sealEnd, shapeClosed: options.shapeClosed, pathClosed: options.pathClosed, axisPlane: options.axisPlane, autoIndex: options.autoIndex, generateUV: options.generateUV, }) return geo; }
the_stack
* @file Pre-computed lookup tables for encoding ambisonic sources. * @author Andrew Allen <bitllama@google.com> */ /** * Pre-computed Spherical Harmonics Coefficients. * * This function generates an efficient lookup table of SH coefficients. It * exploits the way SHs are generated (i.e. Ylm = Nlm * Plm * Em). Since Nlm * & Plm coefficients only depend on theta, and Em only depends on phi, we * can separate the equation along these lines. Em does not depend on * degree, so we only need to compute (2 * l) per azimuth Em total and * Nlm * Plm is symmetrical across indexes, so only positive indexes are * computed ((l + 1) * (l + 2) / 2 - 1) per elevation. */ export const SPHERICAL_HARMONICS = [ [ [0.000000, 0.000000, 0.000000, 1.000000, 1.000000, 1.000000], [0.052336, 0.034899, 0.017452, 0.999848, 0.999391, 0.998630], [0.104528, 0.069756, 0.034899, 0.999391, 0.997564, 0.994522], [0.156434, 0.104528, 0.052336, 0.998630, 0.994522, 0.987688], [0.207912, 0.139173, 0.069756, 0.997564, 0.990268, 0.978148], [0.258819, 0.173648, 0.087156, 0.996195, 0.984808, 0.965926], [0.309017, 0.207912, 0.104528, 0.994522, 0.978148, 0.951057], [0.358368, 0.241922, 0.121869, 0.992546, 0.970296, 0.933580], [0.406737, 0.275637, 0.139173, 0.990268, 0.961262, 0.913545], [0.453990, 0.309017, 0.156434, 0.987688, 0.951057, 0.891007], [0.500000, 0.342020, 0.173648, 0.984808, 0.939693, 0.866025], [0.544639, 0.374607, 0.190809, 0.981627, 0.927184, 0.838671], [0.587785, 0.406737, 0.207912, 0.978148, 0.913545, 0.809017], [0.629320, 0.438371, 0.224951, 0.974370, 0.898794, 0.777146], [0.669131, 0.469472, 0.241922, 0.970296, 0.882948, 0.743145], [0.707107, 0.500000, 0.258819, 0.965926, 0.866025, 0.707107], [0.743145, 0.529919, 0.275637, 0.961262, 0.848048, 0.669131], [0.777146, 0.559193, 0.292372, 0.956305, 0.829038, 0.629320], [0.809017, 0.587785, 0.309017, 0.951057, 0.809017, 0.587785], [0.838671, 0.615661, 0.325568, 0.945519, 0.788011, 0.544639], [0.866025, 0.642788, 0.342020, 0.939693, 0.766044, 0.500000], [0.891007, 0.669131, 0.358368, 0.933580, 0.743145, 0.453990], [0.913545, 0.694658, 0.374607, 0.927184, 0.719340, 0.406737], [0.933580, 0.719340, 0.390731, 0.920505, 0.694658, 0.358368], [0.951057, 0.743145, 0.406737, 0.913545, 0.669131, 0.309017], [0.965926, 0.766044, 0.422618, 0.906308, 0.642788, 0.258819], [0.978148, 0.788011, 0.438371, 0.898794, 0.615661, 0.207912], [0.987688, 0.809017, 0.453990, 0.891007, 0.587785, 0.156434], [0.994522, 0.829038, 0.469472, 0.882948, 0.559193, 0.104528], [0.998630, 0.848048, 0.484810, 0.874620, 0.529919, 0.052336], [1.000000, 0.866025, 0.500000, 0.866025, 0.500000, 0.000000], [0.998630, 0.882948, 0.515038, 0.857167, 0.469472, -0.052336], [0.994522, 0.898794, 0.529919, 0.848048, 0.438371, -0.104528], [0.987688, 0.913545, 0.544639, 0.838671, 0.406737, -0.156434], [0.978148, 0.927184, 0.559193, 0.829038, 0.374607, -0.207912], [0.965926, 0.939693, 0.573576, 0.819152, 0.342020, -0.258819], [0.951057, 0.951057, 0.587785, 0.809017, 0.309017, -0.309017], [0.933580, 0.961262, 0.601815, 0.798636, 0.275637, -0.358368], [0.913545, 0.970296, 0.615661, 0.788011, 0.241922, -0.406737], [0.891007, 0.978148, 0.629320, 0.777146, 0.207912, -0.453990], [0.866025, 0.984808, 0.642788, 0.766044, 0.173648, -0.500000], [0.838671, 0.990268, 0.656059, 0.754710, 0.139173, -0.544639], [0.809017, 0.994522, 0.669131, 0.743145, 0.104528, -0.587785], [0.777146, 0.997564, 0.681998, 0.731354, 0.069756, -0.629320], [0.743145, 0.999391, 0.694658, 0.719340, 0.034899, -0.669131], [0.707107, 1.000000, 0.707107, 0.707107, 0.000000, -0.707107], [0.669131, 0.999391, 0.719340, 0.694658, -0.034899, -0.743145], [0.629320, 0.997564, 0.731354, 0.681998, -0.069756, -0.777146], [0.587785, 0.994522, 0.743145, 0.669131, -0.104528, -0.809017], [0.544639, 0.990268, 0.754710, 0.656059, -0.139173, -0.838671], [0.500000, 0.984808, 0.766044, 0.642788, -0.173648, -0.866025], [0.453990, 0.978148, 0.777146, 0.629320, -0.207912, -0.891007], [0.406737, 0.970296, 0.788011, 0.615661, -0.241922, -0.913545], [0.358368, 0.961262, 0.798636, 0.601815, -0.275637, -0.933580], [0.309017, 0.951057, 0.809017, 0.587785, -0.309017, -0.951057], [0.258819, 0.939693, 0.819152, 0.573576, -0.342020, -0.965926], [0.207912, 0.927184, 0.829038, 0.559193, -0.374607, -0.978148], [0.156434, 0.913545, 0.838671, 0.544639, -0.406737, -0.987688], [0.104528, 0.898794, 0.848048, 0.529919, -0.438371, -0.994522], [0.052336, 0.882948, 0.857167, 0.515038, -0.469472, -0.998630], [0.000000, 0.866025, 0.866025, 0.500000, -0.500000, -1.000000], [-0.052336, 0.848048, 0.874620, 0.484810, -0.529919, -0.998630], [-0.104528, 0.829038, 0.882948, 0.469472, -0.559193, -0.994522], [-0.156434, 0.809017, 0.891007, 0.453990, -0.587785, -0.987688], [-0.207912, 0.788011, 0.898794, 0.438371, -0.615661, -0.978148], [-0.258819, 0.766044, 0.906308, 0.422618, -0.642788, -0.965926], [-0.309017, 0.743145, 0.913545, 0.406737, -0.669131, -0.951057], [-0.358368, 0.719340, 0.920505, 0.390731, -0.694658, -0.933580], [-0.406737, 0.694658, 0.927184, 0.374607, -0.719340, -0.913545], [-0.453990, 0.669131, 0.933580, 0.358368, -0.743145, -0.891007], [-0.500000, 0.642788, 0.939693, 0.342020, -0.766044, -0.866025], [-0.544639, 0.615661, 0.945519, 0.325568, -0.788011, -0.838671], [-0.587785, 0.587785, 0.951057, 0.309017, -0.809017, -0.809017], [-0.629320, 0.559193, 0.956305, 0.292372, -0.829038, -0.777146], [-0.669131, 0.529919, 0.961262, 0.275637, -0.848048, -0.743145], [-0.707107, 0.500000, 0.965926, 0.258819, -0.866025, -0.707107], [-0.743145, 0.469472, 0.970296, 0.241922, -0.882948, -0.669131], [-0.777146, 0.438371, 0.974370, 0.224951, -0.898794, -0.629320], [-0.809017, 0.406737, 0.978148, 0.207912, -0.913545, -0.587785], [-0.838671, 0.374607, 0.981627, 0.190809, -0.927184, -0.544639], [-0.866025, 0.342020, 0.984808, 0.173648, -0.939693, -0.500000], [-0.891007, 0.309017, 0.987688, 0.156434, -0.951057, -0.453990], [-0.913545, 0.275637, 0.990268, 0.139173, -0.961262, -0.406737], [-0.933580, 0.241922, 0.992546, 0.121869, -0.970296, -0.358368], [-0.951057, 0.207912, 0.994522, 0.104528, -0.978148, -0.309017], [-0.965926, 0.173648, 0.996195, 0.087156, -0.984808, -0.258819], [-0.978148, 0.139173, 0.997564, 0.069756, -0.990268, -0.207912], [-0.987688, 0.104528, 0.998630, 0.052336, -0.994522, -0.156434], [-0.994522, 0.069756, 0.999391, 0.034899, -0.997564, -0.104528], [-0.998630, 0.034899, 0.999848, 0.017452, -0.999391, -0.052336], [-1.000000, 0.000000, 1.000000, 0.000000, -1.000000, -0.000000], [-0.998630, -0.034899, 0.999848, -0.017452, -0.999391, 0.052336], [-0.994522, -0.069756, 0.999391, -0.034899, -0.997564, 0.104528], [-0.987688, -0.104528, 0.998630, -0.052336, -0.994522, 0.156434], [-0.978148, -0.139173, 0.997564, -0.069756, -0.990268, 0.207912], [-0.965926, -0.173648, 0.996195, -0.087156, -0.984808, 0.258819], [-0.951057, -0.207912, 0.994522, -0.104528, -0.978148, 0.309017], [-0.933580, -0.241922, 0.992546, -0.121869, -0.970296, 0.358368], [-0.913545, -0.275637, 0.990268, -0.139173, -0.961262, 0.406737], [-0.891007, -0.309017, 0.987688, -0.156434, -0.951057, 0.453990], [-0.866025, -0.342020, 0.984808, -0.173648, -0.939693, 0.500000], [-0.838671, -0.374607, 0.981627, -0.190809, -0.927184, 0.544639], [-0.809017, -0.406737, 0.978148, -0.207912, -0.913545, 0.587785], [-0.777146, -0.438371, 0.974370, -0.224951, -0.898794, 0.629320], [-0.743145, -0.469472, 0.970296, -0.241922, -0.882948, 0.669131], [-0.707107, -0.500000, 0.965926, -0.258819, -0.866025, 0.707107], [-0.669131, -0.529919, 0.961262, -0.275637, -0.848048, 0.743145], [-0.629320, -0.559193, 0.956305, -0.292372, -0.829038, 0.777146], [-0.587785, -0.587785, 0.951057, -0.309017, -0.809017, 0.809017], [-0.544639, -0.615661, 0.945519, -0.325568, -0.788011, 0.838671], [-0.500000, -0.642788, 0.939693, -0.342020, -0.766044, 0.866025], [-0.453990, -0.669131, 0.933580, -0.358368, -0.743145, 0.891007], [-0.406737, -0.694658, 0.927184, -0.374607, -0.719340, 0.913545], [-0.358368, -0.719340, 0.920505, -0.390731, -0.694658, 0.933580], [-0.309017, -0.743145, 0.913545, -0.406737, -0.669131, 0.951057], [-0.258819, -0.766044, 0.906308, -0.422618, -0.642788, 0.965926], [-0.207912, -0.788011, 0.898794, -0.438371, -0.615661, 0.978148], [-0.156434, -0.809017, 0.891007, -0.453990, -0.587785, 0.987688], [-0.104528, -0.829038, 0.882948, -0.469472, -0.559193, 0.994522], [-0.052336, -0.848048, 0.874620, -0.484810, -0.529919, 0.998630], [-0.000000, -0.866025, 0.866025, -0.500000, -0.500000, 1.000000], [0.052336, -0.882948, 0.857167, -0.515038, -0.469472, 0.998630], [0.104528, -0.898794, 0.848048, -0.529919, -0.438371, 0.994522], [0.156434, -0.913545, 0.838671, -0.544639, -0.406737, 0.987688], [0.207912, -0.927184, 0.829038, -0.559193, -0.374607, 0.978148], [0.258819, -0.939693, 0.819152, -0.573576, -0.342020, 0.965926], [0.309017, -0.951057, 0.809017, -0.587785, -0.309017, 0.951057], [0.358368, -0.961262, 0.798636, -0.601815, -0.275637, 0.933580], [0.406737, -0.970296, 0.788011, -0.615661, -0.241922, 0.913545], [0.453990, -0.978148, 0.777146, -0.629320, -0.207912, 0.891007], [0.500000, -0.984808, 0.766044, -0.642788, -0.173648, 0.866025], [0.544639, -0.990268, 0.754710, -0.656059, -0.139173, 0.838671], [0.587785, -0.994522, 0.743145, -0.669131, -0.104528, 0.809017], [0.629320, -0.997564, 0.731354, -0.681998, -0.069756, 0.777146], [0.669131, -0.999391, 0.719340, -0.694658, -0.034899, 0.743145], [0.707107, -1.000000, 0.707107, -0.707107, -0.000000, 0.707107], [0.743145, -0.999391, 0.694658, -0.719340, 0.034899, 0.669131], [0.777146, -0.997564, 0.681998, -0.731354, 0.069756, 0.629320], [0.809017, -0.994522, 0.669131, -0.743145, 0.104528, 0.587785], [0.838671, -0.990268, 0.656059, -0.754710, 0.139173, 0.544639], [0.866025, -0.984808, 0.642788, -0.766044, 0.173648, 0.500000], [0.891007, -0.978148, 0.629320, -0.777146, 0.207912, 0.453990], [0.913545, -0.970296, 0.615661, -0.788011, 0.241922, 0.406737], [0.933580, -0.961262, 0.601815, -0.798636, 0.275637, 0.358368], [0.951057, -0.951057, 0.587785, -0.809017, 0.309017, 0.309017], [0.965926, -0.939693, 0.573576, -0.819152, 0.342020, 0.258819], [0.978148, -0.927184, 0.559193, -0.829038, 0.374607, 0.207912], [0.987688, -0.913545, 0.544639, -0.838671, 0.406737, 0.156434], [0.994522, -0.898794, 0.529919, -0.848048, 0.438371, 0.104528], [0.998630, -0.882948, 0.515038, -0.857167, 0.469472, 0.052336], [1.000000, -0.866025, 0.500000, -0.866025, 0.500000, 0.000000], [0.998630, -0.848048, 0.484810, -0.874620, 0.529919, -0.052336], [0.994522, -0.829038, 0.469472, -0.882948, 0.559193, -0.104528], [0.987688, -0.809017, 0.453990, -0.891007, 0.587785, -0.156434], [0.978148, -0.788011, 0.438371, -0.898794, 0.615661, -0.207912], [0.965926, -0.766044, 0.422618, -0.906308, 0.642788, -0.258819], [0.951057, -0.743145, 0.406737, -0.913545, 0.669131, -0.309017], [0.933580, -0.719340, 0.390731, -0.920505, 0.694658, -0.358368], [0.913545, -0.694658, 0.374607, -0.927184, 0.719340, -0.406737], [0.891007, -0.669131, 0.358368, -0.933580, 0.743145, -0.453990], [0.866025, -0.642788, 0.342020, -0.939693, 0.766044, -0.500000], [0.838671, -0.615661, 0.325568, -0.945519, 0.788011, -0.544639], [0.809017, -0.587785, 0.309017, -0.951057, 0.809017, -0.587785], [0.777146, -0.559193, 0.292372, -0.956305, 0.829038, -0.629320], [0.743145, -0.529919, 0.275637, -0.961262, 0.848048, -0.669131], [0.707107, -0.500000, 0.258819, -0.965926, 0.866025, -0.707107], [0.669131, -0.469472, 0.241922, -0.970296, 0.882948, -0.743145], [0.629320, -0.438371, 0.224951, -0.974370, 0.898794, -0.777146], [0.587785, -0.406737, 0.207912, -0.978148, 0.913545, -0.809017], [0.544639, -0.374607, 0.190809, -0.981627, 0.927184, -0.838671], [0.500000, -0.342020, 0.173648, -0.984808, 0.939693, -0.866025], [0.453990, -0.309017, 0.156434, -0.987688, 0.951057, -0.891007], [0.406737, -0.275637, 0.139173, -0.990268, 0.961262, -0.913545], [0.358368, -0.241922, 0.121869, -0.992546, 0.970296, -0.933580], [0.309017, -0.207912, 0.104528, -0.994522, 0.978148, -0.951057], [0.258819, -0.173648, 0.087156, -0.996195, 0.984808, -0.965926], [0.207912, -0.139173, 0.069756, -0.997564, 0.990268, -0.978148], [0.156434, -0.104528, 0.052336, -0.998630, 0.994522, -0.987688], [0.104528, -0.069756, 0.034899, -0.999391, 0.997564, -0.994522], [0.052336, -0.034899, 0.017452, -0.999848, 0.999391, -0.998630], [0.000000, -0.000000, 0.000000, -1.000000, 1.000000, -1.000000], [-0.052336, 0.034899, -0.017452, -0.999848, 0.999391, -0.998630], [-0.104528, 0.069756, -0.034899, -0.999391, 0.997564, -0.994522], [-0.156434, 0.104528, -0.052336, -0.998630, 0.994522, -0.987688], [-0.207912, 0.139173, -0.069756, -0.997564, 0.990268, -0.978148], [-0.258819, 0.173648, -0.087156, -0.996195, 0.984808, -0.965926], [-0.309017, 0.207912, -0.104528, -0.994522, 0.978148, -0.951057], [-0.358368, 0.241922, -0.121869, -0.992546, 0.970296, -0.933580], [-0.406737, 0.275637, -0.139173, -0.990268, 0.961262, -0.913545], [-0.453990, 0.309017, -0.156434, -0.987688, 0.951057, -0.891007], [-0.500000, 0.342020, -0.173648, -0.984808, 0.939693, -0.866025], [-0.544639, 0.374607, -0.190809, -0.981627, 0.927184, -0.838671], [-0.587785, 0.406737, -0.207912, -0.978148, 0.913545, -0.809017], [-0.629320, 0.438371, -0.224951, -0.974370, 0.898794, -0.777146], [-0.669131, 0.469472, -0.241922, -0.970296, 0.882948, -0.743145], [-0.707107, 0.500000, -0.258819, -0.965926, 0.866025, -0.707107], [-0.743145, 0.529919, -0.275637, -0.961262, 0.848048, -0.669131], [-0.777146, 0.559193, -0.292372, -0.956305, 0.829038, -0.629320], [-0.809017, 0.587785, -0.309017, -0.951057, 0.809017, -0.587785], [-0.838671, 0.615661, -0.325568, -0.945519, 0.788011, -0.544639], [-0.866025, 0.642788, -0.342020, -0.939693, 0.766044, -0.500000], [-0.891007, 0.669131, -0.358368, -0.933580, 0.743145, -0.453990], [-0.913545, 0.694658, -0.374607, -0.927184, 0.719340, -0.406737], [-0.933580, 0.719340, -0.390731, -0.920505, 0.694658, -0.358368], [-0.951057, 0.743145, -0.406737, -0.913545, 0.669131, -0.309017], [-0.965926, 0.766044, -0.422618, -0.906308, 0.642788, -0.258819], [-0.978148, 0.788011, -0.438371, -0.898794, 0.615661, -0.207912], [-0.987688, 0.809017, -0.453990, -0.891007, 0.587785, -0.156434], [-0.994522, 0.829038, -0.469472, -0.882948, 0.559193, -0.104528], [-0.998630, 0.848048, -0.484810, -0.874620, 0.529919, -0.052336], [-1.000000, 0.866025, -0.500000, -0.866025, 0.500000, 0.000000], [-0.998630, 0.882948, -0.515038, -0.857167, 0.469472, 0.052336], [-0.994522, 0.898794, -0.529919, -0.848048, 0.438371, 0.104528], [-0.987688, 0.913545, -0.544639, -0.838671, 0.406737, 0.156434], [-0.978148, 0.927184, -0.559193, -0.829038, 0.374607, 0.207912], [-0.965926, 0.939693, -0.573576, -0.819152, 0.342020, 0.258819], [-0.951057, 0.951057, -0.587785, -0.809017, 0.309017, 0.309017], [-0.933580, 0.961262, -0.601815, -0.798636, 0.275637, 0.358368], [-0.913545, 0.970296, -0.615661, -0.788011, 0.241922, 0.406737], [-0.891007, 0.978148, -0.629320, -0.777146, 0.207912, 0.453990], [-0.866025, 0.984808, -0.642788, -0.766044, 0.173648, 0.500000], [-0.838671, 0.990268, -0.656059, -0.754710, 0.139173, 0.544639], [-0.809017, 0.994522, -0.669131, -0.743145, 0.104528, 0.587785], [-0.777146, 0.997564, -0.681998, -0.731354, 0.069756, 0.629320], [-0.743145, 0.999391, -0.694658, -0.719340, 0.034899, 0.669131], [-0.707107, 1.000000, -0.707107, -0.707107, 0.000000, 0.707107], [-0.669131, 0.999391, -0.719340, -0.694658, -0.034899, 0.743145], [-0.629320, 0.997564, -0.731354, -0.681998, -0.069756, 0.777146], [-0.587785, 0.994522, -0.743145, -0.669131, -0.104528, 0.809017], [-0.544639, 0.990268, -0.754710, -0.656059, -0.139173, 0.838671], [-0.500000, 0.984808, -0.766044, -0.642788, -0.173648, 0.866025], [-0.453990, 0.978148, -0.777146, -0.629320, -0.207912, 0.891007], [-0.406737, 0.970296, -0.788011, -0.615661, -0.241922, 0.913545], [-0.358368, 0.961262, -0.798636, -0.601815, -0.275637, 0.933580], [-0.309017, 0.951057, -0.809017, -0.587785, -0.309017, 0.951057], [-0.258819, 0.939693, -0.819152, -0.573576, -0.342020, 0.965926], [-0.207912, 0.927184, -0.829038, -0.559193, -0.374607, 0.978148], [-0.156434, 0.913545, -0.838671, -0.544639, -0.406737, 0.987688], [-0.104528, 0.898794, -0.848048, -0.529919, -0.438371, 0.994522], [-0.052336, 0.882948, -0.857167, -0.515038, -0.469472, 0.998630], [-0.000000, 0.866025, -0.866025, -0.500000, -0.500000, 1.000000], [0.052336, 0.848048, -0.874620, -0.484810, -0.529919, 0.998630], [0.104528, 0.829038, -0.882948, -0.469472, -0.559193, 0.994522], [0.156434, 0.809017, -0.891007, -0.453990, -0.587785, 0.987688], [0.207912, 0.788011, -0.898794, -0.438371, -0.615661, 0.978148], [0.258819, 0.766044, -0.906308, -0.422618, -0.642788, 0.965926], [0.309017, 0.743145, -0.913545, -0.406737, -0.669131, 0.951057], [0.358368, 0.719340, -0.920505, -0.390731, -0.694658, 0.933580], [0.406737, 0.694658, -0.927184, -0.374607, -0.719340, 0.913545], [0.453990, 0.669131, -0.933580, -0.358368, -0.743145, 0.891007], [0.500000, 0.642788, -0.939693, -0.342020, -0.766044, 0.866025], [0.544639, 0.615661, -0.945519, -0.325568, -0.788011, 0.838671], [0.587785, 0.587785, -0.951057, -0.309017, -0.809017, 0.809017], [0.629320, 0.559193, -0.956305, -0.292372, -0.829038, 0.777146], [0.669131, 0.529919, -0.961262, -0.275637, -0.848048, 0.743145], [0.707107, 0.500000, -0.965926, -0.258819, -0.866025, 0.707107], [0.743145, 0.469472, -0.970296, -0.241922, -0.882948, 0.669131], [0.777146, 0.438371, -0.974370, -0.224951, -0.898794, 0.629320], [0.809017, 0.406737, -0.978148, -0.207912, -0.913545, 0.587785], [0.838671, 0.374607, -0.981627, -0.190809, -0.927184, 0.544639], [0.866025, 0.342020, -0.984808, -0.173648, -0.939693, 0.500000], [0.891007, 0.309017, -0.987688, -0.156434, -0.951057, 0.453990], [0.913545, 0.275637, -0.990268, -0.139173, -0.961262, 0.406737], [0.933580, 0.241922, -0.992546, -0.121869, -0.970296, 0.358368], [0.951057, 0.207912, -0.994522, -0.104528, -0.978148, 0.309017], [0.965926, 0.173648, -0.996195, -0.087156, -0.984808, 0.258819], [0.978148, 0.139173, -0.997564, -0.069756, -0.990268, 0.207912], [0.987688, 0.104528, -0.998630, -0.052336, -0.994522, 0.156434], [0.994522, 0.069756, -0.999391, -0.034899, -0.997564, 0.104528], [0.998630, 0.034899, -0.999848, -0.017452, -0.999391, 0.052336], [1.000000, 0.000000, -1.000000, -0.000000, -1.000000, 0.000000], [0.998630, -0.034899, -0.999848, 0.017452, -0.999391, -0.052336], [0.994522, -0.069756, -0.999391, 0.034899, -0.997564, -0.104528], [0.987688, -0.104528, -0.998630, 0.052336, -0.994522, -0.156434], [0.978148, -0.139173, -0.997564, 0.069756, -0.990268, -0.207912], [0.965926, -0.173648, -0.996195, 0.087156, -0.984808, -0.258819], [0.951057, -0.207912, -0.994522, 0.104528, -0.978148, -0.309017], [0.933580, -0.241922, -0.992546, 0.121869, -0.970296, -0.358368], [0.913545, -0.275637, -0.990268, 0.139173, -0.961262, -0.406737], [0.891007, -0.309017, -0.987688, 0.156434, -0.951057, -0.453990], [0.866025, -0.342020, -0.984808, 0.173648, -0.939693, -0.500000], [0.838671, -0.374607, -0.981627, 0.190809, -0.927184, -0.544639], [0.809017, -0.406737, -0.978148, 0.207912, -0.913545, -0.587785], [0.777146, -0.438371, -0.974370, 0.224951, -0.898794, -0.629320], [0.743145, -0.469472, -0.970296, 0.241922, -0.882948, -0.669131], [0.707107, -0.500000, -0.965926, 0.258819, -0.866025, -0.707107], [0.669131, -0.529919, -0.961262, 0.275637, -0.848048, -0.743145], [0.629320, -0.559193, -0.956305, 0.292372, -0.829038, -0.777146], [0.587785, -0.587785, -0.951057, 0.309017, -0.809017, -0.809017], [0.544639, -0.615661, -0.945519, 0.325568, -0.788011, -0.838671], [0.500000, -0.642788, -0.939693, 0.342020, -0.766044, -0.866025], [0.453990, -0.669131, -0.933580, 0.358368, -0.743145, -0.891007], [0.406737, -0.694658, -0.927184, 0.374607, -0.719340, -0.913545], [0.358368, -0.719340, -0.920505, 0.390731, -0.694658, -0.933580], [0.309017, -0.743145, -0.913545, 0.406737, -0.669131, -0.951057], [0.258819, -0.766044, -0.906308, 0.422618, -0.642788, -0.965926], [0.207912, -0.788011, -0.898794, 0.438371, -0.615661, -0.978148], [0.156434, -0.809017, -0.891007, 0.453990, -0.587785, -0.987688], [0.104528, -0.829038, -0.882948, 0.469472, -0.559193, -0.994522], [0.052336, -0.848048, -0.874620, 0.484810, -0.529919, -0.998630], [0.000000, -0.866025, -0.866025, 0.500000, -0.500000, -1.000000], [-0.052336, -0.882948, -0.857167, 0.515038, -0.469472, -0.998630], [-0.104528, -0.898794, -0.848048, 0.529919, -0.438371, -0.994522], [-0.156434, -0.913545, -0.838671, 0.544639, -0.406737, -0.987688], [-0.207912, -0.927184, -0.829038, 0.559193, -0.374607, -0.978148], [-0.258819, -0.939693, -0.819152, 0.573576, -0.342020, -0.965926], [-0.309017, -0.951057, -0.809017, 0.587785, -0.309017, -0.951057], [-0.358368, -0.961262, -0.798636, 0.601815, -0.275637, -0.933580], [-0.406737, -0.970296, -0.788011, 0.615661, -0.241922, -0.913545], [-0.453990, -0.978148, -0.777146, 0.629320, -0.207912, -0.891007], [-0.500000, -0.984808, -0.766044, 0.642788, -0.173648, -0.866025], [-0.544639, -0.990268, -0.754710, 0.656059, -0.139173, -0.838671], [-0.587785, -0.994522, -0.743145, 0.669131, -0.104528, -0.809017], [-0.629320, -0.997564, -0.731354, 0.681998, -0.069756, -0.777146], [-0.669131, -0.999391, -0.719340, 0.694658, -0.034899, -0.743145], [-0.707107, -1.000000, -0.707107, 0.707107, -0.000000, -0.707107], [-0.743145, -0.999391, -0.694658, 0.719340, 0.034899, -0.669131], [-0.777146, -0.997564, -0.681998, 0.731354, 0.069756, -0.629320], [-0.809017, -0.994522, -0.669131, 0.743145, 0.104528, -0.587785], [-0.838671, -0.990268, -0.656059, 0.754710, 0.139173, -0.544639], [-0.866025, -0.984808, -0.642788, 0.766044, 0.173648, -0.500000], [-0.891007, -0.978148, -0.629320, 0.777146, 0.207912, -0.453990], [-0.913545, -0.970296, -0.615661, 0.788011, 0.241922, -0.406737], [-0.933580, -0.961262, -0.601815, 0.798636, 0.275637, -0.358368], [-0.951057, -0.951057, -0.587785, 0.809017, 0.309017, -0.309017], [-0.965926, -0.939693, -0.573576, 0.819152, 0.342020, -0.258819], [-0.978148, -0.927184, -0.559193, 0.829038, 0.374607, -0.207912], [-0.987688, -0.913545, -0.544639, 0.838671, 0.406737, -0.156434], [-0.994522, -0.898794, -0.529919, 0.848048, 0.438371, -0.104528], [-0.998630, -0.882948, -0.515038, 0.857167, 0.469472, -0.052336], [-1.000000, -0.866025, -0.500000, 0.866025, 0.500000, -0.000000], [-0.998630, -0.848048, -0.484810, 0.874620, 0.529919, 0.052336], [-0.994522, -0.829038, -0.469472, 0.882948, 0.559193, 0.104528], [-0.987688, -0.809017, -0.453990, 0.891007, 0.587785, 0.156434], [-0.978148, -0.788011, -0.438371, 0.898794, 0.615661, 0.207912], [-0.965926, -0.766044, -0.422618, 0.906308, 0.642788, 0.258819], [-0.951057, -0.743145, -0.406737, 0.913545, 0.669131, 0.309017], [-0.933580, -0.719340, -0.390731, 0.920505, 0.694658, 0.358368], [-0.913545, -0.694658, -0.374607, 0.927184, 0.719340, 0.406737], [-0.891007, -0.669131, -0.358368, 0.933580, 0.743145, 0.453990], [-0.866025, -0.642788, -0.342020, 0.939693, 0.766044, 0.500000], [-0.838671, -0.615661, -0.325568, 0.945519, 0.788011, 0.544639], [-0.809017, -0.587785, -0.309017, 0.951057, 0.809017, 0.587785], [-0.777146, -0.559193, -0.292372, 0.956305, 0.829038, 0.629320], [-0.743145, -0.529919, -0.275637, 0.961262, 0.848048, 0.669131], [-0.707107, -0.500000, -0.258819, 0.965926, 0.866025, 0.707107], [-0.669131, -0.469472, -0.241922, 0.970296, 0.882948, 0.743145], [-0.629320, -0.438371, -0.224951, 0.974370, 0.898794, 0.777146], [-0.587785, -0.406737, -0.207912, 0.978148, 0.913545, 0.809017], [-0.544639, -0.374607, -0.190809, 0.981627, 0.927184, 0.838671], [-0.500000, -0.342020, -0.173648, 0.984808, 0.939693, 0.866025], [-0.453990, -0.309017, -0.156434, 0.987688, 0.951057, 0.891007], [-0.406737, -0.275637, -0.139173, 0.990268, 0.961262, 0.913545], [-0.358368, -0.241922, -0.121869, 0.992546, 0.970296, 0.933580], [-0.309017, -0.207912, -0.104528, 0.994522, 0.978148, 0.951057], [-0.258819, -0.173648, -0.087156, 0.996195, 0.984808, 0.965926], [-0.207912, -0.139173, -0.069756, 0.997564, 0.990268, 0.978148], [-0.156434, -0.104528, -0.052336, 0.998630, 0.994522, 0.987688], [-0.104528, -0.069756, -0.034899, 0.999391, 0.997564, 0.994522], [-0.052336, -0.034899, -0.017452, 0.999848, 0.999391, 0.998630], ], [ [-1.000000, -0.000000, 1.000000, -0.000000, 0.000000, -1.000000, -0.000000, 0.000000, -0.000000], [-0.999848, 0.017452, 0.999543, -0.030224, 0.000264, -0.999086, 0.042733, -0.000590, 0.000004], [-0.999391, 0.034899, 0.998173, -0.060411, 0.001055, -0.996348, 0.085356, -0.002357, 0.000034], [-0.998630, 0.052336, 0.995891, -0.090524, 0.002372, -0.991791, 0.127757, -0.005297, 0.000113], [-0.997564, 0.069756, 0.992701, -0.120527, 0.004214, -0.985429, 0.169828, -0.009400, 0.000268], [-0.996195, 0.087156, 0.988606, -0.150384, 0.006578, -0.977277, 0.211460, -0.014654, 0.000523], [-0.994522, 0.104528, 0.983611, -0.180057, 0.009462, -0.967356, 0.252544, -0.021043, 0.000903], [-0.992546, 0.121869, 0.977722, -0.209511, 0.012862, -0.955693, 0.292976, -0.028547, 0.001431], [-0.990268, 0.139173, 0.970946, -0.238709, 0.016774, -0.942316, 0.332649, -0.037143, 0.002131], [-0.987688, 0.156434, 0.963292, -0.267617, 0.021193, -0.927262, 0.371463, -0.046806, 0.003026], [-0.984808, 0.173648, 0.954769, -0.296198, 0.026114, -0.910569, 0.409317, -0.057505, 0.004140], [-0.981627, 0.190809, 0.945388, -0.324419, 0.031530, -0.892279, 0.446114, -0.069209, 0.005492], [-0.978148, 0.207912, 0.935159, -0.352244, 0.037436, -0.872441, 0.481759, -0.081880, 0.007105], [-0.974370, 0.224951, 0.924096, -0.379641, 0.043823, -0.851105, 0.516162, -0.095481, 0.008999], [-0.970296, 0.241922, 0.912211, -0.406574, 0.050685, -0.828326, 0.549233, -0.109969, 0.011193], [-0.965926, 0.258819, 0.899519, -0.433013, 0.058013, -0.804164, 0.580889, -0.125300, 0.013707], [-0.961262, 0.275637, 0.886036, -0.458924, 0.065797, -0.778680, 0.611050, -0.141427, 0.016556], [-0.956305, 0.292372, 0.871778, -0.484275, 0.074029, -0.751940, 0.639639, -0.158301, 0.019758], [-0.951057, 0.309017, 0.856763, -0.509037, 0.082698, -0.724012, 0.666583, -0.175868, 0.023329], [-0.945519, 0.325568, 0.841008, -0.533178, 0.091794, -0.694969, 0.691816, -0.194075, 0.027281], [-0.939693, 0.342020, 0.824533, -0.556670, 0.101306, -0.664885, 0.715274, -0.212865, 0.031630], [-0.933580, 0.358368, 0.807359, -0.579484, 0.111222, -0.633837, 0.736898, -0.232180, 0.036385], [-0.927184, 0.374607, 0.789505, -0.601592, 0.121529, -0.601904, 0.756637, -0.251960, 0.041559], [-0.920505, 0.390731, 0.770994, -0.622967, 0.132217, -0.569169, 0.774442, -0.272143, 0.047160], [-0.913545, 0.406737, 0.751848, -0.643582, 0.143271, -0.535715, 0.790270, -0.292666, 0.053196], [-0.906308, 0.422618, 0.732091, -0.663414, 0.154678, -0.501627, 0.804083, -0.313464, 0.059674], [-0.898794, 0.438371, 0.711746, -0.682437, 0.166423, -0.466993, 0.815850, -0.334472, 0.066599], [-0.891007, 0.453990, 0.690839, -0.700629, 0.178494, -0.431899, 0.825544, -0.355623, 0.073974], [-0.882948, 0.469472, 0.669395, -0.717968, 0.190875, -0.396436, 0.833145, -0.376851, 0.081803], [-0.874620, 0.484810, 0.647439, -0.734431, 0.203551, -0.360692, 0.838638, -0.398086, 0.090085], [-0.866025, 0.500000, 0.625000, -0.750000, 0.216506, -0.324760, 0.842012, -0.419263, 0.098821], [-0.857167, 0.515038, 0.602104, -0.764655, 0.229726, -0.288728, 0.843265, -0.440311, 0.108009], [-0.848048, 0.529919, 0.578778, -0.778378, 0.243192, -0.252688, 0.842399, -0.461164, 0.117644], [-0.838671, 0.544639, 0.555052, -0.791154, 0.256891, -0.216730, 0.839422, -0.481753, 0.127722], [-0.829038, 0.559193, 0.530955, -0.802965, 0.270803, -0.180944, 0.834347, -0.502011, 0.138237], [-0.819152, 0.573576, 0.506515, -0.813798, 0.284914, -0.145420, 0.827194, -0.521871, 0.149181], [-0.809017, 0.587785, 0.481763, -0.823639, 0.299204, -0.110246, 0.817987, -0.541266, 0.160545], [-0.798636, 0.601815, 0.456728, -0.832477, 0.313658, -0.075508, 0.806757, -0.560132, 0.172317], [-0.788011, 0.615661, 0.431441, -0.840301, 0.328257, -0.041294, 0.793541, -0.578405, 0.184487], [-0.777146, 0.629320, 0.405934, -0.847101, 0.342984, -0.007686, 0.778379, -0.596021, 0.197040], [-0.766044, 0.642788, 0.380236, -0.852869, 0.357821, 0.025233, 0.761319, -0.612921, 0.209963], [-0.754710, 0.656059, 0.354380, -0.857597, 0.372749, 0.057383, 0.742412, -0.629044, 0.223238], [-0.743145, 0.669131, 0.328396, -0.861281, 0.387751, 0.088686, 0.721714, -0.644334, 0.236850], [-0.731354, 0.681998, 0.302317, -0.863916, 0.402807, 0.119068, 0.699288, -0.658734, 0.250778], [-0.719340, 0.694658, 0.276175, -0.865498, 0.417901, 0.148454, 0.675199, -0.672190, 0.265005], [-0.707107, 0.707107, 0.250000, -0.866025, 0.433013, 0.176777, 0.649519, -0.684653, 0.279508], [-0.694658, 0.719340, 0.223825, -0.865498, 0.448125, 0.203969, 0.622322, -0.696073, 0.294267], [-0.681998, 0.731354, 0.197683, -0.863916, 0.463218, 0.229967, 0.593688, -0.706405, 0.309259], [-0.669131, 0.743145, 0.171604, -0.861281, 0.478275, 0.254712, 0.563700, -0.715605, 0.324459], [-0.656059, 0.754710, 0.145620, -0.857597, 0.493276, 0.278147, 0.532443, -0.723633, 0.339844], [-0.642788, 0.766044, 0.119764, -0.852869, 0.508205, 0.300221, 0.500009, -0.730451, 0.355387], [-0.629320, 0.777146, 0.094066, -0.847101, 0.523041, 0.320884, 0.466490, -0.736025, 0.371063], [-0.615661, 0.788011, 0.068559, -0.840301, 0.537768, 0.340093, 0.431982, -0.740324, 0.386845], [-0.601815, 0.798636, 0.043272, -0.832477, 0.552367, 0.357807, 0.396584, -0.743320, 0.402704], [-0.587785, 0.809017, 0.018237, -0.823639, 0.566821, 0.373991, 0.360397, -0.744989, 0.418613], [-0.573576, 0.819152, -0.006515, -0.813798, 0.581112, 0.388612, 0.323524, -0.745308, 0.434544], [-0.559193, 0.829038, -0.030955, -0.802965, 0.595222, 0.401645, 0.286069, -0.744262, 0.450467], [-0.544639, 0.838671, -0.055052, -0.791154, 0.609135, 0.413066, 0.248140, -0.741835, 0.466352], [-0.529919, 0.848048, -0.078778, -0.778378, 0.622833, 0.422856, 0.209843, -0.738017, 0.482171], [-0.515038, 0.857167, -0.102104, -0.764655, 0.636300, 0.431004, 0.171288, -0.732801, 0.497894], [-0.500000, 0.866025, -0.125000, -0.750000, 0.649519, 0.437500, 0.132583, -0.726184, 0.513490], [-0.484810, 0.874620, -0.147439, -0.734431, 0.662474, 0.442340, 0.093837, -0.718167, 0.528929], [-0.469472, 0.882948, -0.169395, -0.717968, 0.675150, 0.445524, 0.055160, -0.708753, 0.544183], [-0.453990, 0.891007, -0.190839, -0.700629, 0.687531, 0.447059, 0.016662, -0.697950, 0.559220], [-0.438371, 0.898794, -0.211746, -0.682437, 0.699602, 0.446953, -0.021550, -0.685769, 0.574011], [-0.422618, 0.906308, -0.232091, -0.663414, 0.711348, 0.445222, -0.059368, -0.672226, 0.588528], [-0.406737, 0.913545, -0.251848, -0.643582, 0.722755, 0.441884, -0.096684, -0.657339, 0.602741], [-0.390731, 0.920505, -0.270994, -0.622967, 0.733809, 0.436964, -0.133395, -0.641130, 0.616621], [-0.374607, 0.927184, -0.289505, -0.601592, 0.744496, 0.430488, -0.169397, -0.623624, 0.630141], [-0.358368, 0.933580, -0.307359, -0.579484, 0.754804, 0.422491, -0.204589, -0.604851, 0.643273], [-0.342020, 0.939693, -0.324533, -0.556670, 0.764720, 0.413008, -0.238872, -0.584843, 0.655990], [-0.325568, 0.945519, -0.341008, -0.533178, 0.774231, 0.402081, -0.272150, -0.563635, 0.668267], [-0.309017, 0.951057, -0.356763, -0.509037, 0.783327, 0.389754, -0.304329, -0.541266, 0.680078], [-0.292372, 0.956305, -0.371778, -0.484275, 0.791997, 0.376077, -0.335319, -0.517778, 0.691399], [-0.275637, 0.961262, -0.386036, -0.458924, 0.800228, 0.361102, -0.365034, -0.493216, 0.702207], [-0.258819, 0.965926, -0.399519, -0.433013, 0.808013, 0.344885, -0.393389, -0.467627, 0.712478], [-0.241922, 0.970296, -0.412211, -0.406574, 0.815340, 0.327486, -0.420306, -0.441061, 0.722191], [-0.224951, 0.974370, -0.424096, -0.379641, 0.822202, 0.308969, -0.445709, -0.413572, 0.731327], [-0.207912, 0.978148, -0.435159, -0.352244, 0.828589, 0.289399, -0.469527, -0.385215, 0.739866], [-0.190809, 0.981627, -0.445388, -0.324419, 0.834495, 0.268846, -0.491693, -0.356047, 0.747790], [-0.173648, 0.984808, -0.454769, -0.296198, 0.839912, 0.247382, -0.512145, -0.326129, 0.755082], [-0.156434, 0.987688, -0.463292, -0.267617, 0.844832, 0.225081, -0.530827, -0.295521, 0.761728], [-0.139173, 0.990268, -0.470946, -0.238709, 0.849251, 0.202020, -0.547684, -0.264287, 0.767712], [-0.121869, 0.992546, -0.477722, -0.209511, 0.853163, 0.178279, -0.562672, -0.232494, 0.773023], [-0.104528, 0.994522, -0.483611, -0.180057, 0.856563, 0.153937, -0.575747, -0.200207, 0.777648], [-0.087156, 0.996195, -0.488606, -0.150384, 0.859447, 0.129078, -0.586872, -0.167494, 0.781579], [-0.069756, 0.997564, -0.492701, -0.120527, 0.861811, 0.103786, -0.596018, -0.134426, 0.784806], [-0.052336, 0.998630, -0.495891, -0.090524, 0.863653, 0.078146, -0.603158, -0.101071, 0.787324], [-0.034899, 0.999391, -0.498173, -0.060411, 0.864971, 0.052243, -0.608272, -0.067500, 0.789126], [-0.017452, 0.999848, -0.499543, -0.030224, 0.865762, 0.026165, -0.611347, -0.033786, 0.790208], [0.000000, 1.000000, -0.500000, 0.000000, 0.866025, -0.000000, -0.612372, 0.000000, 0.790569], [0.017452, 0.999848, -0.499543, 0.030224, 0.865762, -0.026165, -0.611347, 0.033786, 0.790208], [0.034899, 0.999391, -0.498173, 0.060411, 0.864971, -0.052243, -0.608272, 0.067500, 0.789126], [0.052336, 0.998630, -0.495891, 0.090524, 0.863653, -0.078146, -0.603158, 0.101071, 0.787324], [0.069756, 0.997564, -0.492701, 0.120527, 0.861811, -0.103786, -0.596018, 0.134426, 0.784806], [0.087156, 0.996195, -0.488606, 0.150384, 0.859447, -0.129078, -0.586872, 0.167494, 0.781579], [0.104528, 0.994522, -0.483611, 0.180057, 0.856563, -0.153937, -0.575747, 0.200207, 0.777648], [0.121869, 0.992546, -0.477722, 0.209511, 0.853163, -0.178279, -0.562672, 0.232494, 0.773023], [0.139173, 0.990268, -0.470946, 0.238709, 0.849251, -0.202020, -0.547684, 0.264287, 0.767712], [0.156434, 0.987688, -0.463292, 0.267617, 0.844832, -0.225081, -0.530827, 0.295521, 0.761728], [0.173648, 0.984808, -0.454769, 0.296198, 0.839912, -0.247382, -0.512145, 0.326129, 0.755082], [0.190809, 0.981627, -0.445388, 0.324419, 0.834495, -0.268846, -0.491693, 0.356047, 0.747790], [0.207912, 0.978148, -0.435159, 0.352244, 0.828589, -0.289399, -0.469527, 0.385215, 0.739866], [0.224951, 0.974370, -0.424096, 0.379641, 0.822202, -0.308969, -0.445709, 0.413572, 0.731327], [0.241922, 0.970296, -0.412211, 0.406574, 0.815340, -0.327486, -0.420306, 0.441061, 0.722191], [0.258819, 0.965926, -0.399519, 0.433013, 0.808013, -0.344885, -0.393389, 0.467627, 0.712478], [0.275637, 0.961262, -0.386036, 0.458924, 0.800228, -0.361102, -0.365034, 0.493216, 0.702207], [0.292372, 0.956305, -0.371778, 0.484275, 0.791997, -0.376077, -0.335319, 0.517778, 0.691399], [0.309017, 0.951057, -0.356763, 0.509037, 0.783327, -0.389754, -0.304329, 0.541266, 0.680078], [0.325568, 0.945519, -0.341008, 0.533178, 0.774231, -0.402081, -0.272150, 0.563635, 0.668267], [0.342020, 0.939693, -0.324533, 0.556670, 0.764720, -0.413008, -0.238872, 0.584843, 0.655990], [0.358368, 0.933580, -0.307359, 0.579484, 0.754804, -0.422491, -0.204589, 0.604851, 0.643273], [0.374607, 0.927184, -0.289505, 0.601592, 0.744496, -0.430488, -0.169397, 0.623624, 0.630141], [0.390731, 0.920505, -0.270994, 0.622967, 0.733809, -0.436964, -0.133395, 0.641130, 0.616621], [0.406737, 0.913545, -0.251848, 0.643582, 0.722755, -0.441884, -0.096684, 0.657339, 0.602741], [0.422618, 0.906308, -0.232091, 0.663414, 0.711348, -0.445222, -0.059368, 0.672226, 0.588528], [0.438371, 0.898794, -0.211746, 0.682437, 0.699602, -0.446953, -0.021550, 0.685769, 0.574011], [0.453990, 0.891007, -0.190839, 0.700629, 0.687531, -0.447059, 0.016662, 0.697950, 0.559220], [0.469472, 0.882948, -0.169395, 0.717968, 0.675150, -0.445524, 0.055160, 0.708753, 0.544183], [0.484810, 0.874620, -0.147439, 0.734431, 0.662474, -0.442340, 0.093837, 0.718167, 0.528929], [0.500000, 0.866025, -0.125000, 0.750000, 0.649519, -0.437500, 0.132583, 0.726184, 0.513490], [0.515038, 0.857167, -0.102104, 0.764655, 0.636300, -0.431004, 0.171288, 0.732801, 0.497894], [0.529919, 0.848048, -0.078778, 0.778378, 0.622833, -0.422856, 0.209843, 0.738017, 0.482171], [0.544639, 0.838671, -0.055052, 0.791154, 0.609135, -0.413066, 0.248140, 0.741835, 0.466352], [0.559193, 0.829038, -0.030955, 0.802965, 0.595222, -0.401645, 0.286069, 0.744262, 0.450467], [0.573576, 0.819152, -0.006515, 0.813798, 0.581112, -0.388612, 0.323524, 0.745308, 0.434544], [0.587785, 0.809017, 0.018237, 0.823639, 0.566821, -0.373991, 0.360397, 0.744989, 0.418613], [0.601815, 0.798636, 0.043272, 0.832477, 0.552367, -0.357807, 0.396584, 0.743320, 0.402704], [0.615661, 0.788011, 0.068559, 0.840301, 0.537768, -0.340093, 0.431982, 0.740324, 0.386845], [0.629320, 0.777146, 0.094066, 0.847101, 0.523041, -0.320884, 0.466490, 0.736025, 0.371063], [0.642788, 0.766044, 0.119764, 0.852869, 0.508205, -0.300221, 0.500009, 0.730451, 0.355387], [0.656059, 0.754710, 0.145620, 0.857597, 0.493276, -0.278147, 0.532443, 0.723633, 0.339844], [0.669131, 0.743145, 0.171604, 0.861281, 0.478275, -0.254712, 0.563700, 0.715605, 0.324459], [0.681998, 0.731354, 0.197683, 0.863916, 0.463218, -0.229967, 0.593688, 0.706405, 0.309259], [0.694658, 0.719340, 0.223825, 0.865498, 0.448125, -0.203969, 0.622322, 0.696073, 0.294267], [0.707107, 0.707107, 0.250000, 0.866025, 0.433013, -0.176777, 0.649519, 0.684653, 0.279508], [0.719340, 0.694658, 0.276175, 0.865498, 0.417901, -0.148454, 0.675199, 0.672190, 0.265005], [0.731354, 0.681998, 0.302317, 0.863916, 0.402807, -0.119068, 0.699288, 0.658734, 0.250778], [0.743145, 0.669131, 0.328396, 0.861281, 0.387751, -0.088686, 0.721714, 0.644334, 0.236850], [0.754710, 0.656059, 0.354380, 0.857597, 0.372749, -0.057383, 0.742412, 0.629044, 0.223238], [0.766044, 0.642788, 0.380236, 0.852869, 0.357821, -0.025233, 0.761319, 0.612921, 0.209963], [0.777146, 0.629320, 0.405934, 0.847101, 0.342984, 0.007686, 0.778379, 0.596021, 0.197040], [0.788011, 0.615661, 0.431441, 0.840301, 0.328257, 0.041294, 0.793541, 0.578405, 0.184487], [0.798636, 0.601815, 0.456728, 0.832477, 0.313658, 0.075508, 0.806757, 0.560132, 0.172317], [0.809017, 0.587785, 0.481763, 0.823639, 0.299204, 0.110246, 0.817987, 0.541266, 0.160545], [0.819152, 0.573576, 0.506515, 0.813798, 0.284914, 0.145420, 0.827194, 0.521871, 0.149181], [0.829038, 0.559193, 0.530955, 0.802965, 0.270803, 0.180944, 0.834347, 0.502011, 0.138237], [0.838671, 0.544639, 0.555052, 0.791154, 0.256891, 0.216730, 0.839422, 0.481753, 0.127722], [0.848048, 0.529919, 0.578778, 0.778378, 0.243192, 0.252688, 0.842399, 0.461164, 0.117644], [0.857167, 0.515038, 0.602104, 0.764655, 0.229726, 0.288728, 0.843265, 0.440311, 0.108009], [0.866025, 0.500000, 0.625000, 0.750000, 0.216506, 0.324760, 0.842012, 0.419263, 0.098821], [0.874620, 0.484810, 0.647439, 0.734431, 0.203551, 0.360692, 0.838638, 0.398086, 0.090085], [0.882948, 0.469472, 0.669395, 0.717968, 0.190875, 0.396436, 0.833145, 0.376851, 0.081803], [0.891007, 0.453990, 0.690839, 0.700629, 0.178494, 0.431899, 0.825544, 0.355623, 0.073974], [0.898794, 0.438371, 0.711746, 0.682437, 0.166423, 0.466993, 0.815850, 0.334472, 0.066599], [0.906308, 0.422618, 0.732091, 0.663414, 0.154678, 0.501627, 0.804083, 0.313464, 0.059674], [0.913545, 0.406737, 0.751848, 0.643582, 0.143271, 0.535715, 0.790270, 0.292666, 0.053196], [0.920505, 0.390731, 0.770994, 0.622967, 0.132217, 0.569169, 0.774442, 0.272143, 0.047160], [0.927184, 0.374607, 0.789505, 0.601592, 0.121529, 0.601904, 0.756637, 0.251960, 0.041559], [0.933580, 0.358368, 0.807359, 0.579484, 0.111222, 0.633837, 0.736898, 0.232180, 0.036385], [0.939693, 0.342020, 0.824533, 0.556670, 0.101306, 0.664885, 0.715274, 0.212865, 0.031630], [0.945519, 0.325568, 0.841008, 0.533178, 0.091794, 0.694969, 0.691816, 0.194075, 0.027281], [0.951057, 0.309017, 0.856763, 0.509037, 0.082698, 0.724012, 0.666583, 0.175868, 0.023329], [0.956305, 0.292372, 0.871778, 0.484275, 0.074029, 0.751940, 0.639639, 0.158301, 0.019758], [0.961262, 0.275637, 0.886036, 0.458924, 0.065797, 0.778680, 0.611050, 0.141427, 0.016556], [0.965926, 0.258819, 0.899519, 0.433013, 0.058013, 0.804164, 0.580889, 0.125300, 0.013707], [0.970296, 0.241922, 0.912211, 0.406574, 0.050685, 0.828326, 0.549233, 0.109969, 0.011193], [0.974370, 0.224951, 0.924096, 0.379641, 0.043823, 0.851105, 0.516162, 0.095481, 0.008999], [0.978148, 0.207912, 0.935159, 0.352244, 0.037436, 0.872441, 0.481759, 0.081880, 0.007105], [0.981627, 0.190809, 0.945388, 0.324419, 0.031530, 0.892279, 0.446114, 0.069209, 0.005492], [0.984808, 0.173648, 0.954769, 0.296198, 0.026114, 0.910569, 0.409317, 0.057505, 0.004140], [0.987688, 0.156434, 0.963292, 0.267617, 0.021193, 0.927262, 0.371463, 0.046806, 0.003026], [0.990268, 0.139173, 0.970946, 0.238709, 0.016774, 0.942316, 0.332649, 0.037143, 0.002131], [0.992546, 0.121869, 0.977722, 0.209511, 0.012862, 0.955693, 0.292976, 0.028547, 0.001431], [0.994522, 0.104528, 0.983611, 0.180057, 0.009462, 0.967356, 0.252544, 0.021043, 0.000903], [0.996195, 0.087156, 0.988606, 0.150384, 0.006578, 0.977277, 0.211460, 0.014654, 0.000523], [0.997564, 0.069756, 0.992701, 0.120527, 0.004214, 0.985429, 0.169828, 0.009400, 0.000268], [0.998630, 0.052336, 0.995891, 0.090524, 0.002372, 0.991791, 0.127757, 0.005297, 0.000113], [0.999391, 0.034899, 0.998173, 0.060411, 0.001055, 0.996348, 0.085356, 0.002357, 0.000034], [0.999848, 0.017452, 0.999543, 0.030224, 0.000264, 0.999086, 0.042733, 0.000590, 0.000004], [1.000000, -0.000000, 1.000000, -0.000000, 0.000000, 1.000000, -0.000000, 0.000000, -0.000000], ], ]; export const SPHERICAL_HARMONICS_AZIMUTH_RESOLUTION = SPHERICAL_HARMONICS[0].length; export const SPHERICAL_HARMONICS_ELEVATION_RESOLUTION = SPHERICAL_HARMONICS[1].length; /** * The maximum allowed ambisonic order. */ export const SPHERICAL_HARMONICS_MAX_ORDER = SPHERICAL_HARMONICS[0][0].length / 2; /** * Pre-computed per-band weighting coefficients for producing energy-preserving * Max-Re sources. */ export const MAX_RE_WEIGHTS = [ [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.000000, 1.000000, 1.000000, 1.000000], [1.003236, 1.002156, 0.999152, 0.990038], [1.032370, 1.021194, 0.990433, 0.898572], [1.062694, 1.040231, 0.979161, 0.799806], [1.093999, 1.058954, 0.964976, 0.693603], [1.126003, 1.077006, 0.947526, 0.579890], [1.158345, 1.093982, 0.926474, 0.458690], [1.190590, 1.109437, 0.901512, 0.330158], [1.222228, 1.122890, 0.872370, 0.194621], [1.252684, 1.133837, 0.838839, 0.052614], [1.281987, 1.142358, 0.801199, 0.000000], [1.312073, 1.150207, 0.760839, 0.000000], [1.343011, 1.157424, 0.717799, 0.000000], [1.374649, 1.163859, 0.671999, 0.000000], [1.406809, 1.169354, 0.623371, 0.000000], [1.439286, 1.173739, 0.571868, 0.000000], [1.471846, 1.176837, 0.517465, 0.000000], [1.504226, 1.178465, 0.460174, 0.000000], [1.536133, 1.178438, 0.400043, 0.000000], [1.567253, 1.176573, 0.337165, 0.000000], [1.597247, 1.172695, 0.271688, 0.000000], [1.625766, 1.166645, 0.203815, 0.000000], [1.652455, 1.158285, 0.133806, 0.000000], [1.676966, 1.147506, 0.061983, 0.000000], [1.699006, 1.134261, 0.000000, 0.000000], [1.720224, 1.119789, 0.000000, 0.000000], [1.741631, 1.104810, 0.000000, 0.000000], [1.763183, 1.089330, 0.000000, 0.000000], [1.784837, 1.073356, 0.000000, 0.000000], [1.806548, 1.056898, 0.000000, 0.000000], [1.828269, 1.039968, 0.000000, 0.000000], [1.849952, 1.022580, 0.000000, 0.000000], [1.871552, 1.004752, 0.000000, 0.000000], [1.893018, 0.986504, 0.000000, 0.000000], [1.914305, 0.967857, 0.000000, 0.000000], [1.935366, 0.948837, 0.000000, 0.000000], [1.956154, 0.929471, 0.000000, 0.000000], [1.976625, 0.909790, 0.000000, 0.000000], [1.996736, 0.889823, 0.000000, 0.000000], [2.016448, 0.869607, 0.000000, 0.000000], [2.035721, 0.849175, 0.000000, 0.000000], [2.054522, 0.828565, 0.000000, 0.000000], [2.072818, 0.807816, 0.000000, 0.000000], [2.090581, 0.786964, 0.000000, 0.000000], [2.107785, 0.766051, 0.000000, 0.000000], [2.124411, 0.745115, 0.000000, 0.000000], [2.140439, 0.724196, 0.000000, 0.000000], [2.155856, 0.703332, 0.000000, 0.000000], [2.170653, 0.682561, 0.000000, 0.000000], [2.184823, 0.661921, 0.000000, 0.000000], [2.198364, 0.641445, 0.000000, 0.000000], [2.211275, 0.621169, 0.000000, 0.000000], [2.223562, 0.601125, 0.000000, 0.000000], [2.235230, 0.581341, 0.000000, 0.000000], [2.246289, 0.561847, 0.000000, 0.000000], [2.256751, 0.542667, 0.000000, 0.000000], [2.266631, 0.523826, 0.000000, 0.000000], [2.275943, 0.505344, 0.000000, 0.000000], [2.284707, 0.487239, 0.000000, 0.000000], [2.292939, 0.469528, 0.000000, 0.000000], [2.300661, 0.452225, 0.000000, 0.000000], [2.307892, 0.435342, 0.000000, 0.000000], [2.314654, 0.418888, 0.000000, 0.000000], [2.320969, 0.402870, 0.000000, 0.000000], [2.326858, 0.387294, 0.000000, 0.000000], [2.332343, 0.372164, 0.000000, 0.000000], [2.337445, 0.357481, 0.000000, 0.000000], [2.342186, 0.343246, 0.000000, 0.000000], [2.346585, 0.329458, 0.000000, 0.000000], [2.350664, 0.316113, 0.000000, 0.000000], [2.354442, 0.303208, 0.000000, 0.000000], [2.357937, 0.290738, 0.000000, 0.000000], [2.361168, 0.278698, 0.000000, 0.000000], [2.364152, 0.267080, 0.000000, 0.000000], [2.366906, 0.255878, 0.000000, 0.000000], [2.369446, 0.245082, 0.000000, 0.000000], [2.371786, 0.234685, 0.000000, 0.000000], [2.373940, 0.224677, 0.000000, 0.000000], [2.375923, 0.215048, 0.000000, 0.000000], [2.377745, 0.205790, 0.000000, 0.000000], [2.379421, 0.196891, 0.000000, 0.000000], [2.380959, 0.188342, 0.000000, 0.000000], [2.382372, 0.180132, 0.000000, 0.000000], [2.383667, 0.172251, 0.000000, 0.000000], [2.384856, 0.164689, 0.000000, 0.000000], [2.385945, 0.157435, 0.000000, 0.000000], [2.386943, 0.150479, 0.000000, 0.000000], [2.387857, 0.143811, 0.000000, 0.000000], [2.388694, 0.137421, 0.000000, 0.000000], [2.389460, 0.131299, 0.000000, 0.000000], [2.390160, 0.125435, 0.000000, 0.000000], [2.390801, 0.119820, 0.000000, 0.000000], [2.391386, 0.114445, 0.000000, 0.000000], [2.391921, 0.109300, 0.000000, 0.000000], [2.392410, 0.104376, 0.000000, 0.000000], [2.392857, 0.099666, 0.000000, 0.000000], [2.393265, 0.095160, 0.000000, 0.000000], [2.393637, 0.090851, 0.000000, 0.000000], [2.393977, 0.086731, 0.000000, 0.000000], [2.394288, 0.082791, 0.000000, 0.000000], [2.394571, 0.079025, 0.000000, 0.000000], [2.394829, 0.075426, 0.000000, 0.000000], [2.395064, 0.071986, 0.000000, 0.000000], [2.395279, 0.068699, 0.000000, 0.000000], [2.395475, 0.065558, 0.000000, 0.000000], [2.395653, 0.062558, 0.000000, 0.000000], [2.395816, 0.059693, 0.000000, 0.000000], [2.395964, 0.056955, 0.000000, 0.000000], [2.396099, 0.054341, 0.000000, 0.000000], [2.396222, 0.051845, 0.000000, 0.000000], [2.396334, 0.049462, 0.000000, 0.000000], [2.396436, 0.047186, 0.000000, 0.000000], [2.396529, 0.045013, 0.000000, 0.000000], [2.396613, 0.042939, 0.000000, 0.000000], [2.396691, 0.040959, 0.000000, 0.000000], [2.396761, 0.039069, 0.000000, 0.000000], [2.396825, 0.037266, 0.000000, 0.000000], [2.396883, 0.035544, 0.000000, 0.000000], [2.396936, 0.033901, 0.000000, 0.000000], [2.396984, 0.032334, 0.000000, 0.000000], [2.397028, 0.030838, 0.000000, 0.000000], [2.397068, 0.029410, 0.000000, 0.000000], [2.397104, 0.028048, 0.000000, 0.000000], [2.397137, 0.026749, 0.000000, 0.000000], [2.397167, 0.025509, 0.000000, 0.000000], [2.397194, 0.024326, 0.000000, 0.000000], [2.397219, 0.023198, 0.000000, 0.000000], [2.397242, 0.022122, 0.000000, 0.000000], [2.397262, 0.021095, 0.000000, 0.000000], [2.397281, 0.020116, 0.000000, 0.000000], [2.397298, 0.019181, 0.000000, 0.000000], [2.397314, 0.018290, 0.000000, 0.000000], [2.397328, 0.017441, 0.000000, 0.000000], [2.397341, 0.016630, 0.000000, 0.000000], [2.397352, 0.015857, 0.000000, 0.000000], [2.397363, 0.015119, 0.000000, 0.000000], [2.397372, 0.014416, 0.000000, 0.000000], [2.397381, 0.013745, 0.000000, 0.000000], [2.397389, 0.013106, 0.000000, 0.000000], [2.397396, 0.012496, 0.000000, 0.000000], [2.397403, 0.011914, 0.000000, 0.000000], [2.397409, 0.011360, 0.000000, 0.000000], [2.397414, 0.010831, 0.000000, 0.000000], [2.397419, 0.010326, 0.000000, 0.000000], [2.397424, 0.009845, 0.000000, 0.000000], [2.397428, 0.009387, 0.000000, 0.000000], [2.397432, 0.008949, 0.000000, 0.000000], [2.397435, 0.008532, 0.000000, 0.000000], [2.397438, 0.008135, 0.000000, 0.000000], [2.397441, 0.007755, 0.000000, 0.000000], [2.397443, 0.007394, 0.000000, 0.000000], [2.397446, 0.007049, 0.000000, 0.000000], [2.397448, 0.006721, 0.000000, 0.000000], [2.397450, 0.006407, 0.000000, 0.000000], [2.397451, 0.006108, 0.000000, 0.000000], [2.397453, 0.005824, 0.000000, 0.000000], [2.397454, 0.005552, 0.000000, 0.000000], [2.397456, 0.005293, 0.000000, 0.000000], [2.397457, 0.005046, 0.000000, 0.000000], [2.397458, 0.004811, 0.000000, 0.000000], [2.397459, 0.004586, 0.000000, 0.000000], [2.397460, 0.004372, 0.000000, 0.000000], [2.397461, 0.004168, 0.000000, 0.000000], [2.397461, 0.003974, 0.000000, 0.000000], [2.397462, 0.003788, 0.000000, 0.000000], [2.397463, 0.003611, 0.000000, 0.000000], [2.397463, 0.003443, 0.000000, 0.000000], [2.397464, 0.003282, 0.000000, 0.000000], [2.397464, 0.003129, 0.000000, 0.000000], [2.397465, 0.002983, 0.000000, 0.000000], [2.397465, 0.002844, 0.000000, 0.000000], [2.397465, 0.002711, 0.000000, 0.000000], [2.397466, 0.002584, 0.000000, 0.000000], [2.397466, 0.002464, 0.000000, 0.000000], [2.397466, 0.002349, 0.000000, 0.000000], [2.397466, 0.002239, 0.000000, 0.000000], [2.397467, 0.002135, 0.000000, 0.000000], [2.397467, 0.002035, 0.000000, 0.000000], [2.397467, 0.001940, 0.000000, 0.000000], [2.397467, 0.001849, 0.000000, 0.000000], [2.397467, 0.001763, 0.000000, 0.000000], [2.397467, 0.001681, 0.000000, 0.000000], [2.397468, 0.001602, 0.000000, 0.000000], [2.397468, 0.001527, 0.000000, 0.000000], [2.397468, 0.001456, 0.000000, 0.000000], [2.397468, 0.001388, 0.000000, 0.000000], [2.397468, 0.001323, 0.000000, 0.000000], [2.397468, 0.001261, 0.000000, 0.000000], [2.397468, 0.001202, 0.000000, 0.000000], [2.397468, 0.001146, 0.000000, 0.000000], [2.397468, 0.001093, 0.000000, 0.000000], [2.397468, 0.001042, 0.000000, 0.000000], [2.397468, 0.000993, 0.000000, 0.000000], [2.397468, 0.000947, 0.000000, 0.000000], [2.397468, 0.000902, 0.000000, 0.000000], [2.397468, 0.000860, 0.000000, 0.000000], [2.397468, 0.000820, 0.000000, 0.000000], [2.397469, 0.000782, 0.000000, 0.000000], [2.397469, 0.000745, 0.000000, 0.000000], [2.397469, 0.000710, 0.000000, 0.000000], [2.397469, 0.000677, 0.000000, 0.000000], [2.397469, 0.000646, 0.000000, 0.000000], [2.397469, 0.000616, 0.000000, 0.000000], [2.397469, 0.000587, 0.000000, 0.000000], [2.397469, 0.000559, 0.000000, 0.000000], [2.397469, 0.000533, 0.000000, 0.000000], [2.397469, 0.000508, 0.000000, 0.000000], [2.397469, 0.000485, 0.000000, 0.000000], [2.397469, 0.000462, 0.000000, 0.000000], [2.397469, 0.000440, 0.000000, 0.000000], [2.397469, 0.000420, 0.000000, 0.000000], [2.397469, 0.000400, 0.000000, 0.000000], [2.397469, 0.000381, 0.000000, 0.000000], [2.397469, 0.000364, 0.000000, 0.000000], [2.397469, 0.000347, 0.000000, 0.000000], [2.397469, 0.000330, 0.000000, 0.000000], [2.397469, 0.000315, 0.000000, 0.000000], [2.397469, 0.000300, 0.000000, 0.000000], [2.397469, 0.000286, 0.000000, 0.000000], [2.397469, 0.000273, 0.000000, 0.000000], [2.397469, 0.000260, 0.000000, 0.000000], [2.397469, 0.000248, 0.000000, 0.000000], [2.397469, 0.000236, 0.000000, 0.000000], [2.397469, 0.000225, 0.000000, 0.000000], [2.397469, 0.000215, 0.000000, 0.000000], [2.397469, 0.000205, 0.000000, 0.000000], [2.397469, 0.000195, 0.000000, 0.000000], [2.397469, 0.000186, 0.000000, 0.000000], [2.397469, 0.000177, 0.000000, 0.000000], [2.397469, 0.000169, 0.000000, 0.000000], [2.397469, 0.000161, 0.000000, 0.000000], [2.397469, 0.000154, 0.000000, 0.000000], [2.397469, 0.000147, 0.000000, 0.000000], [2.397469, 0.000140, 0.000000, 0.000000], [2.397469, 0.000133, 0.000000, 0.000000], [2.397469, 0.000127, 0.000000, 0.000000], [2.397469, 0.000121, 0.000000, 0.000000], [2.397469, 0.000115, 0.000000, 0.000000], [2.397469, 0.000110, 0.000000, 0.000000], [2.397469, 0.000105, 0.000000, 0.000000], [2.397469, 0.000100, 0.000000, 0.000000], [2.397469, 0.000095, 0.000000, 0.000000], [2.397469, 0.000091, 0.000000, 0.000000], [2.397469, 0.000087, 0.000000, 0.000000], [2.397469, 0.000083, 0.000000, 0.000000], [2.397469, 0.000079, 0.000000, 0.000000], [2.397469, 0.000075, 0.000000, 0.000000], [2.397469, 0.000071, 0.000000, 0.000000], [2.397469, 0.000068, 0.000000, 0.000000], [2.397469, 0.000065, 0.000000, 0.000000], [2.397469, 0.000062, 0.000000, 0.000000], [2.397469, 0.000059, 0.000000, 0.000000], [2.397469, 0.000056, 0.000000, 0.000000], [2.397469, 0.000054, 0.000000, 0.000000], [2.397469, 0.000051, 0.000000, 0.000000], [2.397469, 0.000049, 0.000000, 0.000000], [2.397469, 0.000046, 0.000000, 0.000000], [2.397469, 0.000044, 0.000000, 0.000000], [2.397469, 0.000042, 0.000000, 0.000000], [2.397469, 0.000040, 0.000000, 0.000000], [2.397469, 0.000038, 0.000000, 0.000000], [2.397469, 0.000037, 0.000000, 0.000000], [2.397469, 0.000035, 0.000000, 0.000000], [2.397469, 0.000033, 0.000000, 0.000000], [2.397469, 0.000032, 0.000000, 0.000000], [2.397469, 0.000030, 0.000000, 0.000000], [2.397469, 0.000029, 0.000000, 0.000000], [2.397469, 0.000027, 0.000000, 0.000000], [2.397469, 0.000026, 0.000000, 0.000000], [2.397469, 0.000025, 0.000000, 0.000000], [2.397469, 0.000024, 0.000000, 0.000000], [2.397469, 0.000023, 0.000000, 0.000000], [2.397469, 0.000022, 0.000000, 0.000000], [2.397469, 0.000021, 0.000000, 0.000000], [2.397469, 0.000020, 0.000000, 0.000000], [2.397469, 0.000019, 0.000000, 0.000000], [2.397469, 0.000018, 0.000000, 0.000000], [2.397469, 0.000017, 0.000000, 0.000000], [2.397469, 0.000016, 0.000000, 0.000000], [2.397469, 0.000015, 0.000000, 0.000000], [2.397469, 0.000015, 0.000000, 0.000000], [2.397469, 0.000014, 0.000000, 0.000000], [2.397469, 0.000013, 0.000000, 0.000000], [2.397469, 0.000013, 0.000000, 0.000000], [2.397469, 0.000012, 0.000000, 0.000000], [2.397469, 0.000012, 0.000000, 0.000000], [2.397469, 0.000011, 0.000000, 0.000000], [2.397469, 0.000011, 0.000000, 0.000000], [2.397469, 0.000010, 0.000000, 0.000000], [2.397469, 0.000010, 0.000000, 0.000000], [2.397469, 0.000009, 0.000000, 0.000000], [2.397469, 0.000009, 0.000000, 0.000000], [2.397469, 0.000008, 0.000000, 0.000000], [2.397469, 0.000008, 0.000000, 0.000000], [2.397469, 0.000008, 0.000000, 0.000000], [2.397469, 0.000007, 0.000000, 0.000000], [2.397469, 0.000007, 0.000000, 0.000000], [2.397469, 0.000007, 0.000000, 0.000000], [2.397469, 0.000006, 0.000000, 0.000000], [2.397469, 0.000006, 0.000000, 0.000000], [2.397469, 0.000006, 0.000000, 0.000000], [2.397469, 0.000005, 0.000000, 0.000000], [2.397469, 0.000005, 0.000000, 0.000000], [2.397469, 0.000005, 0.000000, 0.000000], [2.397469, 0.000005, 0.000000, 0.000000], [2.397469, 0.000004, 0.000000, 0.000000], [2.397469, 0.000004, 0.000000, 0.000000], [2.397469, 0.000004, 0.000000, 0.000000], [2.397469, 0.000004, 0.000000, 0.000000], [2.397469, 0.000004, 0.000000, 0.000000], [2.397469, 0.000004, 0.000000, 0.000000], [2.397469, 0.000003, 0.000000, 0.000000], [2.397469, 0.000003, 0.000000, 0.000000], [2.397469, 0.000003, 0.000000, 0.000000], [2.397469, 0.000003, 0.000000, 0.000000], [2.397469, 0.000003, 0.000000, 0.000000], [2.397469, 0.000003, 0.000000, 0.000000], [2.397469, 0.000003, 0.000000, 0.000000], [2.397469, 0.000002, 0.000000, 0.000000], [2.397469, 0.000002, 0.000000, 0.000000], [2.397469, 0.000002, 0.000000, 0.000000], [2.397469, 0.000002, 0.000000, 0.000000], [2.397469, 0.000002, 0.000000, 0.000000], [2.397469, 0.000002, 0.000000, 0.000000], [2.397469, 0.000002, 0.000000, 0.000000], [2.397469, 0.000002, 0.000000, 0.000000], [2.397469, 0.000002, 0.000000, 0.000000], [2.397469, 0.000002, 0.000000, 0.000000], [2.397469, 0.000001, 0.000000, 0.000000], [2.397469, 0.000001, 0.000000, 0.000000], [2.397469, 0.000001, 0.000000, 0.000000], ]; export const MAX_RE_WEIGHTS_RESOLUTION = MAX_RE_WEIGHTS.length;
the_stack
import * as React from 'react'; import { IPropertyFieldIconPickerPropsInternal } from './PropertyFieldIconPicker'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import GuidHelper from './GuidHelper'; /** * @interface * PropertyFieldIconPickerHost properties interface * */ export interface IPropertyFieldIconPickerHostProps extends IPropertyFieldIconPickerPropsInternal { } /** * @interface * PropertyFieldIconPickerHost state interface * */ export interface IPropertyFieldIconPickerHostState { isOpen: boolean; isHoverDropdown?: boolean; hoverFont?: string; selectedFont?: string; safeSelectedFont?: string; errorMessage?: string; } /** * @interface * Define a safe font object * */ interface ISafeFont { Name: string; SafeValue: string; } /** * @class * Renders the controls for PropertyFieldIconPicker component */ export default class PropertyFieldIconPickerHost extends React.Component<IPropertyFieldIconPickerHostProps, IPropertyFieldIconPickerHostState> { /** * @var * Defines the font series */ private fonts: ISafeFont[] = [ {Name: "DecreaseIndentLegacy", SafeValue: 'ms-Icon--DecreaseIndentLegacy'}, {Name: "IncreaseIndentLegacy", SafeValue: 'ms-Icon--IncreaseIndentLegacy'}, {Name: "GlobalNavButton", SafeValue: 'ms-Icon--GlobalNavButton'}, {Name: "InternetSharing", SafeValue: 'ms-Icon--InternetSharing'}, {Name: "Brightness", SafeValue: 'ms-Icon--Brightness'}, {Name: "MapPin", SafeValue: 'ms-Icon--MapPin'}, {Name: "Airplane", SafeValue: 'ms-Icon--Airplane'}, {Name: "Tablet", SafeValue: 'ms-Icon--Tablet'}, {Name: "QuickNote", SafeValue: 'ms-Icon--QuickNote'}, {Name: "ChevronDown", SafeValue: 'ms-Icon--ChevronDown'}, {Name: "ChevronUp", SafeValue: 'ms-Icon--ChevronUp'}, {Name: "Edit", SafeValue: 'ms-Icon--Edit'}, {Name: "Add", SafeValue: 'ms-Icon--Add'}, {Name: "Cancel", SafeValue: 'ms-Icon--Cancel'}, {Name: "More", SafeValue: 'ms-Icon--More'}, {Name: "Settings", SafeValue: 'ms-Icon--Settings'}, {Name: "Video", SafeValue: 'ms-Icon--Video'}, {Name: "Mail", SafeValue: 'ms-Icon--Mail'}, {Name: "People", SafeValue: 'ms-Icon--People'}, {Name: "Phone", SafeValue: 'ms-Icon--Phone'}, {Name: "Pin", SafeValue: 'ms-Icon--Pin'}, {Name: "Shop", SafeValue: 'ms-Icon--Shop'}, {Name: "Link", SafeValue: 'ms-Icon--Link'}, {Name: "Filter", SafeValue: 'ms-Icon--Filter'}, {Name: "Zoom", SafeValue: 'ms-Icon--Zoom'}, {Name: "ZoomOut", SafeValue: 'ms-Icon--ZoomOut'}, {Name: "Microphone", SafeValue: 'ms-Icon--Microphone'}, {Name: "Search", SafeValue: 'ms-Icon--Search'}, {Name: "Camera", SafeValue: 'ms-Icon--Camera'}, {Name: "Attach", SafeValue: 'ms-Icon--Attach'}, {Name: "Send", SafeValue: 'ms-Icon--Send'}, {Name: "FavoriteList", SafeValue: 'ms-Icon--FavoriteList'}, {Name: "PageSolid", SafeValue: 'ms-Icon--PageSolid'}, {Name: "Forward", SafeValue: 'ms-Icon--Forward'}, {Name: "Back", SafeValue: 'ms-Icon--Back'}, {Name: "Refresh", SafeValue: 'ms-Icon--Refresh'}, {Name: "Share", SafeValue: 'ms-Icon--Share'}, {Name: "Lock", SafeValue: 'ms-Icon--Lock'}, {Name: "EMI", SafeValue: 'ms-Icon--EMI'}, {Name: "MiniLink", SafeValue: 'ms-Icon--MiniLink'}, {Name: "Blocked", SafeValue: 'ms-Icon--Blocked'}, {Name: "FavoriteStar", SafeValue: 'ms-Icon--FavoriteStar'}, {Name: "FavoriteStarFill", SafeValue: 'ms-Icon--FavoriteStarFill'}, {Name: "ReadingMode", SafeValue: 'ms-Icon--ReadingMode'}, {Name: "Remove", SafeValue: 'ms-Icon--Remove'}, {Name: "Checkbox", SafeValue: 'ms-Icon--Checkbox'}, {Name: "CheckboxComposite", SafeValue: 'ms-Icon--CheckboxComposite'}, {Name: "CheckboxIndeterminate", SafeValue: 'ms-Icon--CheckboxIndeterminate'}, {Name: "CheckMark", SafeValue: 'ms-Icon--CheckMark'}, {Name: "BackToWindow", SafeValue: 'ms-Icon--BackToWindow'}, {Name: "FullScreen", SafeValue: 'ms-Icon--FullScreen'}, {Name: "Print", SafeValue: 'ms-Icon--Print'}, {Name: "Up", SafeValue: 'ms-Icon--Up'}, {Name: "Down", SafeValue: 'ms-Icon--Down'}, {Name: "Delete", SafeValue: 'ms-Icon--Delete'}, {Name: "Save", SafeValue: 'ms-Icon--Save'}, {Name: "SIPMove", SafeValue: 'ms-Icon--SIPMove'}, {Name: "EraseTool", SafeValue: 'ms-Icon--EraseTool'}, {Name: "GripperTool", SafeValue: 'ms-Icon--GripperTool'}, {Name: "Dialpad", SafeValue: 'ms-Icon--Dialpad'}, {Name: "PageLeft", SafeValue: 'ms-Icon--PageLeft'}, {Name: "PageRight", SafeValue: 'ms-Icon--PageRight'}, {Name: "MultiSelect", SafeValue: 'ms-Icon--MultiSelect'}, {Name: "Play", SafeValue: 'ms-Icon--Play'}, {Name: "Pause", SafeValue: 'ms-Icon--Pause'}, {Name: "ChevronLeft", SafeValue: 'ms-Icon--ChevronLeft'}, {Name: "ChevronRight", SafeValue: 'ms-Icon--ChevronRight'}, {Name: "Emoji2", SafeValue: 'ms-Icon--Emoji2'}, {Name: "System", SafeValue: 'ms-Icon--System'}, {Name: "Globe", SafeValue: 'ms-Icon--Globe'}, {Name: "Unpin", SafeValue: 'ms-Icon--Unpin'}, {Name: "Contact", SafeValue: 'ms-Icon--Contact'}, {Name: "Memo", SafeValue: 'ms-Icon--Memo'}, {Name: "WindowsLogo", SafeValue: 'ms-Icon--WindowsLogo'}, {Name: "Error", SafeValue: 'ms-Icon--Error'}, {Name: "Unlock", SafeValue: 'ms-Icon--Unlock'}, {Name: "Calendar", SafeValue: 'ms-Icon--Calendar'}, {Name: "Megaphone", SafeValue: 'ms-Icon--Megaphone'}, {Name: "AutoEnhanceOn", SafeValue: 'ms-Icon--AutoEnhanceOn'}, {Name: "AutoEnhanceOff", SafeValue: 'ms-Icon--AutoEnhanceOff'}, {Name: "Color", SafeValue: 'ms-Icon--Color'}, {Name: "SaveAs", SafeValue: 'ms-Icon--SaveAs'}, {Name: "Light", SafeValue: 'ms-Icon--Light'}, {Name: "Filters", SafeValue: 'ms-Icon--Filters'}, {Name: "Contrast", SafeValue: 'ms-Icon--Contrast'}, {Name: "Redo", SafeValue: 'ms-Icon--Redo'}, {Name: "Undo", SafeValue: 'ms-Icon--Undo'}, {Name: "Album", SafeValue: 'ms-Icon--Album'}, {Name: "Rotate", SafeValue: 'ms-Icon--Rotate'}, {Name: "PanoIndicator", SafeValue: 'ms-Icon--PanoIndicator'}, {Name: "ThumbnailView", SafeValue: 'ms-Icon--ThumbnailView'}, {Name: "Package", SafeValue: 'ms-Icon--Package'}, {Name: "Warning", SafeValue: 'ms-Icon--Warning'}, {Name: "Financial", SafeValue: 'ms-Icon--Financial'}, {Name: "ShoppingCart", SafeValue: 'ms-Icon--ShoppingCart'}, {Name: "Train", SafeValue: 'ms-Icon--Train'}, {Name: "Flag", SafeValue: 'ms-Icon--Flag'}, {Name: "Move", SafeValue: 'ms-Icon--Move'}, {Name: "Page", SafeValue: 'ms-Icon--Page'}, {Name: "TouchPointer", SafeValue: 'ms-Icon--TouchPointer'}, {Name: "Merge", SafeValue: 'ms-Icon--Merge'}, {Name: "TurnRight", SafeValue: 'ms-Icon--TurnRight'}, {Name: "Ferry", SafeValue: 'ms-Icon--Ferry'}, {Name: "Tab", SafeValue: 'ms-Icon--Tab'}, {Name: "Admin", SafeValue: 'ms-Icon--Admin'}, {Name: "TVMonitor", SafeValue: 'ms-Icon--TVMonitor'}, {Name: "Speakers", SafeValue: 'ms-Icon--Speakers'}, {Name: "Car", SafeValue: 'ms-Icon--Car'}, {Name: "EatDrink", SafeValue: 'ms-Icon--EatDrink'}, {Name: "LocationCircle", SafeValue: 'ms-Icon--LocationCircle'}, {Name: "Home", SafeValue: 'ms-Icon--Home'}, {Name: "SwitcherStartEnd", SafeValue: 'ms-Icon--SwitcherStartEnd'}, {Name: "IncidentTriangle", SafeValue: 'ms-Icon--IncidentTriangle'}, {Name: "Touch", SafeValue: 'ms-Icon--Touch'}, {Name: "MapDirections", SafeValue: 'ms-Icon--MapDirections'}, {Name: "History", SafeValue: 'ms-Icon--History'}, {Name: "Location", SafeValue: 'ms-Icon--Location'}, {Name: "Work", SafeValue: 'ms-Icon--Work'}, {Name: "Recent", SafeValue: 'ms-Icon--Recent'}, {Name: "Hotel", SafeValue: 'ms-Icon--Hotel'}, {Name: "LocationDot", SafeValue: 'ms-Icon--LocationDot'}, {Name: "News", SafeValue: 'ms-Icon--News'}, {Name: "Chat", SafeValue: 'ms-Icon--Chat'}, {Name: "Group", SafeValue: 'ms-Icon--Group'}, {Name: "View", SafeValue: 'ms-Icon--View'}, {Name: "Clear", SafeValue: 'ms-Icon--Clear'}, {Name: "Sync", SafeValue: 'ms-Icon--Sync'}, {Name: "Download", SafeValue: 'ms-Icon--Download'}, {Name: "Help", SafeValue: 'ms-Icon--Help'}, {Name: "Upload", SafeValue: 'ms-Icon--Upload'}, {Name: "Emoji", SafeValue: 'ms-Icon--Emoji'}, {Name: "MailForward", SafeValue: 'ms-Icon--MailForward'}, {Name: "ClosePane", SafeValue: 'ms-Icon--ClosePane'}, {Name: "OpenPane", SafeValue: 'ms-Icon--OpenPane'}, {Name: "PreviewLink", SafeValue: 'ms-Icon--PreviewLink'}, {Name: "ZoomIn", SafeValue: 'ms-Icon--ZoomIn'}, {Name: "Bookmarks", SafeValue: 'ms-Icon--Bookmarks'}, {Name: "Document", SafeValue: 'ms-Icon--Document'}, {Name: "ProtectedDocument", SafeValue: 'ms-Icon--ProtectedDocument'}, {Name: "OpenInNewWindow", SafeValue: 'ms-Icon--OpenInNewWindow'}, {Name: "MailFill", SafeValue: 'ms-Icon--MailFill'}, {Name: "ViewAll", SafeValue: 'ms-Icon--ViewAll'}, {Name: "Switch", SafeValue: 'ms-Icon--Switch'}, {Name: "Rename", SafeValue: 'ms-Icon--Rename'}, {Name: "Folder", SafeValue: 'ms-Icon--Folder'}, {Name: "Picture", SafeValue: 'ms-Icon--Picture'}, {Name: "ShowResults", SafeValue: 'ms-Icon--ShowResults'}, {Name: "Message", SafeValue: 'ms-Icon--Message'}, {Name: "CalendarDay", SafeValue: 'ms-Icon--CalendarDay'}, {Name: "CalendarWeek", SafeValue: 'ms-Icon--CalendarWeek'}, {Name: "MailReplyAll", SafeValue: 'ms-Icon--MailReplyAll'}, {Name: "Read", SafeValue: 'ms-Icon--Read'}, {Name: "PaymentCard", SafeValue: 'ms-Icon--PaymentCard'}, {Name: "Copy", SafeValue: 'ms-Icon--Copy'}, {Name: "Important", SafeValue: 'ms-Icon--Important'}, {Name: "MailReply", SafeValue: 'ms-Icon--MailReply'}, {Name: "Sort", SafeValue: 'ms-Icon--Sort'}, {Name: "GotoToday", SafeValue: 'ms-Icon--GotoToday'}, {Name: "Font", SafeValue: 'ms-Icon--Font'}, {Name: "FontColor", SafeValue: 'ms-Icon--FontColor'}, {Name: "FolderFill", SafeValue: 'ms-Icon--FolderFill'}, {Name: "Permissions", SafeValue: 'ms-Icon--Permissions'}, {Name: "DisableUpdates", SafeValue: 'ms-Icon--DisableUpdates'}, {Name: "Unfavorite", SafeValue: 'ms-Icon--Unfavorite'}, {Name: "Italic", SafeValue: 'ms-Icon--Italic'}, {Name: "Underline", SafeValue: 'ms-Icon--Underline'}, {Name: "Bold", SafeValue: 'ms-Icon--Bold'}, {Name: "MoveToFolder", SafeValue: 'ms-Icon--MoveToFolder'}, {Name: "Dislike", SafeValue: 'ms-Icon--Dislike'}, {Name: "Like", SafeValue: 'ms-Icon--Like'}, {Name: "AlignRight", SafeValue: 'ms-Icon--AlignRight'}, {Name: "AlignCenter", SafeValue: 'ms-Icon--AlignCenter'}, {Name: "AlignLeft", SafeValue: 'ms-Icon--AlignLeft'}, {Name: "OpenFile", SafeValue: 'ms-Icon--OpenFile'}, {Name: "FontDecrease", SafeValue: 'ms-Icon--FontDecrease'}, {Name: "FontIncrease", SafeValue: 'ms-Icon--FontIncrease'}, {Name: "FontSize", SafeValue: 'ms-Icon--FontSize'}, {Name: "CellPhone", SafeValue: 'ms-Icon--CellPhone'}, {Name: "Tag", SafeValue: 'ms-Icon--Tag'}, {Name: "Library", SafeValue: 'ms-Icon--Library'}, {Name: "PostUpdate", SafeValue: 'ms-Icon--PostUpdate'}, {Name: "NewFolder", SafeValue: 'ms-Icon--NewFolder'}, {Name: "CalendarReply", SafeValue: 'ms-Icon--CalendarReply'}, {Name: "UnsyncFolder", SafeValue: 'ms-Icon--UnsyncFolder'}, {Name: "SyncFolder", SafeValue: 'ms-Icon--SyncFolder'}, {Name: "BlockContact", SafeValue: 'ms-Icon--BlockContact'}, {Name: "AddFriend", SafeValue: 'ms-Icon--AddFriend'}, {Name: "BulletedList", SafeValue: 'ms-Icon--BulletedList'}, {Name: "Preview", SafeValue: 'ms-Icon--Preview'}, {Name: "DockLeft", SafeValue: 'ms-Icon--DockLeft'}, {Name: "DockRight", SafeValue: 'ms-Icon--DockRight'}, {Name: "Repair", SafeValue: 'ms-Icon--Repair'}, {Name: "Accounts", SafeValue: 'ms-Icon--Accounts'}, {Name: "RadioBullet", SafeValue: 'ms-Icon--RadioBullet'}, {Name: "Stopwatch", SafeValue: 'ms-Icon--Stopwatch'}, {Name: "Clock", SafeValue: 'ms-Icon--Clock'}, {Name: "AlarmClock", SafeValue: 'ms-Icon--AlarmClock'}, {Name: "Hospital", SafeValue: 'ms-Icon--Hospital'}, {Name: "Timer", SafeValue: 'ms-Icon--Timer'}, {Name: "FullCircleMask", SafeValue: 'ms-Icon--FullCircleMask'}, {Name: "LocationFill", SafeValue: 'ms-Icon--LocationFill'}, {Name: "ChromeMinimize", SafeValue: 'ms-Icon--ChromeMinimize'}, {Name: "Annotation", SafeValue: 'ms-Icon--Annotation'}, {Name: "ChromeClose", SafeValue: 'ms-Icon--ChromeClose'}, {Name: "Accept", SafeValue: 'ms-Icon--Accept'}, {Name: "Fingerprint", SafeValue: 'ms-Icon--Fingerprint'}, {Name: "Handwriting", SafeValue: 'ms-Icon--Handwriting'}, {Name: "StackIndicator", SafeValue: 'ms-Icon--StackIndicator'}, {Name: "Completed", SafeValue: 'ms-Icon--Completed'}, {Name: "Label", SafeValue: 'ms-Icon--Label'}, {Name: "FlickDown", SafeValue: 'ms-Icon--FlickDown'}, {Name: "FlickUp", SafeValue: 'ms-Icon--FlickUp'}, {Name: "FlickLeft", SafeValue: 'ms-Icon--FlickLeft'}, {Name: "FlickRight", SafeValue: 'ms-Icon--FlickRight'}, {Name: "MusicInCollection", SafeValue: 'ms-Icon--MusicInCollection'}, {Name: "OneDrive", SafeValue: 'ms-Icon--OneDrive'}, {Name: "CompassNW", SafeValue: 'ms-Icon--CompassNW'}, {Name: "Code", SafeValue: 'ms-Icon--Code'}, {Name: "LightningBolt", SafeValue: 'ms-Icon--LightningBolt'}, {Name: "Info", SafeValue: 'ms-Icon--Info'}, {Name: "CalculatorAddition", SafeValue: 'ms-Icon--CalculatorAddition'}, {Name: "CalculatorSubtract", SafeValue: 'ms-Icon--CalculatorSubtract'}, {Name: "PrintfaxPrinterFile", SafeValue: 'ms-Icon--PrintfaxPrinterFile'}, {Name: "Health", SafeValue: 'ms-Icon--Health'}, {Name: "ChevronUpSmall", SafeValue: 'ms-Icon--ChevronUpSmall'}, {Name: "ChevronDownSmall", SafeValue: 'ms-Icon--ChevronDownSmall'}, {Name: "ChevronLeftSmall", SafeValue: 'ms-Icon--ChevronLeftSmall'}, {Name: "ChevronRightSmall", SafeValue: 'ms-Icon--ChevronRightSmall'}, {Name: "ChevronUpMed", SafeValue: 'ms-Icon--ChevronUpMed'}, {Name: "ChevronDownMed", SafeValue: 'ms-Icon--ChevronDownMed'}, {Name: "ChevronLeftMed", SafeValue: 'ms-Icon--ChevronLeftMed'}, {Name: "ChevronRightMed", SafeValue: 'ms-Icon--ChevronRightMed'}, {Name: "Dictionary", SafeValue: 'ms-Icon--Dictionary'}, {Name: "ChromeBack", SafeValue: 'ms-Icon--ChromeBack'}, {Name: "PC1", SafeValue: 'ms-Icon--PC1'}, {Name: "PresenceChickletVideo", SafeValue: 'ms-Icon--PresenceChickletVideo'}, {Name: "Reply", SafeValue: 'ms-Icon--Reply'}, {Name: "DoubleChevronLeftMed", SafeValue: 'ms-Icon--DoubleChevronLeftMed'}, {Name: "Volume0", SafeValue: 'ms-Icon--Volume0'}, {Name: "Volume1", SafeValue: 'ms-Icon--Volume1'}, {Name: "Volume2", SafeValue: 'ms-Icon--Volume2'}, {Name: "Volume3", SafeValue: 'ms-Icon--Volume3'}, {Name: "CaretHollow", SafeValue: 'ms-Icon--CaretHollow'}, {Name: "CaretSolid", SafeValue: 'ms-Icon--CaretSolid'}, {Name: "Pinned", SafeValue: 'ms-Icon--Pinned'}, {Name: "PinnedFill", SafeValue: 'ms-Icon--PinnedFill'}, {Name: "Chart", SafeValue: 'ms-Icon--Chart'}, {Name: "BidiLtr", SafeValue: 'ms-Icon--BidiLtr'}, {Name: "BidiRtl", SafeValue: 'ms-Icon--BidiRtl'}, {Name: "RevToggleKey", SafeValue: 'ms-Icon--RevToggleKey'}, {Name: "RightDoubleQuote", SafeValue: 'ms-Icon--RightDoubleQuote'}, {Name: "Sunny", SafeValue: 'ms-Icon--Sunny'}, {Name: "CloudWeather", SafeValue: 'ms-Icon--CloudWeather'}, {Name: "Cloudy", SafeValue: 'ms-Icon--Cloudy'}, {Name: "PartlyCloudyDay", SafeValue: 'ms-Icon--PartlyCloudyDay'}, {Name: "PartlyCloudyNight", SafeValue: 'ms-Icon--PartlyCloudyNight'}, {Name: "ClearNight", SafeValue: 'ms-Icon--ClearNight'}, {Name: "RainShowersDay", SafeValue: 'ms-Icon--RainShowersDay'}, {Name: "Rain", SafeValue: 'ms-Icon--Rain'}, {Name: "RainSnow", SafeValue: 'ms-Icon--RainSnow'}, {Name: "Snow", SafeValue: 'ms-Icon--Snow'}, {Name: "BlowingSnow", SafeValue: 'ms-Icon--BlowingSnow'}, {Name: "Frigid", SafeValue: 'ms-Icon--Frigid'}, {Name: "Fog", SafeValue: 'ms-Icon--Fog'}, {Name: "Squalls", SafeValue: 'ms-Icon--Squalls'}, {Name: "Duststorm", SafeValue: 'ms-Icon--Duststorm'}, {Name: "Precipitation", SafeValue: 'ms-Icon--Precipitation'}, {Name: "Ringer", SafeValue: 'ms-Icon--Ringer'}, {Name: "PDF", SafeValue: 'ms-Icon--PDF'}, {Name: "SortLines", SafeValue: 'ms-Icon--SortLines'}, {Name: "Ribbon", SafeValue: 'ms-Icon--Ribbon'}, {Name: "CheckList", SafeValue: 'ms-Icon--CheckList'}, {Name: "Generate", SafeValue: 'ms-Icon--Generate'}, {Name: "Equalizer", SafeValue: 'ms-Icon--Equalizer'}, {Name: "BarChartHorizontal", SafeValue: 'ms-Icon--BarChartHorizontal'}, {Name: "Freezing", SafeValue: 'ms-Icon--Freezing'}, {Name: "SnowShowerDay", SafeValue: 'ms-Icon--SnowShowerDay'}, {Name: "HailDay", SafeValue: 'ms-Icon--HailDay'}, {Name: "WorkFlow", SafeValue: 'ms-Icon--WorkFlow'}, {Name: "StoreLogoMed", SafeValue: 'ms-Icon--StoreLogoMed'}, {Name: "RainShowersNight", SafeValue: 'ms-Icon--RainShowersNight'}, {Name: "SnowShowerNight", SafeValue: 'ms-Icon--SnowShowerNight'}, {Name: "HailNight", SafeValue: 'ms-Icon--HailNight'}, {Name: "Info2", SafeValue: 'ms-Icon--Info2'}, {Name: "StoreLogo", SafeValue: 'ms-Icon--StoreLogo'}, {Name: "Broom", SafeValue: 'ms-Icon--Broom'}, {Name: "MusicInCollectionFill", SafeValue: 'ms-Icon--MusicInCollectionFill'}, {Name: "List", SafeValue: 'ms-Icon--List'}, {Name: "Asterisk", SafeValue: 'ms-Icon--Asterisk'}, {Name: "ErrorBadge", SafeValue: 'ms-Icon--ErrorBadge'}, {Name: "CircleRing", SafeValue: 'ms-Icon--CircleRing'}, {Name: "CircleFill", SafeValue: 'ms-Icon--CircleFill'}, {Name: "Lightbulb", SafeValue: 'ms-Icon--Lightbulb'}, {Name: "StatusTriangle", SafeValue: 'ms-Icon--StatusTriangle'}, {Name: "VolumeDisabled", SafeValue: 'ms-Icon--VolumeDisabled'}, {Name: "Puzzle", SafeValue: 'ms-Icon--Puzzle'}, {Name: "EmojiNeutral", SafeValue: 'ms-Icon--EmojiNeutral'}, {Name: "EmojiDisappointed", SafeValue: 'ms-Icon--EmojiDisappointed'}, {Name: "HomeSolid", SafeValue: 'ms-Icon--HomeSolid'}, {Name: "Cocktails", SafeValue: 'ms-Icon--Cocktails'}, {Name: "Articles", SafeValue: 'ms-Icon--Articles'}, {Name: "Cycling", SafeValue: 'ms-Icon--Cycling'}, {Name: "DietPlanNotebook", SafeValue: 'ms-Icon--DietPlanNotebook'}, {Name: "Pill", SafeValue: 'ms-Icon--Pill'}, {Name: "Running", SafeValue: 'ms-Icon--Running'}, {Name: "Weights", SafeValue: 'ms-Icon--Weights'}, {Name: "BarChart4", SafeValue: 'ms-Icon--BarChart4'}, {Name: "CirclePlus", SafeValue: 'ms-Icon--CirclePlus'}, {Name: "Coffee", SafeValue: 'ms-Icon--Coffee'}, {Name: "Cotton", SafeValue: 'ms-Icon--Cotton'}, {Name: "Market", SafeValue: 'ms-Icon--Market'}, {Name: "Money", SafeValue: 'ms-Icon--Money'}, {Name: "PieDouble", SafeValue: 'ms-Icon--PieDouble'}, {Name: "RemoveFilter", SafeValue: 'ms-Icon--RemoveFilter'}, {Name: "StockDown", SafeValue: 'ms-Icon--StockDown'}, {Name: "StockUp", SafeValue: 'ms-Icon--StockUp'}, {Name: "Cricket", SafeValue: 'ms-Icon--Cricket'}, {Name: "Golf", SafeValue: 'ms-Icon--Golf'}, {Name: "Baseball", SafeValue: 'ms-Icon--Baseball'}, {Name: "Soccer", SafeValue: 'ms-Icon--Soccer'}, {Name: "MoreSports", SafeValue: 'ms-Icon--MoreSports'}, {Name: "AutoRacing", SafeValue: 'ms-Icon--AutoRacing'}, {Name: "CollegeHoops", SafeValue: 'ms-Icon--CollegeHoops'}, {Name: "CollegeFootball", SafeValue: 'ms-Icon--CollegeFootball'}, {Name: "ProFootball", SafeValue: 'ms-Icon--ProFootball'}, {Name: "ProHockey", SafeValue: 'ms-Icon--ProHockey'}, {Name: "Rugby", SafeValue: 'ms-Icon--Rugby'}, {Name: "Tennis", SafeValue: 'ms-Icon--Tennis'}, {Name: "Arrivals", SafeValue: 'ms-Icon--Arrivals'}, {Name: "Design", SafeValue: 'ms-Icon--Design'}, {Name: "Website", SafeValue: 'ms-Icon--Website'}, {Name: "Drop", SafeValue: 'ms-Icon--Drop'}, {Name: "Snow", SafeValue: 'ms-Icon--Snow'}, {Name: "BusSolid", SafeValue: 'ms-Icon--BusSolid'}, {Name: "FerrySolid", SafeValue: 'ms-Icon--FerrySolid'}, {Name: "TrainSolid", SafeValue: 'ms-Icon--TrainSolid'}, {Name: "Heart", SafeValue: 'ms-Icon--Heart'}, {Name: "HeartFill", SafeValue: 'ms-Icon--HeartFill'}, {Name: "Ticket", SafeValue: 'ms-Icon--Ticket'}, {Name: "AzureLogo", SafeValue: 'ms-Icon--AzureLogo'}, {Name: "BingLogo", SafeValue: 'ms-Icon--BingLogo'}, {Name: "MSNLogo", SafeValue: 'ms-Icon--MSNLogo'}, {Name: "OutlookLogo", SafeValue: 'ms-Icon--OutlookLogo'}, {Name: "OfficeLogo", SafeValue: 'ms-Icon--OfficeLogo'}, {Name: "SkypeLogo", SafeValue: 'ms-Icon--SkypeLogo'}, {Name: "Door", SafeValue: 'ms-Icon--Door'}, {Name: "GiftCard", SafeValue: 'ms-Icon--GiftCard'}, {Name: "DoubleBookmark", SafeValue: 'ms-Icon--DoubleBookmark'}, {Name: "StatusErrorFull", SafeValue: 'ms-Icon--StatusErrorFull'}, {Name: "Certificate", SafeValue: 'ms-Icon--Certificate'}, {Name: "Photo2", SafeValue: 'ms-Icon--Photo2'}, {Name: "CloudDownload", SafeValue: 'ms-Icon--CloudDownload'}, {Name: "WindDirection", SafeValue: 'ms-Icon--WindDirection'}, {Name: "Family", SafeValue: 'ms-Icon--Family'}, {Name: "CSS", SafeValue: 'ms-Icon--CSS'}, {Name: "JS", SafeValue: 'ms-Icon--JS'}, {Name: "ReminderGroup", SafeValue: 'ms-Icon--ReminderGroup'}, {Name: "Section", SafeValue: 'ms-Icon--Section'}, {Name: "OneNoteLogo", SafeValue: 'ms-Icon--OneNoteLogo'}, {Name: "ToggleFilled", SafeValue: 'ms-Icon--ToggleFilled'}, {Name: "ToggleBorder", SafeValue: 'ms-Icon--ToggleBorder'}, {Name: "SliderThumb", SafeValue: 'ms-Icon--SliderThumb'}, {Name: "ToggleThumb", SafeValue: 'ms-Icon--ToggleThumb'}, {Name: "Documentation", SafeValue: 'ms-Icon--Documentation'}, {Name: "Badge", SafeValue: 'ms-Icon--Badge'}, {Name: "Giftbox", SafeValue: 'ms-Icon--Giftbox'}, {Name: "ExcelLogo", SafeValue: 'ms-Icon--ExcelLogo'}, {Name: "WordLogo", SafeValue: 'ms-Icon--WordLogo'}, {Name: "PowerPointLogo", SafeValue: 'ms-Icon--PowerPointLogo'}, {Name: "Cafe", SafeValue: 'ms-Icon--Cafe'}, {Name: "SpeedHigh", SafeValue: 'ms-Icon--SpeedHigh'}, {Name: "MusicNote", SafeValue: 'ms-Icon--MusicNote'}, {Name: "EdgeLogo", SafeValue: 'ms-Icon--EdgeLogo'}, {Name: "CompletedSolid", SafeValue: 'ms-Icon--CompletedSolid'}, {Name: "AlbumRemove", SafeValue: 'ms-Icon--AlbumRemove'}, {Name: "MessageFill", SafeValue: 'ms-Icon--MessageFill'}, {Name: "TabletSelected", SafeValue: 'ms-Icon--TabletSelected'}, {Name: "MobileSelected", SafeValue: 'ms-Icon--MobileSelected'}, {Name: "LaptopSelected", SafeValue: 'ms-Icon--LaptopSelected'}, {Name: "TVMonitorSelected", SafeValue: 'ms-Icon--TVMonitorSelected'}, {Name: "DeveloperTools", SafeValue: 'ms-Icon--DeveloperTools'}, {Name: "InsertTextBox", SafeValue: 'ms-Icon--InsertTextBox'}, {Name: "LowerBrightness", SafeValue: 'ms-Icon--LowerBrightness'}, {Name: "CloudUpload", SafeValue: 'ms-Icon--CloudUpload'}, {Name: "DateTime", SafeValue: 'ms-Icon--DateTime'}, {Name: "Tiles", SafeValue: 'ms-Icon--Tiles'}, {Name: "Org", SafeValue: 'ms-Icon--Org'}, {Name: "PartyLeader", SafeValue: 'ms-Icon--PartyLeader'}, {Name: "DRM", SafeValue: 'ms-Icon--DRM'}, {Name: "CloudAdd", SafeValue: 'ms-Icon--CloudAdd'}, {Name: "AppIconDefault", SafeValue: 'ms-Icon--AppIconDefault'}, {Name: "Photo2Add", SafeValue: 'ms-Icon--Photo2Add'}, {Name: "Photo2Remove", SafeValue: 'ms-Icon--Photo2Remove'}, {Name: "POI", SafeValue: 'ms-Icon--POI'}, {Name: "FacebookLogo", SafeValue: 'ms-Icon--FacebookLogo'}, {Name: "AddTo", SafeValue: 'ms-Icon--AddTo'}, {Name: "RadioBtnOn", SafeValue: 'ms-Icon--RadioBtnOn'}, {Name: "Embed", SafeValue: 'ms-Icon--Embed'}, {Name: "VideoSolid", SafeValue: 'ms-Icon--VideoSolid'}, {Name: "Teamwork", SafeValue: 'ms-Icon--Teamwork'}, {Name: "PeopleAdd", SafeValue: 'ms-Icon--PeopleAdd'}, {Name: "Glasses", SafeValue: 'ms-Icon--Glasses'}, {Name: "DateTime2", SafeValue: 'ms-Icon--DateTime2'}, {Name: "Shield", SafeValue: 'ms-Icon--Shield'}, {Name: "Header1", SafeValue: 'ms-Icon--Header1'}, {Name: "PageAdd", SafeValue: 'ms-Icon--PageAdd'}, {Name: "NumberedList", SafeValue: 'ms-Icon--NumberedList'}, {Name: "PowerBILogo", SafeValue: 'ms-Icon--PowerBILogo'}, {Name: "Product", SafeValue: 'ms-Icon--Product'}, {Name: "Blocked2", SafeValue: 'ms-Icon--Blocked2'}, {Name: "FangBody", SafeValue: 'ms-Icon--FangBody'}, {Name: "Glimmer", SafeValue: 'ms-Icon--Glimmer'}, {Name: "ChatInviteFriend", SafeValue: 'ms-Icon--ChatInviteFriend'}, {Name: "SharepointLogo", SafeValue: 'ms-Icon--SharepointLogo'}, {Name: "YammerLogo", SafeValue: 'ms-Icon--YammerLogo'}, {Name: "ReturnToSession", SafeValue: 'ms-Icon--ReturnToSession'}, {Name: "OpenFolderHorizontal", SafeValue: 'ms-Icon--OpenFolderHorizontal'}, {Name: "SwayLogo", SafeValue: 'ms-Icon--SwayLogo'}, {Name: "OutOfOffice", SafeValue: 'ms-Icon--OutOfOffice'}, {Name: "Trophy", SafeValue: 'ms-Icon--Trophy'}, {Name: "ReopenPages", SafeValue: 'ms-Icon--ReopenPages'}, {Name: "AADLogo", SafeValue: 'ms-Icon--AADLogo'}, {Name: "AccessLogo", SafeValue: 'ms-Icon--AccessLogo'}, {Name: "AdminALogo", SafeValue: 'ms-Icon--AdminALogo'}, {Name: "AdminCLogo", SafeValue: 'ms-Icon--AdminCLogo'}, {Name: "AdminDLogo", SafeValue: 'ms-Icon--AdminDLogo'}, {Name: "AdminELogo", SafeValue: 'ms-Icon--AdminELogo'}, {Name: "AdminLLogo", SafeValue: 'ms-Icon--AdminLLogo'}, {Name: "AdminMLogo", SafeValue: 'ms-Icon--AdminMLogo'}, {Name: "AdminOLogo", SafeValue: 'ms-Icon--AdminOLogo'}, {Name: "AdminPLogo", SafeValue: 'ms-Icon--AdminPLogo'}, {Name: "AdminSLogo", SafeValue: 'ms-Icon--AdminSLogo'}, {Name: "AdminYLogo", SafeValue: 'ms-Icon--AdminYLogo'}, {Name: "AlchemyLogo", SafeValue: 'ms-Icon--AlchemyLogo'}, {Name: "BoxLogo", SafeValue: 'ms-Icon--BoxLogo'}, {Name: "DelveLogo", SafeValue: 'ms-Icon--DelveLogo'}, {Name: "DropboxLogo", SafeValue: 'ms-Icon--DropboxLogo'}, {Name: "ExchangeLogo", SafeValue: 'ms-Icon--ExchangeLogo'}, {Name: "LyncLogo", SafeValue: 'ms-Icon--LyncLogo'}, {Name: "OfficeVideoLogo", SafeValue: 'ms-Icon--OfficeVideoLogo'}, {Name: "ParatureLogo", SafeValue: 'ms-Icon--ParatureLogo'}, {Name: "SocialListeningLogo", SafeValue: 'ms-Icon--SocialListeningLogo'}, {Name: "VisioLogo", SafeValue: 'ms-Icon--VisioLogo'}, {Name: "Balloons", SafeValue: 'ms-Icon--Balloons'}, {Name: "Cat", SafeValue: 'ms-Icon--Cat'}, {Name: "MailAlert", SafeValue: 'ms-Icon--MailAlert'}, {Name: "MailCheck", SafeValue: 'ms-Icon--MailCheck'}, {Name: "MailLowImportance", SafeValue: 'ms-Icon--MailLowImportance'}, {Name: "MailPause", SafeValue: 'ms-Icon--MailPause'}, {Name: "MailRepeat", SafeValue: 'ms-Icon--MailRepeat'}, {Name: "SecurityGroup", SafeValue: 'ms-Icon--SecurityGroup'}, {Name: "VoicemailForward", SafeValue: 'ms-Icon--VoicemailForward'}, {Name: "VoicemailReply", SafeValue: 'ms-Icon--VoicemailReply'}, {Name: "Waffle", SafeValue: 'ms-Icon--Waffle'}, {Name: "RemoveEvent", SafeValue: 'ms-Icon--RemoveEvent'}, {Name: "EventInfo", SafeValue: 'ms-Icon--EventInfo'}, {Name: "ForwardEvent", SafeValue: 'ms-Icon--ForwardEvent'}, {Name: "WipePhone", SafeValue: 'ms-Icon--WipePhone'}, {Name: "AddOnlineMeeting", SafeValue: 'ms-Icon--AddOnlineMeeting'}, {Name: "JoinOnlineMeeting", SafeValue: 'ms-Icon--JoinOnlineMeeting'}, {Name: "RemoveLink", SafeValue: 'ms-Icon--RemoveLink'}, {Name: "PeopleBlock", SafeValue: 'ms-Icon--PeopleBlock'}, {Name: "PeopleRepeat", SafeValue: 'ms-Icon--PeopleRepeat'}, {Name: "PeopleAlert", SafeValue: 'ms-Icon--PeopleAlert'}, {Name: "PeoplePause", SafeValue: 'ms-Icon--PeoplePause'}, {Name: "TransferCall", SafeValue: 'ms-Icon--TransferCall'}, {Name: "AddPhone", SafeValue: 'ms-Icon--AddPhone'}, {Name: "UnknownCall", SafeValue: 'ms-Icon--UnknownCall'}, {Name: "NoteReply", SafeValue: 'ms-Icon--NoteReply'}, {Name: "NoteForward", SafeValue: 'ms-Icon--NoteForward'}, {Name: "NotePinned", SafeValue: 'ms-Icon--NotePinned'}, {Name: "RemoveOccurrence", SafeValue: 'ms-Icon--RemoveOccurrence'}, {Name: "Timeline", SafeValue: 'ms-Icon--Timeline'}, {Name: "EditNote", SafeValue: 'ms-Icon--EditNote'}, {Name: "CircleHalfFull", SafeValue: 'ms-Icon--CircleHalfFull'}, {Name: "Room", SafeValue: 'ms-Icon--Room'}, {Name: "Unsubscribe", SafeValue: 'ms-Icon--Unsubscribe'}, {Name: "Subscribe", SafeValue: 'ms-Icon--Subscribe'}, {Name: "RecurringTask", SafeValue: 'ms-Icon--RecurringTask'}, {Name: "TaskManager", SafeValue: 'ms-Icon--TaskManager'}, {Name: "Combine", SafeValue: 'ms-Icon--Combine'}, {Name: "Split", SafeValue: 'ms-Icon--Split'}, {Name: "DoubleChevronUp", SafeValue: 'ms-Icon--DoubleChevronUp'}, {Name: "DoubleChevronLeft", SafeValue: 'ms-Icon--DoubleChevronLeft'}, {Name: "DoubleChevronRight", SafeValue: 'ms-Icon--DoubleChevronRight'}, {Name: "Ascending", SafeValue: 'ms-Icon--Ascending'}, {Name: "Descending", SafeValue: 'ms-Icon--Descending'}, {Name: "TextBox", SafeValue: 'ms-Icon--TextBox'}, {Name: "TextField", SafeValue: 'ms-Icon--TextField'}, {Name: "NumberField", SafeValue: 'ms-Icon--NumberField'}, {Name: "Dropdown", SafeValue: 'ms-Icon--Dropdown'}, {Name: "BookingsLogo", SafeValue: 'ms-Icon--BookingsLogo'}, {Name: "ClassNotebookLogo", SafeValue: 'ms-Icon--ClassNotebookLogo'}, {Name: "CollabsDBLogo", SafeValue: 'ms-Icon--CollabsDBLogo'}, {Name: "DelveAnalyticsLogo", SafeValue: 'ms-Icon--DelveAnalyticsLogo'}, {Name: "DocsLogo", SafeValue: 'ms-Icon--DocsLogo'}, {Name: "DynamicsCRMLogo", SafeValue: 'ms-Icon--DynamicsCRMLogo'}, {Name: "DynamicSMBLogo", SafeValue: 'ms-Icon--DynamicSMBLogo'}, {Name: "OfficeAssistantLogo", SafeValue: 'ms-Icon--OfficeAssistantLogo'}, {Name: "OfficeStoreLogo", SafeValue: 'ms-Icon--OfficeStoreLogo'}, {Name: "OneNoteEduLogo", SafeValue: 'ms-Icon--OneNoteEduLogo'}, {Name: "Planner", SafeValue: 'ms-Icon--Planner'}, {Name: "PowerApps", SafeValue: 'ms-Icon--PowerApps'}, {Name: "Suitcase", SafeValue: 'ms-Icon--Suitcase'}, {Name: "ProjectLogo", SafeValue: 'ms-Icon--ProjectLogo'}, {Name: "CaretLeft8", SafeValue: 'ms-Icon--CaretLeft8'}, {Name: "CaretRight8", SafeValue: 'ms-Icon--CaretRight8'}, {Name: "CaretUp8", SafeValue: 'ms-Icon--CaretUp8'}, {Name: "CaretDown8", SafeValue: 'ms-Icon--CaretDown8'}, {Name: "CaretLeftSolid8", SafeValue: 'ms-Icon--CaretLeftSolid8'}, {Name: "CaretRightSolid8", SafeValue: 'ms-Icon--CaretRightSolid8'}, {Name: "CaretUpSolid8", SafeValue: 'ms-Icon--CaretUpSolid8'}, {Name: "CaretDownSolid8", SafeValue: 'ms-Icon--CaretDownSolid8'}, {Name: "ClearFormatting", SafeValue: 'ms-Icon--ClearFormatting'}, {Name: "Superscript", SafeValue: 'ms-Icon--Superscript'}, {Name: "Subscript", SafeValue: 'ms-Icon--Subscript'}, {Name: "Strikethrough", SafeValue: 'ms-Icon--Strikethrough'}, {Name: "SingleBookmark", SafeValue: 'ms-Icon--SingleBookmark'}, {Name: "DoubleChevronDown", SafeValue: 'ms-Icon--DoubleChevronDown'}, {Name: "ReplyAll", SafeValue: 'ms-Icon--ReplyAll'}, {Name: "GoogleDriveLogo", SafeValue: 'ms-Icon--GoogleDriveLogo'}, {Name: "Questionnaire", SafeValue: 'ms-Icon--Questionnaire'}, {Name: "AddGroup", SafeValue: 'ms-Icon--AddGroup'}, {Name: "TemporaryUser", SafeValue: 'ms-Icon--TemporaryUser'}, {Name: "GroupedDescending", SafeValue: 'ms-Icon--GroupedDescending'}, {Name: "GroupedAscending", SafeValue: 'ms-Icon--GroupedAscending'}, {Name: "SortUp", SafeValue: 'ms-Icon--SortUp'}, {Name: "SortDown", SafeValue: 'ms-Icon--SortDown'}, {Name: "AwayStatus", SafeValue: 'ms-Icon--AwayStatus'}, {Name: "SyncToPC", SafeValue: 'ms-Icon--SyncToPC'}, {Name: "AustralianRules", SafeValue: 'ms-Icon--AustralianRules'}, {Name: "DoubleChevronUp12", SafeValue: 'ms-Icon--DoubleChevronUp12'}, {Name: "DoubleChevronDown12", SafeValue: 'ms-Icon--DoubleChevronDown12'}, {Name: "DoubleChevronLeft12", SafeValue: 'ms-Icon--DoubleChevronLeft12'}, {Name: "DoubleChevronRight12", SafeValue: 'ms-Icon--DoubleChevronRight12'}, {Name: "CalendarAgenda", SafeValue: 'ms-Icon--CalendarAgenda'}, {Name: "AddEvent", SafeValue: 'ms-Icon--AddEvent'}, {Name: "AssetLibrary", SafeValue: 'ms-Icon--AssetLibrary'}, {Name: "DataConnectionLibrary", SafeValue: 'ms-Icon--DataConnectionLibrary'}, {Name: "DocLibrary", SafeValue: 'ms-Icon--DocLibrary'}, {Name: "FormLibrary", SafeValue: 'ms-Icon--FormLibrary'}, {Name: "ReportLibrary", SafeValue: 'ms-Icon--ReportLibrary'}, {Name: "ContactCard", SafeValue: 'ms-Icon--ContactCard'}, {Name: "CustomList", SafeValue: 'ms-Icon--CustomList'}, {Name: "IssueTracking", SafeValue: 'ms-Icon--IssueTracking'}, {Name: "PictureLibrary", SafeValue: 'ms-Icon--PictureLibrary'}, {Name: "AppForOfficeLogo", SafeValue: 'ms-Icon--AppForOfficeLogo'}, {Name: "OfflineOneDriveParachute", SafeValue: 'ms-Icon--OfflineOneDriveParachute'}, {Name: "OfflineOneDriveParachuteDisabled", SafeValue: 'ms-Icon--OfflineOneDriveParachuteDisabled'}, {Name: "LargeGrid", SafeValue: 'ms-Icon--LargeGrid'}, {Name: "TriangleSolidUp12", SafeValue: 'ms-Icon--TriangleSolidUp12'}, {Name: "TriangleSolidDown12", SafeValue: 'ms-Icon--TriangleSolidDown12'}, {Name: "TriangleSolidLeft12", SafeValue: 'ms-Icon--TriangleSolidLeft12'}, {Name: "TriangleSolidRight12", SafeValue: 'ms-Icon--TriangleSolidRight12'}, {Name: "TriangleUp12", SafeValue: 'ms-Icon--TriangleUp12'}, {Name: "TriangleDown12", SafeValue: 'ms-Icon--TriangleDown12'}, {Name: "TriangleLeft12", SafeValue: 'ms-Icon--TriangleLeft12'}, {Name: "TriangleRight12", SafeValue: 'ms-Icon--TriangleRight12'}, {Name: "ArrowUpRight8", SafeValue: 'ms-Icon--ArrowUpRight8'}, {Name: "ArrowDownRight8", SafeValue: 'ms-Icon--ArrowDownRight8'}, {Name: "DocumentSet", SafeValue: 'ms-Icon--DocumentSet'}, {Name: "DelveAnalytics", SafeValue: 'ms-Icon--DelveAnalytics'}, {Name: "OneDriveAdd", SafeValue: 'ms-Icon--OneDriveAdd'}, {Name: "Header2", SafeValue: 'ms-Icon--Header2'}, {Name: "Header3", SafeValue: 'ms-Icon--Header3'}, {Name: "Header4", SafeValue: 'ms-Icon--Header4'}, {Name: "MarketDown", SafeValue: 'ms-Icon--MarketDown'}, {Name: "CalendarWorkWeek", SafeValue: 'ms-Icon--CalendarWorkWeek'}, {Name: "SidePanel", SafeValue: 'ms-Icon--SidePanel'}, {Name: "GlobeFavorite", SafeValue: 'ms-Icon--GlobeFavorite'}, {Name: "CaretTopLeftSolid8", SafeValue: 'ms-Icon--CaretTopLeftSolid8'}, {Name: "CaretTopRightSolid8", SafeValue: 'ms-Icon--CaretTopRightSolid8'}, {Name: "ViewAll2", SafeValue: 'ms-Icon--ViewAll2'}, {Name: "DocumentReply", SafeValue: 'ms-Icon--DocumentReply'}, {Name: "PlayerSettings", SafeValue: 'ms-Icon--PlayerSettings'}, {Name: "ReceiptForward", SafeValue: 'ms-Icon--ReceiptForward'}, {Name: "ReceiptReply", SafeValue: 'ms-Icon--ReceiptReply'}, {Name: "ReceiptCheck", SafeValue: 'ms-Icon--ReceiptCheck'}, {Name: "Fax", SafeValue: 'ms-Icon--Fax'}, {Name: "RecurringEvent", SafeValue: 'ms-Icon--RecurringEvent'}, {Name: "ReplyAlt", SafeValue: 'ms-Icon--ReplyAlt'}, {Name: "ReplyAllAlt", SafeValue: 'ms-Icon--ReplyAllAlt'}, {Name: "EditStyle", SafeValue: 'ms-Icon--EditStyle'}, {Name: "EditMail", SafeValue: 'ms-Icon--EditMail'}, {Name: "Lifesaver", SafeValue: 'ms-Icon--Lifesaver'}, {Name: "LifesaverLock", SafeValue: 'ms-Icon--LifesaverLock'}, {Name: "InboxCheck", SafeValue: 'ms-Icon--InboxCheck'}, {Name: "FolderSearch", SafeValue: 'ms-Icon--FolderSearch'}, {Name: "CollapseMenu", SafeValue: 'ms-Icon--CollapseMenu'}, {Name: "ExpandMenu", SafeValue: 'ms-Icon--ExpandMenu'}, {Name: "Boards", SafeValue: 'ms-Icon--Boards'}, {Name: "SunAdd", SafeValue: 'ms-Icon--SunAdd'}, {Name: "SunQuestionMark", SafeValue: 'ms-Icon--SunQuestionMark'}, {Name: "LandscapeOrientation", SafeValue: 'ms-Icon--LandscapeOrientation'}, {Name: "DocumentSearch", SafeValue: 'ms-Icon--DocumentSearch'}, {Name: "PublicCalendar", SafeValue: 'ms-Icon--PublicCalendar'}, {Name: "PublicContactCard", SafeValue: 'ms-Icon--PublicContactCard'}, {Name: "PublicEmail", SafeValue: 'ms-Icon--PublicEmail'}, {Name: "PublicFolder", SafeValue: 'ms-Icon--PublicFolder'}, {Name: "WordDocument", SafeValue: 'ms-Icon--WordDocument'}, {Name: "PowerPointDocument", SafeValue: 'ms-Icon--PowerPointDocument'}, {Name: "ExcelDocument", SafeValue: 'ms-Icon--ExcelDocument'}, {Name: "GroupedList", SafeValue: 'ms-Icon--GroupedList'}, {Name: "ClassroomLogo", SafeValue: 'ms-Icon--ClassroomLogo'}, {Name: "Sections", SafeValue: 'ms-Icon--Sections'}, {Name: "EditPhoto", SafeValue: 'ms-Icon--EditPhoto'}, {Name: "Starburst", SafeValue: 'ms-Icon--Starburst'}, {Name: "ShareiOS", SafeValue: 'ms-Icon--ShareiOS'}, {Name: "AirTickets", SafeValue: 'ms-Icon--AirTickets'}, {Name: "PencilReply", SafeValue: 'ms-Icon--PencilReply'}, {Name: "Tiles2", SafeValue: 'ms-Icon--Tiles2'}, {Name: "SkypeCircleCheck", SafeValue: 'ms-Icon--SkypeCircleCheck'}, {Name: "SkypeCircleClock", SafeValue: 'ms-Icon--SkypeCircleClock'}, {Name: "SkypeCircleMinus", SafeValue: 'ms-Icon--SkypeCircleMinus'}, {Name: "SkypeCheck", SafeValue: 'ms-Icon--SkypeCheck'}, {Name: "SkypeClock", SafeValue: 'ms-Icon--SkypeClock'}, {Name: "SkypeMinus", SafeValue: 'ms-Icon--SkypeMinus'}, {Name: "SkypeMessage", SafeValue: 'ms-Icon--SkypeMessage'}, {Name: "ClosedCaption", SafeValue: 'ms-Icon--ClosedCaption'}, {Name: "ATPLogo", SafeValue: 'ms-Icon--ATPLogo'}, {Name: "OfficeFormLogo", SafeValue: 'ms-Icon--OfficeFormLogo'}, {Name: "RecycleBin", SafeValue: 'ms-Icon--RecycleBin'}, {Name: "EmptyRecycleBin", SafeValue: 'ms-Icon--EmptyRecycleBin'}, {Name: "Hide2", SafeValue: 'ms-Icon--Hide2'}, {Name: "iOSAppStoreLogo", SafeValue: 'ms-Icon--iOSAppStoreLogo'}, {Name: "AndroidLogo", SafeValue: 'ms-Icon--AndroidLogo'}, {Name: "Breadcrumb", SafeValue: 'ms-Icon--Breadcrumb'}, {Name: "ClearFilter", SafeValue: 'ms-Icon--ClearFilter'}, {Name: "Flow", SafeValue: 'ms-Icon--Flow'}, {Name: "PowerAppsLogo", SafeValue: 'ms-Icon--PowerAppsLogo'}, {Name: "PowerApps2Logo", SafeValue: 'ms-Icon--PowerApps2Logo'} ]; private latestValidateValue: string; private async: Async; private delayedValidate: (value: string) => void; private _key: string; /** * @function * Constructor */ constructor(props: IPropertyFieldIconPickerHostProps) { super(props); //Bind the current object to the external called onSelectDate method this.onOpenDialog = this.onOpenDialog.bind(this); this.toggleHover = this.toggleHover.bind(this); this.toggleHoverLeave = this.toggleHoverLeave.bind(this); this.onClickFont = this.onClickFont.bind(this); this.onFontDropdownChanged = this.onFontDropdownChanged.bind(this); this.mouseEnterDropDown = this.mouseEnterDropDown.bind(this); this.mouseLeaveDropDown = this.mouseLeaveDropDown.bind(this); this._key = GuidHelper.getGuid(); if (this.props.orderAlphabetical === true) this.orderAlphabetical(); //Init the state this.state = { isOpen: false, isHoverDropdown: false, errorMessage: '' }; this.async = new Async(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime); //Inits the default value if (props.initialValue != null && props.initialValue != '') { for (var i = 0; i < this.fonts.length; i++) { var font = this.fonts[i]; if (font.SafeValue == props.initialValue) { this.state.selectedFont = font.Name; this.state.safeSelectedFont = font.SafeValue; } } } } /** * @function * Orders the font list */ private orderAlphabetical(): void { this.fonts.sort(this.compare); } private compare(a: ISafeFont, b: ISafeFont) { if (a.Name < b.Name) return -1; if (a.Name > b.Name) return 1; return 0; } /** * @function * Function to refresh the Web Part properties */ private changeSelectedFont(newValue: string): void { this.delayedValidate(newValue); } /** * @function * Validates the new custom field value */ private validate(value: string): void { if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) { this.notifyAfterValidate(this.props.initialValue, value); return; } if (this.latestValidateValue === value) return; this.latestValidateValue = value; var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || ''); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this.notifyAfterValidate(this.props.initialValue, value); this.state.errorMessage = result; this.setState(this.state); } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this.notifyAfterValidate(this.props.initialValue, value); this.state.errorMessage = errorMessage; this.setState(this.state); }); } } else { this.notifyAfterValidate(this.props.initialValue, value); } } /** * @function * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: string, newValue: string) { if (this.props.onPropertyChange && newValue != null) { this.props.properties[this.props.targetProperty] = newValue; this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue); if (!this.props.disableReactivePropertyChanges && this.props.render != null) this.props.render(); } } /** * @function * Called when the component will unmount */ public componentWillUnmount() { this.async.dispose(); } /** * @function * Function to open the dialog */ private onOpenDialog(): void { if (this.props.disabled === true) return; this.state.isOpen = !this.state.isOpen; this.setState(this.state); } /** * @function * Mouse is hover a font */ private toggleHover(element?: any) { var hoverFont: string = element.currentTarget.textContent; this.state.hoverFont = hoverFont; this.setState(this.state); } /** * @function * Mouse is leaving a font */ private toggleHoverLeave(element?: any) { this.state.hoverFont = ''; this.setState(this.state); } /** * @function * Mouse is hover the fontpicker */ private mouseEnterDropDown(element?: any) { this.state.isHoverDropdown = true; this.setState(this.state); } /** * @function * Mouse is leaving the fontpicker */ private mouseLeaveDropDown(element?: any) { this.state.isHoverDropdown = false; this.setState(this.state); } /** * @function * User clicked on a font */ private onClickFont(element?: any) { var clickedFont: string = element.currentTarget.textContent; this.state.selectedFont = clickedFont; this.state.safeSelectedFont = this.getSafeFont(clickedFont); this.onOpenDialog(); this.changeSelectedFont(this.state.safeSelectedFont); this.setState(this.state); } /** * @function * Gets a safe font value from a font name */ private getSafeFont(fontName: string): string { for (var i = 0; i < this.fonts.length; i++) { var font = this.fonts[i]; if (font.Name === fontName) return font.SafeValue; } return ''; } /** * @function * The font dropdown selected value changed (used when the previewFont property equals false) */ private onFontDropdownChanged(option: IDropdownOption, index?: number): void { this.changeSelectedFont(option.key as string); } /** * @function * Renders the controls */ public render(): JSX.Element { if (this.props.preview === false) { //If the user don't want to use the preview font picker, //we're building a classical drop down picker var dropDownOptions: IDropdownOption[] = []; var selectedKey: string; this.fonts.map((font: ISafeFont) => { var isSelected: boolean = false; isSelected = true; selectedKey = font.SafeValue; dropDownOptions.push( { key: font.SafeValue, text: font.Name, isSelected: isSelected } ); }); return ( <div> <Dropdown label={this.props.label} options={dropDownOptions} selectedKey={selectedKey} onChanged={this.onFontDropdownChanged} disabled={this.props.disabled} /> { this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p> </span> </div> : ''} </div> ); } else { //User wants to use the preview font picker, so just build it var fontSelect = { fontSize: '16px', width: '100%', position: 'relative', display: 'inline-block', zoom: 1 }; var dropdownColor = '1px solid #c8c8c8'; if (this.props.disabled === true) dropdownColor = '1px solid #f4f4f4'; else if (this.state.isOpen === true) dropdownColor = '1px solid #3091DE'; else if (this.state.isHoverDropdown === true) dropdownColor = '1px solid #767676'; var fontSelectA = { backgroundColor: this.props.disabled === true ? '#f4f4f4' : '#fff', borderRadius : '0px', backgroundClip : 'padding-box', border: dropdownColor, display: 'block', overflow: 'hidden', whiteSpace: 'nowrap', position: 'relative', height: '26px', lineHeight: '26px', padding: '0 0 0 8px', color: this.props.disabled === true ? '#a6a6a6' : '#444', textDecoration: 'none', cursor: this.props.disabled === true ? 'default' : 'pointer' }; var fontSelectASpan = { marginRight: '26px', display: 'block', overflow: 'hidden', whiteSpace: 'nowrap', lineHeight: '1.8', textOverflow: 'ellipsis', cursor: this.props.disabled === true ? 'default' : 'pointer', //fontFamily: this.state.safeSelectedFont != null && this.state.safeSelectedFont != '' ? this.state.safeSelectedFont : 'Arial', //fontSize: this.state.safeSelectedFont, fontWeight: 400 }; var fontSelectADiv = { borderRadius : '0 0px 0px 0', backgroundClip : 'padding-box', border: '0px', position: 'absolute', right: '0', top: '0', display: 'block', height: '100%', width: '22px' }; var fontSelectADivB = { display: 'block', width: '100%', height: '100%', cursor: this.props.disabled === true ? 'default' : 'pointer', marginTop: '2px' }; var fsDrop = { background: '#fff', border: '1px solid #aaa', borderTop: '0', position: 'absolute', top: '29px', left: '0', width: 'calc(100% - 2px)', //boxShadow: '0 4px 5px rgba(0,0,0,.15)', zIndex: 999, display: this.state.isOpen ? 'block' : 'none' }; var fsResults = { margin: '0 4px 4px 0', maxHeight: '190px', width: 'calc(100% - 4px)', padding: '0 0 0 4px', position: 'relative', overflowX: 'hidden', overflowY: 'auto' }; var carret: string = this.state.isOpen ? 'ms-Icon ms-Icon--ChevronUp' : 'ms-Icon ms-Icon--ChevronDown'; //Renders content return ( <div style={{ marginBottom: '8px'}}> <Label>{this.props.label}</Label> <div style={fontSelect}> <a style={fontSelectA} onClick={this.onOpenDialog} onMouseEnter={this.mouseEnterDropDown} onMouseLeave={this.mouseLeaveDropDown} role="menuitem"> <span style={fontSelectASpan}> <i className={'ms-Icon ms-Icon--' + this.state.selectedFont} aria-hidden="true" style={{marginRight:'10px'}}></i> {this.state.selectedFont} </span> <div style={fontSelectADiv}> <i style={fontSelectADivB} className={carret}></i> </div> </a> <div style={fsDrop}> <ul style={fsResults}> {this.fonts.map((font: ISafeFont, index: number) => { var backgroundColor: string = 'transparent'; if (this.state.selectedFont === font.Name) backgroundColor = '#c7e0f4'; else if (this.state.hoverFont === font.Name) backgroundColor = '#eaeaea'; var innerStyle = { lineHeight: '80%', padding: '7px 7px 8px', margin: '0', listStyle: 'none', fontSize: '16px', backgroundColor: backgroundColor, cursor: 'pointer' }; return ( <li value={font.Name} role="menuitem" key={this._key + '-iconpicker-' + index} onMouseEnter={this.toggleHover} onClick={this.onClickFont} onMouseLeave={this.toggleHoverLeave} style={innerStyle}> <i className={'ms-Icon ' + font.SafeValue} aria-hidden="true" style={{fontSize: '24px', marginRight:'10px'}}></i> {font.Name} </li> ); }) } </ul> </div> </div> { this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p> </span> </div> : ''} </div> ); } } }
the_stack
import "../../../node_modules/monaco-editor/esm/vs/language/typescript/monaco.contribution.js"; import "../../../node_modules/monaco-editor/esm/vs/basic-languages/typescript/typescript.contribution.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickAccess/standaloneCommandsQuickAccess.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/browser/controller/coreCommands.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/bracketMatching/bracketMatching.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/caretOperations/caretOperations.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/clipboard/clipboard.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/codeAction/codeActionContributions.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/comment/comment.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/contextmenu/contextmenu.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/cursorUndo/cursorUndo.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/dnd/dnd.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/find/findController.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/folding/folding.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/fontZoom/fontZoom.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/format/formatActions.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/link/goToDefinitionAtPosition.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/hover/hover.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/indentation/indentation.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/inlayHints/inlayHintsController.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/linesOperations/linesOperations.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/links/links.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/multicursor/multicursor.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/parameterHints/parameterHints.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/rename/rename.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/smartSelect/smartSelect.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/suggest/suggestController.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/tokenization/tokenization.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/toggleTabFocusMode/toggleTabFocusMode.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/unusualLineTerminators/unusualLineTerminators.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/viewportSemanticTokens/viewportSemanticTokens.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/wordHighlighter/wordHighlighter.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/wordOperations/wordOperations.js"; import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/wordPartOperations/wordPartOperations.js"; // Load up these strings even in VSCode, even if they are not used // in order to get them translated import "../../../node_modules/monaco-editor/esm/vs/editor/common/standaloneStrings.js"; import "../../../node_modules/monaco-editor/esm/vs/base/browser/ui/codicons/codiconStyles.js"; // The codicons are defined here and must be loaded // import 'monaco-editor/esm/vs/language/css/monaco.contribution'; // import 'monaco-editor/esm/vs/language/json/monaco.contribution'; // import 'monaco-editor/esm/vs/language/html/monaco.contribution'; // import 'monaco-editor/esm/vs/basic-languages/monaco.contribution.js'; // export * from 'monaco-editor/esm/vs/editor/edcore.main'; // import "../../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/inspectTokens/inspectTokens.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickAccess/standaloneGotoLineQuickAccess.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/quickAccess/standaloneGotoSymbolQuickAccess.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/referenceSearch/standaloneReferenceSearch.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/standalone/browser/toggleHighContrast/toggleHighContrast.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/browser/widget/codeEditorWidget.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/browser/widget/diffEditorWidget.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/browser/widget/diffNavigator.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/anchorSelect/anchorSelect.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/caretOperations/transpose.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/codelens/codelensController.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/colorPicker/colorContributions.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/documentSymbols/documentSymbols.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/inlineCompletions/ghostTextController.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoSymbol/goToCommands.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/gotoError/gotoError.js"; // import "../../../node_modules/monaco-editor/esm/vs/editor/contrib/inPlaceReplace/inPlaceReplace.js"; import { editor as Editor, languages, Uri } from "../../../node_modules/monaco-editor/esm/vs/editor/editor.api.js"; import type { Environment } from "../../../node_modules/monaco-editor/esm/vs/editor/editor.api"; import GithubLight from "../util/github-light"; import GithubDark from "../util/github-dark"; import WebWorker, { WorkerConfig } from "../util/WebWorker"; import { mediaTheme, themeGet } from "../scripts/theme"; import { parseSearchQuery, parseInput } from "../util/parse-query"; import TS_WORKER_FACTORY_URL from "worker:../workers/ts-worker-factory.ts"; import TYPESCRIPT_WORKER_URL from "worker:../workers/typescript.ts"; import EDITOR_WORKER_URL from "worker:../workers/editor.ts"; import { getRequest } from "../util/cache.js"; export const TS_WORKER = new WebWorker(TYPESCRIPT_WORKER_URL, { name: "ts-worker" }); // Since packaging is done by you, you need // to instruct the editor how you named the // bundles that contain the web workers. (window as any).MonacoEnvironment = { getWorker: function (_, label) { if (label === "typescript" || label === "javascript") { return TS_WORKER; } return (() => { let EditorWorker = new Worker(EDITOR_WORKER_URL, { name: "editor-worker" }); EditorWorker?.terminate(); return EditorWorker; })(); }, } as Environment; export { languages, Editor, Uri }; export const build = (oldShareURL: URL) => { const initialValue = parseSearchQuery(oldShareURL) || [ '// Click Run for the Bundled, Minified & Gzipped package size', 'export * from "@okikio/animate";', ].join("\n"); let inputEl = document.querySelector(".app#input #editor") as HTMLElement; let outputEl = document.querySelector(".app#output #editor") as HTMLElement; inputEl.textContent = ""; outputEl.textContent = ""; let inputEditor: Editor.IStandaloneCodeEditor; let outputEditor: Editor.IStandaloneCodeEditor; // @ts-ignore Editor.defineTheme("dark", GithubDark); // @ts-ignore Editor.defineTheme("light", GithubLight); // Basically android and monaco is pretty bad, this makes it less bad // See https://github.com/microsoft/pxt/pull/7099 for this, and the long // read is in https://github.com/microsoft/monaco-editor/issues/563 const isAndroid = navigator && /android/i.test(navigator.userAgent) let editorOpts: Editor.IStandaloneEditorConstructionOptions = { // @ts-ignore bracketPairColorization: { enabled: true, }, parameterHints: { enabled: true, }, model: Editor.createModel( initialValue, "typescript", Uri.parse("file://input.ts") ), quickSuggestions: { other: !isAndroid, comments: !isAndroid, strings: !isAndroid, }, acceptSuggestionOnCommitCharacter: !isAndroid, acceptSuggestionOnEnter: !isAndroid ? "on" : "off", // accessibilitySupport: !isAndroid ? "on" : "off", minimap: { enabled: false, }, padding: { bottom: 2.5, top: 2.5, }, scrollbar: { // Subtle shadows to the left & top. Defaults to true. useShadows: false, vertical: "auto", }, lightbulb: { enabled: true }, wordWrap: "on", roundedSelection: true, scrollBeyondLastLine: true, smoothScrolling: true, theme: (() => { let theme = themeGet(); return theme == "system" ? mediaTheme() : theme; })(), automaticLayout: true, language: "typescript", lineNumbers: "on", }; inputEditor = Editor.create(inputEl, editorOpts); outputEditor = Editor.create(outputEl, { ...editorOpts, model: Editor.createModel( `// Output`, "typescript", Uri.parse("file://output.ts") ), }); document.addEventListener("theme-change", () => { let theme = themeGet(); Editor.setTheme(theme == "system" ? mediaTheme() : theme); }); languages.typescript.typescriptDefaults.setWorkerOptions({ customWorkerPath: new URL(TS_WORKER_FACTORY_URL, document.location.origin).toString() }); languages.typescript.typescriptDefaults.setDiagnosticsOptions({ ...languages.typescript.typescriptDefaults.getDiagnosticsOptions(), // noSemanticValidation: false, noSemanticValidation: true, noSyntaxValidation: false, noSuggestionDiagnostics: false, // This is when tslib is not found diagnosticCodesToIgnore: [2354], }); // Compiler options languages.typescript.typescriptDefaults.setCompilerOptions({ moduleResolution: languages.typescript.ModuleResolutionKind.NodeJs, target: languages.typescript.ScriptTarget.Latest, module: languages.typescript.ModuleKind.ES2015, noEmit: true, lib: ["es2021", "dom", "dom.iterable", "webworker", "esnext", "node"], exclude: ["node_modules"], resolveJsonModule: true, allowNonTsExtensions: true, esModuleInterop: true, noResolve: true, allowSyntheticDefaultImports: true, isolatedModules: true, experimentalDecorators: true, emitDecoratorMetadata: true, jsx: languages.typescript.JsxEmit.React, }); // @ts-ignore languages.typescript.typescriptDefaults.setInlayHintsOptions({ includeInlayParameterNameHints: "literals", includeInlayParameterNameHintsWhenArgumentMatchesName: true }); languages.typescript.typescriptDefaults.setEagerModelSync(true); languages.typescript.typescriptDefaults.addExtraLib( "declare module 'https://*' {\n\texport * from \"https://cdn.esm.sh/*\";\n}", `file://node_modules/@types/https.d.ts` ); // (?:(?:import|export|require)(?:\s?(.*)?\s?)(?:from\s+|\((?:\s+)?)["']([^"']+)["'])\)? const IMPORTS_REXPORTS_REQUIRE_REGEX = /(?:(?:import|export|require)(?:.)*?(?:from\s+|\((?:\s+)?)["']([^"']+)["'])\)?/g; const FetchCache = new Set(); languages.registerHoverProvider("typescript", { provideHover(model, position) { let content = model.getLineContent(position.lineNumber); if (typeof content != "string" || content.length == 0) return; let matches = Array.from(content.matchAll(IMPORTS_REXPORTS_REQUIRE_REGEX)) ?? []; if (matches.length <= 0) return; let matchArr = matches.map(([, pkg]) => pkg); let pkg = matchArr[0]; if (/\.|http(s)?\:/.test(pkg)) return; else if ( /^(skypack|unpkg|jsdelivr|esm|esm\.run|esm\.sh)\:/.test(pkg) ) { pkg = pkg.replace( /^(skypack|unpkg|jsdelivr|esm|esm\.run|esm\.sh)\:/, "" ); } return (async () => { let { url, version: inputedVersion } = parseInput(pkg); let result: any; try { let response = await getRequest(url, true); result = await response.json(); } catch (e) { console.warn(e); return; } // result?.results -> api.npms.io // result?.objects -> registry.npmjs.com if (result?.results.length <= 0) return; // result?.results -> api.npms.io // result?.objects -> registry.npmjs.com const { name, description, version, date, publisher, links } = result?.results?.[0]?.package ?? {}; let author = publisher?.username; let _date = new Date(date).toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric", }); return { contents: [].concat({ value: `### [${name}](${links?.npm }) v${inputedVersion || version}\n${description}\n\n\nPublished on ${_date} ${author ? `by [@${author}](https://www.npmjs.com/~${author})` : "" }\n\n${links?.repository ? `[GitHub](${links?.repository}) |` : "" } [Skypack](https://skypack.dev/view/${name}) | [Unpkg](https://unpkg.com/browse/${name}/) | [Openbase](https://openbase.com/js/${name})`, }), }; })(); }, }); return [inputEditor, outputEditor]; };
the_stack
import * as Immutable from "immutable"; import * as _ from "lodash"; import { Base } from "./base"; import { Collapse } from "./collapse"; import { Event } from "./event"; import { Key } from "./key"; import { Select } from "./select"; import { timerange, TimeRange } from "./timerange"; import { CollapseOptions, SelectOptions } from "./types"; import { DedupFunction, ReducerFunction, ValueMap } from "./types"; import { avg, first, InterpolationType, last, max, median, min, percentile, stdev, sum } from "./functions"; /** * Convert the `fieldspec` into a list if it is not already. */ function fieldAsArray(field: string | string[]): string[] { if (_.isArray(field)) { return field; } else if (_.isString(field)) { return field.split("."); } } /** * A `Collection` holds a ordered (but not sorted) list of `Event`s and provides the * underlying functionality for manipulating those `Event`s. * * In Typescript, `Collection` is a generic of type `T`, which is the homogeneous * `Event` type of the `Collection`. `T` is likely one of: * * `Collection<Time>` * * `Collection<TimeRange>` * * `Collection<Index>` * * A `Collection` has several sub-classes, including a `SortedCollection`, which maintains * `Events` in chronological order. * * A `TimeSeries` wraps a `SortedCollection` by attaching meta data to the series of * chronological `Event`s. This provides the most common structure to use for dealing with * sequences of `Event`s. */ export class Collection<T extends Key> extends Base { /** * Rebuild the keyMap from scratch */ protected static buildKeyMap<S extends Key>( events: Immutable.List<Event<S>> ): Immutable.Map<string, Immutable.Set<number>> { let keyMap = Immutable.Map<string, Immutable.Set<number>>(); events.forEach((e, i) => { const k = e.getKey().toString(); const indicies: Immutable.Set<number> = keyMap.has(k) ? keyMap.get(k).add(i) : Immutable.Set<number>([i]); keyMap = keyMap.set(k, indicies); }); return keyMap; } // Member variables protected _events: Immutable.List<Event<T>>; protected _keyMap: Immutable.Map<string, Immutable.Set<number>>; /** * Construct a new `Collection`. * * You can construct a new empty `Collection` with `new`: * * ``` * const myCollection = new Collection<Time>(); * ``` * * Alternatively, you can use the factory function: * * ``` * const myCollection = collection<Time>(); * ``` * * A `Collection` may also be constructed with an initial list of `Events` * by supplying an `Immutable.List<Event<T>>`, or from another `Collection` * to make a copy. * * See also `SortedCollection`, which keeps `Event`s in chronological order, * and also allows you to do `groupBy` and `window` operations. For a higher * level interface for managing `Event`s, use the `TimeSeries`, which wraps * the `SortedCollection` along with meta data about that collection. */ constructor(arg1?: Immutable.List<Event<T>> | Collection<T>) { super(); if (!arg1) { this._events = Immutable.List<Event<T>>(); this._keyMap = Immutable.Map<string, Immutable.Set<number>>(); } else if (arg1 instanceof Collection) { const other = arg1 as Collection<T>; this._events = other._events; this._keyMap = other._keyMap; } else if (Immutable.List.isList(arg1)) { this._events = arg1; this._keyMap = Collection.buildKeyMap<T>(arg1); } } /** * Returns the `Collection` as a regular JSON object. */ public toJSON(): any { return this._events.toJS(); } /** * Serialize out the `Collection` as a string. This will be the * string representation of `toJSON()`. */ public toString(): string { return JSON.stringify(this.toJSON()); } /** * Adds a new `Event` into the `Collection`, returning a new `Collection` * containing that `Event`. Optionally the `Event`s may be de-duplicated. * * The dedup arg may `true` (in which case any existing `Event`s with the * same key will be replaced by this new Event), or with a function. If * dedup is a user function that function will be passed a list of all `Event`s * with that duplicated key and will be expected to return a single `Event` * to replace them with, thus shifting de-duplication logic to the user. * * Example 1: * * ``` * let myCollection = collection<Time>() * .addEvent(e1) * .addEvent(e2); * ``` * * Example 2: * ``` * // dedup with the sum of the duplicated events * const myCollection = collection<Time>() * .addEvent(e1) * .addEvent(e2) * .addEvent(e3, (events) => { * const a = events.reduce((sum, e) => sum + e.get("a"), 0); * return new Event<Time>(t, { a }); * }); * ``` */ public addEvent(event: Event<T>, dedup?: DedupFunction<T> | boolean): Collection<T> { const k = event.getKey().toString(); let events = this._events; let e = event; // Our event to be added let indicies: Immutable.Set<number> = this._keyMap.has(k) ? this._keyMap.get(k) : Immutable.Set<number>(); // Dedup if (dedup) { const conflicts = this.atKey(event.getKey()).toList(); if (conflicts.size > 0) { // Remove duplicates from the event list events = this._events.filterNot( duplicate => duplicate.getKey().toString() === event.getKey().toString() ); // Resolves the duplicates and this event to a single event if (_.isFunction(dedup)) { e = dedup(conflicts.concat(e)); } // Indicies for this key will only have this one event in it indicies = Immutable.Set(); } } // Add the new event to our event list events = events.push(e); // Call the post add hook to give sub-classes a chance to modify // the event list. If they do, then we'll rebuild the keyMap. let newKeyMap = this._keyMap; indicies = indicies.add(events.size - 1); newKeyMap = this._keyMap.set(k, indicies); return this.clone(events, newKeyMap) as Collection<T>; } /** * Removes the `Event` (or duplicate keyed Events) with the given key. */ public removeEvents(key: T): Collection<T> { const k = key.toString(); const indices = this._keyMap.get(k); const events = this._events.filterNot((event, i) => indices.has(i)); const keyMap = this._keyMap.remove(k); return this.clone(events, keyMap) as Collection<T>; } /** * Takes the last n `Event`'s of the `Collection` and returns a new `Collection`. */ public takeLast(amount: number): Collection<T> { const events = this._events.takeLast(amount); const keyMap = Collection.buildKeyMap(events); return this.clone(events, keyMap) as Collection<T>; } /** * Completely replace the existing `Event`'s in this Collection. */ public setEvents(events: Immutable.List<Event<T>>): Collection<T> { let keyMap = Immutable.Map<string, Immutable.Set<number>>(); events.forEach((e, i) => { const k = e.getKey().toString(); const indicies: Immutable.Set<number> = keyMap.has(k) ? keyMap.get(k).add(i) : Immutable.Set<number>([i]); keyMap = keyMap.set(k, indicies); }); return this.clone(events, keyMap) as Collection<T>; } /** * Returns the number of `Event`'s in this Collection */ public size(): number { return this._events.size; } /** * Returns the number of valid items in this `Collection`. * * Uses the `fieldPath` to look up values in all Events. * * It then counts the number that are considered valid, which * specifically are not: * * NaN * * undefined * * null. */ public sizeValid(fieldPath: string = "value"): number { let count = 0; this._events.forEach(e => { if (e.isValid(fieldPath)) { count++; } }); return count; } /** * Return if the `Collection` has any events in it */ public isEmpty(): boolean { return this.size() === 0; } /** * Returns the `Event` at the given position `pos` in the `Collection`. The * events in the `Collection` will be in the same order as they were inserted, * unless some sorting has been evoked by the user. * * Note: this is the least efficient way to fetch a point. If you wish to scan * the whole set of Events, use iterators (see `forEach()` and `map()`). * For direct access the `Collection` is optimized for returning results via * the `Event`'s key T, i.e. timestamp (see `atKey()`). * * Example: * ``` * const c1 = collection( * Immutable.List([ * event(time("2015-04-22T03:30:00Z"), Immutable.Map({ a: 5, b: 6 })), * event(time("2015-04-22T02:30:00Z"), Immutable.Map({ a: 4, b: 2 })) * ]) * ); * c1.at(1).get("a") // 4 * ``` */ public at(pos: number): Event<T> { return this.eventList().get(pos); } /** * Returns the `Event` located at the key specified, if it exists. * * Note: this doesn't find the closest key, or implement `bisect`. For that you need the * `SortedCollection`, that is also part of a `TimeSeries`. * On the plus side, if you know the key this is an efficient way to access the * `Event` within the `Collection`. * * Example: * ``` * const t1 = time("2015-04-22T03:30:00Z"); * const t2 = time("2015-04-22T02:30:00Z"); * const c1 = collection( * Immutable.List([ * event(t1, Immutable.Map({ a: 5, b: 6 })), * event(t2, Immutable.Map({ a: 4, b: 2 })) * ]) * ); * const event = collection.atKey(t2); * event.get("a") // 4 * ``` */ public atKey(key: T): Immutable.List<Event<T>> { const indexes = this._keyMap.get(key.toString()); return indexes .map(i => { return this._events.get(i); }) .toList(); } /** * Returns the first event in the `Collection`. */ public firstEvent(): Event<T> { return this._events.first(); } /** * Returns the last event in the `Collection`. */ public lastEvent(): Event<T> { return this._events.last(); } /** * Returns all the `Event<T>`s as an `Immutable.List`. */ public eventList(): Immutable.List<Event<T>> { return this._events.toList(); } /** * Returns the events in the `Collection` as an `Immutable.Map`, where * the key of type `T` (`Time`, `Index`, or `TimeRange`), * represented as a string, is mapped to the `Event` itself. * * @returns Immutable.Map<T, Event<T>> Events in this Collection, * converted to a Map. */ public eventMap() { return this._events.toMap(); } /** * Returns an iterator (`IterableIterator`) into the internal * list of events within this `Collection`. * * Example: * ``` * let iterator = collection.entries(); * for (let x = iterator.next(); !x.done; x = iterator.next()) { * const [key, event] = x.value; * console.log(`Key: ${key}, Event: ${event.toString()}`); * } * ``` */ public entries(): IterableIterator<[number, Event<T>]> { return this._events.entries(); } /** * Iterate over the events in this `Collection`. * * `Event`s are in the order that they were added, unless the Collection * has since been sorted. The `sideEffect` is a user supplied function which * is passed the `Event<T>` and the index. * * Returns the number of items iterated. * * Example: * ``` * collection.forEach((e, i) => { * console.log(`Event[${i}] is ${e.toString()}`); * }) * ``` */ public forEach(sideEffect: (value?: Event<T>, index?: number) => any): number { return this._events.forEach(sideEffect); } /** * Map the `Event`s in this `Collection` to new `Event`s. * * For each `Event` passed to your `mapper` function you return a new Event. * * Example: * ``` * const mapped = sorted.map(event => { * return new Event(event.key(), { a: event.get("x") * 2 }); * }); * ``` */ public map<M extends Key>( mapper: (event?: Event<T>, index?: number) => Event<M> ): Collection<M> { const remapped = this._events.map(mapper); return new Collection<M>(Immutable.List<Event<M>>(remapped)); } /** * Remap the keys, but keep the data the same. You can use this if you * have a `Collection` of `Event<Index>` and want to convert to events * of `Event<Time>`s, for example. The return result of remapping the * keys of a T to U i.e. `Collection<T>` remapped with new keys of type * `U` as a `Collection<U>`. * * Example: * * In this example we remap `Time` keys to `TimeRange` keys using the `Time.toTimeRange()` * method, centering the new `TimeRange`s around each `Time` with duration given * by the `Duration` object supplied, in this case representing one hour. * * ``` * const remapped = myCollection.mapKeys<TimeRange>(t => * t.toTimeRange(duration("1h"), TimeAlignment.Middle) * ); * ``` * */ public mapKeys<U extends Key>(mapper: (key: T) => U): Collection<U> { const list = this._events.map( event => new Event<U>(mapper(event.getKey()), event.getData()) ); return new Collection<U>(list); } /** * Flat map over the events in this `Collection`. * * For each `Event<T>` passed to your callback function you should map that to * zero, one or many `Event<U>`s, returned as an `Immutable.List<Event<U>>`. * * Example: * ``` * const processor = new Fill<T>(options); // processor addEvent() returns 0, 1 or n new events * const filled = this.flatMap<T>(e => processor.addEvent(e)); * ``` */ public flatMap<U extends Key>( mapper: (event?: Event<T>, index?: number) => Immutable.List<Event<U>> ): Collection<U> { const remapped: Immutable.List<Event<U>> = this._events.flatMap(mapper); return new Collection<U>(Immutable.List<Event<U>>(remapped)); } /** * Sorts the `Collection` by the `Event` key `T`. * * In the case case of the key being `Time`, this is clear. * For `TimeRangeEvents` and `IndexedEvents`, the `Collection` * will be sorted by the begin time. * * This method is particularly useful when the `Collection` * will be passed into a `TimeSeries`. * * See also `Collection.isChronological()`. * * @example * ``` * const sorted = collection.sortByKey(); * ``` */ public sortByKey(): Collection<T> { const sorted = Immutable.List<Event<T>>( this._events.sortBy(event => { return +event.getKey().timestamp(); }) ); return new Collection<T>(sorted); } /** * Sorts the `Collection` using the value referenced by * the `field`. */ public sort(field: string | string[]): Collection<T> { const fs = fieldAsArray(field); const sorted = Immutable.List<Event<T>>( this._events.sortBy(event => { return event.get(fs); }) ); return new Collection<T>(sorted); } /** * Perform a slice of events within the `Collection`, returns a new * `Collection` representing a portion of this `TimeSeries` from `begin` up to * but not including `end`. */ public slice(begin?: number, end?: number): Collection<T> { return this.setEvents(this._events.slice(begin, end)); } /** * Returns a new `Collection` with all `Event`s except the first */ public rest(): Collection<T> { return this.setEvents(this._events.rest()); } /** * Filter the Collection's `Event`'s with the supplied function. * * The function `predicate` is passed each `Event` and should return * true to keep the `Event` or false to discard. * * Example: * ``` * const filtered = collection.filter(e => e.get("a") < 8) * ``` */ public filter(predicate: (event: Event<T>, index: number) => boolean) { return this.setEvents(this._events.filter(predicate)); } /** * Returns the time range extents of the `Collection` as a `TimeRange`. * * Since this `Collection` is not necessarily in order, this method will traverse the * `Collection` and determine the earliest and latest time represented within it. */ public timerange(): TimeRange { let minimum; let maximum; this.forEach(e => { if (!minimum || e.begin() < minimum) { minimum = e.begin(); } if (!maximum || e.end() > maximum) { maximum = e.end(); } }); if (minimum && maximum) { return timerange(minimum, maximum); } } /** * Aggregates the `Collection`'s `Event`s down to a single value per field. * * This makes use of a user defined function suppled as the `reducer` to do * the reduction of values to a single value. The `ReducerFunction` is defined * like so: * * ``` * (values: number[]) => number * ``` * * Fields to be aggregated are specified using a `fieldSpec` argument, which * can be a field name or array of field names. * * If the `fieldSpec` matches multiple fields then an object is returned * with keys being the fields and the values being the aggregated value for * those fields. If the `fieldSpec` is for a single field then just the * aggregated value is returned. * * Note: The `Collection` class itself contains most of the common aggregation functions * built in (e.g. `myCollection.avg("value")`), but this is here to help when what * you need isn't supplied out of the box. */ public aggregate(reducer: ReducerFunction, fieldSpec: string | string[]); public aggregate(reducer: ReducerFunction, fieldSpec?) { const v: ValueMap = Event.aggregate(this.eventList(), reducer, fieldSpec); if (_.isString(fieldSpec)) { return v[fieldSpec]; } else if (_.isArray(fieldSpec)) { return v; } } /** * Returns the first value in the `Collection` for the `fieldspec` */ public first(fieldSpec: string, filter?): number; public first(fieldSpec: string[], filter?): { [s: string]: number[] }; public first(fieldSpec: any, filter?) { return this.aggregate(first(filter), fieldSpec); } /** * Returns the last value in the `Collection` for the `fieldspec` */ public last(fieldSpec: string, filter?): number; public last(fieldSpec: string[], filter?): { [s: string]: number[] }; public last(fieldSpec: any, filter?) { return this.aggregate(last(filter), fieldSpec); } /** * Returns the sum of the `Event`'s in this `Collection` * for the `fieldspec` */ public sum(fieldSpec: string, filter?): number; public sum(fieldSpec: string[], filter?): { [s: string]: number[] }; public sum(fieldSpec: any, filter?) { return this.aggregate(sum(filter), fieldSpec); } /** * Aggregates the `Event`'s in this `Collection` down * to their average(s). * * The `fieldSpec` passed into the avg function is either * a field name or a list of fields. * * The `filter` is one of the Pond filter functions that can be used to remove * bad values in different ways before filtering. * * Example: * ``` * const e1 = event(time("2015-04-22T02:30:00Z"), Immutable.Map({ a: 8, b: 2 })); * const e2 = event(time("2015-04-22T01:30:00Z"), Immutable.Map({ a: 3, b: 3 })); * const e3 = event(time("2015-04-22T03:30:00Z"), Immutable.Map({ a: 5, b: 7 })); * const c = collection<Time>() * .addEvent(e1) * .addEvent(e2) * .addEvent(e3); * * c.avg("b") // 4 */ public avg(fieldSpec: string, filter?): number; public avg(fieldSpec: string[], filter?): { [s: string]: number[] }; public avg(fieldSpec: any, filter?) { return this.aggregate(avg(filter), fieldSpec); } /** * Aggregates the `Event`'s in this `Collection` down to * their maximum value(s). * * The `fieldSpec` passed into the avg function is either a field name or * a list of fields. * * The `filter` is one of the Pond filter functions that can be used to remove * bad values in different ways before filtering. * * The result is the maximum value if the fieldSpec is for one field. If * multiple fields then a map of fieldName -> max values is returned */ public max(fieldSpec: string, filter?): number; public max(fieldSpec: string[], filter?): { [s: string]: number[] }; public max(fieldSpec: any, filter?) { return this.aggregate(max(filter), fieldSpec); } /** * Aggregates the `Event`'s in this `Collection` down to * their minimum value(s) */ public min(fieldSpec: string, filter?): number; public min(fieldSpec: string[], filter?): { [s: string]: number[] }; public min(fieldSpec: any, filter?) { return this.aggregate(min(filter), fieldSpec); } /** * Aggregates the events down to their median value */ public median(fieldSpec: string, filter?): number; public median(fieldSpec: string[], filter?): { [s: string]: number[] }; public median(fieldSpec: any, filter?) { return this.aggregate(median(filter), fieldSpec); } /** * Aggregates the events down to their standard deviation */ public stdev(fieldSpec: string, filter?): number; public stdev(fieldSpec: string[], filter?): { [s: string]: number[] }; public stdev(fieldSpec: any, filter?) { return this.aggregate(stdev(filter), fieldSpec); } /** * Gets percentile q within the `Collection`. This works the same way as numpy. * * The percentile function has several parameters that can be supplied: * * `q` - The percentile (should be between 0 and 100) * * `fieldSpec` - Field or fields to find the percentile of * * `interp` - Specifies the interpolation method to use when the desired, see below * * `filter` - Optional filter function used to clean data before aggregating * * For `interp` a `InterpolationType` should be supplied if the default ("linear") is * not used. This enum is defined like so: * ``` * enum InterpolationType { * linear = 1, * lower, * higher, * nearest, * midpoint * } * ``` * Emum values: * * `linear`: i + (j - i) * fraction, where fraction is the * fractional part of the index surrounded by i and j. * * `lower`: i. * * `higher`: j. * * `nearest`: i or j whichever is nearest. * * `midpoint`: (i + j) / 2. * */ public percentile(q: number, fieldSpec: string, interp?: InterpolationType, filter?): number; public percentile( q: number, fieldSpec: string[], interp?: InterpolationType, filter? ): { [s: string]: number[] }; public percentile( q: number, fieldSpec: any, interp: InterpolationType = InterpolationType.linear, filter? ) { return this.aggregate(percentile(q, interp, filter), fieldSpec); } /** * Gets n quantiles within the `Collection`. * * The quantiles function has several parameters that can be supplied: * * `n` - The number of quantiles * * `column` - Field to find the quantiles within * * `interp` - Specifies the interpolation method to use when the desired, see below * * For `interp` a `InterpolationType` should be supplied if the default ("linear") is * not used. This enum is defined like so: * ``` * enum InterpolationType { * linear = 1, * lower, * higher, * nearest, * midpoint * } * ``` * Emum values: * * `linear`: i + (j - i) * fraction, where fraction is the * fractional part of the index surrounded by i and j. * * `lower`: i. * * `higher`: j. * * `nearest`: i or j whichever is nearest. * * `midpoint`: (i + j) / 2. */ public quantile( n: number, column: string = "value", interp: InterpolationType = InterpolationType.linear ) { const results = []; const sorted = this.sort(column); const subsets = 1.0 / n; if (n > this.size()) { throw new Error("Subset n is greater than the Collection length"); } for (let i = subsets; i < 1; i += subsets) { const index = Math.floor((sorted.size() - 1) * i); if (index < sorted.size() - 1) { const fraction = (sorted.size() - 1) * i - index; const v0 = +sorted.at(index).get(column); const v1 = +sorted.at(index + 1).get(column); let v; if (InterpolationType.lower || fraction === 0) { v = v0; } else if (InterpolationType.linear) { v = v0 + (v1 - v0) * fraction; } else if (InterpolationType.higher) { v = v1; } else if (InterpolationType.nearest) { v = fraction < 0.5 ? v0 : v1; } else if (InterpolationType.midpoint) { v = (v0 + v1) / 2; } results.push(v); } } return results; } /** * Returns true if all events in this `Collection` are in chronological order. */ public isChronological(): boolean { let result = true; let t; this.forEach(e => { if (!t) { t = e.timestamp().getTime(); } else { if (e.timestamp() < t) { result = false; } t = e.timestamp(); } }); return result; } /** * Collapse multiple columns of a `Collection` into a new column. * * The `collapse()` method needs to be supplied with a `CollapseOptions` * object. You use this to specify the columns to collapse, the column name * of the column to collapse to and the reducer function. In addition you * can choose to append this new column or use it in place of the columns * collapsed. * * ``` * { * fieldSpecList: string[]; * fieldName: string; * reducer: any; * append: boolean; * } * ``` * Options: * * `fieldSpecList` - the list of fields to collapse * * `fieldName` - the new field's name * * `reducer()` - a function to collapse using e.g. `avg()` * * `append` - to include only the new field, or include it in addition * to the previous fields. * * Example: * ``` * // Initial collection * const t1 = time("2015-04-22T02:30:00Z"); * const t2 = time("2015-04-22T03:30:00Z"); * const t3 = time("2015-04-22T04:30:00Z"); * const c = collection<Time>() * .addEvent(event(t1, Immutable.Map({ a: 5, b: 6 }))) * .addEvent(event(t2, Immutable.Map({ a: 4, b: 2 }))) * .addEvent( event(t2, Immutable.Map({ a: 6, b: 3 }))); * * // Sum columns "a" and "b" into a new column "v" * const sums = c.collapse({ * fieldSpecList: ["a", "b"], * fieldName: "v", * reducer: sum(), * append: false * }); * * sums.at(0).get("v") // 11 * sums.at(1).get("v") // 6 * sums.at(2).get("v") // 9 * ``` */ public collapse(options: CollapseOptions): Collection<T> { const p = new Collapse<T>(options); return this.flatMap(e => p.addEvent(e)); } /** * Select out specified columns from the `Event`s within this `Collection`. * * The `select()` method needs to be supplied with a `SelectOptions` * object, which takes the following form: * * ``` * { * fields: string[]; * } * ``` * Options: * * `fields` - array of columns to keep within each `Event`. * * Example: * ``` * const timestamp1 = time("2015-04-22T02:30:00Z"); * const timestamp2 = time("2015-04-22T03:30:00Z"); * const timestamp3 = time("2015-04-22T04:30:00Z"); * const e1 = event(timestamp1, Immutable.Map({ a: 5, b: 6, c: 7 })); * const e2 = event(timestamp2, Immutable.Map({ a: 4, b: 5, c: 6 })); * const e3 = event(timestamp2, Immutable.Map({ a: 6, b: 3, c: 2 })); * * const c = collection<Time>() * .addEvent(e1) * .addEvent(e2) * .addEvent(e3); * * const c1 = c.select({ * fields: ["b", "c"] * }); * * // result: 3 events containing just b and c (a is discarded) * ``` */ public select(options: SelectOptions): Collection<T> { const p = new Select<T>(options); return this.flatMap(e => p.addEvent(e)); } // // To be reimplemented by subclass // /** * Internal method to clone this `Collection` (protected) */ protected clone(events, keyMap): Base { const c = new Collection<T>(); c._events = events; c._keyMap = keyMap; return c; } protected onEventAdded(events: Immutable.List<Event<T>>): Immutable.List<Event<T>> { return events; } } function collectionFactory<T extends Key>(arg1?: Immutable.List<Event<T>> | Collection<T>) { return new Collection<T>(arg1); } export { collectionFactory as collection };
the_stack
import * as chai from "chai" import * as chaiAsPromised from "chai-as-promised" import * as sinon from "sinon" import * as sinonChai from "sinon-chai" import { HTTPMethod } from "./common/request" import { Interaction, InteractionObject } from "./dsl/interaction" import { MockService } from "./dsl/mockService" import { PactOptions, PactOptionsComplete } from "./dsl/options" import serviceFactory from "@pact-foundation/pact-node" import { Pact } from "./httpPact" import { ImportMock } from "ts-mock-imports" // Mock out the PactNode interfaces class PactServer { public start(): void {} public delete(): void {} } chai.use(sinonChai) chai.use(chaiAsPromised) const expect = chai.expect describe("Pact", () => { let pact: Pact const fullOpts = { consumer: "A", provider: "B", port: 1234, host: "127.0.0.1", ssl: false, logLevel: "info", spec: 2, cors: false, pactfileWriteMode: "overwrite", } as PactOptionsComplete before(() => { // Stub out pact-node const manager = ImportMock.mockClass(serviceFactory, "createServer") as any manager.mock("createServer", () => {}) }) beforeEach(() => { pact = (Object.create(Pact.prototype) as any) as Pact pact.opts = fullOpts }) afterEach(() => { sinon.restore() // return serviceFactory.removeAllServers() }) describe("#constructor", () => { it("throws Error when consumer not provided", () => { expect(() => { new Pact({ consumer: "", provider: "provider" }) }).to.throw(Error, "You must specify a Consumer for this pact.") }) it("throws Error when provider not provided", () => { expect(() => { new Pact({ consumer: "someconsumer", provider: "" }) }).to.throw(Error, "You must specify a Provider for this pact.") }) }) describe("#createOptionsWithDefault", () => { const constructorOpts: PactOptions = { consumer: "A", provider: "B", } it("merges options with sensible defaults", () => { const opts = Pact.createOptionsWithDefaults(constructorOpts) expect(opts.consumer).to.eq("A") expect(opts.provider).to.eq("B") expect(opts.cors).to.eq(false) expect(opts.host).to.eq("127.0.0.1") expect(opts.logLevel).to.eq("info") expect(opts.spec).to.eq(2) expect(opts.dir).not.to.be.empty expect(opts.log).not.to.be.empty expect(opts.pactfileWriteMode).to.eq("overwrite") expect(opts.ssl).to.eq(false) expect(opts.sslcert).to.eq(undefined) expect(opts.sslkey).to.eq(undefined) }) }) describe("#setup", () => { const serverMock = { start: () => Promise.resolve(), options: { port: 1234 }, logLevel: (a: any) => {}, } describe("when server is not properly configured", () => { describe("and pact-node is unable to start the server", () => { it("returns a rejected promise", async () => { const p: any = new Pact(fullOpts) p.server = { start: () => Promise.reject("pact-node error"), options: { port: 1234 }, } return expect(p.setup()).to.eventually.be.rejectedWith( "pact-node error" ) }) }) }) describe("when server is properly configured", () => { it("starts the mock server in the background", () => { const p: any = new Pact(fullOpts) p.server = serverMock return expect(p.setup()).to.eventually.be.fulfilled }) }) describe("when server is properly configured", () => { it("returns the current configuration", () => { const p: any = new Pact(fullOpts) p.server = serverMock return expect(p.setup()).to.eventually.include({ consumer: "A", provider: "B", port: 1234, host: "127.0.0.1", ssl: false, logLevel: "info", spec: 2, cors: false, pactfileWriteMode: "overwrite", }) }) }) }) describe("#addInteraction", () => { const interaction: InteractionObject = { state: "i have a list of projects", uponReceiving: "a request for projects", withRequest: { method: HTTPMethod.GET, path: "/projects", headers: { Accept: "application/json" }, }, willRespondWith: { status: 200, headers: { "Content-Type": "application/json" }, body: {}, }, } describe("when given a provider state", () => { it("creates interaction with state", () => { pact.mockService = { addInteraction: ( int: InteractionObject ): Promise<string | undefined> => Promise.resolve(int.state), } as any return expect( pact.addInteraction(interaction) ).to.eventually.have.property("providerState") }) }) describe("when not given a provider state", () => { it("creates interaction with no state", () => { pact.mockService = { addInteraction: ( int: InteractionObject ): Promise<string | undefined> => Promise.resolve(int.state), } as any interaction.state = undefined return expect( pact.addInteraction(interaction) ).to.eventually.not.have.property("providerState") }) describe("when given an Interaction as a builder", () => { it("creates interaction", () => { const interaction2 = new Interaction() .given("i have a list of projects") .uponReceiving("a request for projects") .withRequest({ method: HTTPMethod.GET, path: "/projects", headers: { Accept: "application/json" }, }) .willRespondWith({ status: 200, headers: { "Content-Type": "application/json" }, body: {}, }) pact.mockService = { addInteraction: (int: Interaction): Promise<Interaction> => Promise.resolve(int), } as any return expect( pact.addInteraction(interaction2) ).to.eventually.have.property("given") }) }) }) }) describe("#verify", () => { describe("when pact verification is successful", () => { it("returns a successful promise and remove interactions", () => { pact.mockService = { verify: () => Promise.resolve("verified!"), removeInteractions: () => Promise.resolve("removeInteractions"), } as any const verifyPromise = pact.verify() return Promise.all([ expect(verifyPromise).to.eventually.eq("removeInteractions"), expect(verifyPromise).to.eventually.be.fulfilled, ]) }) }) describe("when pact verification is unsuccessful", () => { it("throws an error", () => { const removeInteractionsStub = sinon .stub(MockService.prototype, "removeInteractions") .resolves("removeInteractions") pact.mockService = { verify: () => Promise.reject("not verified!"), removeInteractions: removeInteractionsStub, } as any const verifyPromise = pact.verify() return Promise.all([ expect(verifyPromise).to.eventually.be.rejectedWith(Error), verifyPromise.catch(() => expect(removeInteractionsStub).to.callCount(1) ), ]) }) }) describe("when pact verification is successful", () => { describe("and an error is thrown in the cleanup", () => { it("throws an error", () => { pact.mockService = { verify: () => Promise.resolve("verified!"), removeInteractions: () => { throw new Error("error removing interactions") }, } as any return expect(pact.verify()).to.eventually.be.rejectedWith(Error) }) }) }) }) describe("#finalize", () => { describe("when writing Pact is successful", () => { it("returns a successful promise and shuts down down the mock server", () => { pact.mockService = { writePact: () => Promise.resolve("pact file written!"), removeInteractions: sinon.stub(), } as any pact.server = { delete: () => Promise.resolve(), } as any return expect(pact.finalize()).to.eventually.be.fulfilled }) }) describe("when writing Pact is unsuccessful", () => { it("throws an error and shuts down the server", () => { pact.mockService = { writePact: () => Promise.reject(new Error("pact not file written!")), removeInteractions: sinon.stub(), } as any const deleteStub = sinon.stub(PactServer.prototype, "delete").resolves() pact.server = { delete: deleteStub } as any return expect(pact.finalize()).to.eventually.be.rejected.then(() => expect(deleteStub).to.callCount(1) ) }) }) describe("when writing pact is successful and shutting down the mock server is unsuccessful", () => { it("throws an error", () => { pact.mockService = { writePact: sinon.stub(), removeInteractions: sinon.stub(), } as any pact.server = { delete: () => Promise.reject(), } as any return expect(pact.finalize).to.throw(Error) }) }) }) describe("#writePact", () => { describe("when writing Pact is successful", () => { it("returns a successful promise", () => { pact.mockService = { writePact: () => Promise.resolve("pact file written!"), removeInteractions: sinon.stub(), } as any const writePactPromise = pact.writePact() return Promise.all([ expect(writePactPromise).to.eventually.eq("pact file written!"), expect(writePactPromise).to.eventually.be.fulfilled, ]) }) }) }) describe("#removeInteractions", () => { describe("when removing interactions is successful", () => { it("returns a successful promise", () => { pact.mockService = { removeInteractions: () => Promise.resolve("interactions removed!"), } as any const removeInteractionsPromise = pact.removeInteractions() return Promise.all([ expect(removeInteractionsPromise).to.eventually.eq( "interactions removed!" ), expect(removeInteractionsPromise).to.eventually.be.fulfilled, ]) }) }) }) })
the_stack
import { NULL_ADDRESS, trimLeading0x } from '@celo/base/lib/address' import { BigNumber } from 'bignumber.js' import { keccak } from 'ethereumjs-util' import coder from 'web3-eth-abi' export interface EIP712Parameter { name: string type: string } export interface EIP712Types { [key: string]: EIP712Parameter[] } export interface EIP712TypesWithPrimary { types: EIP712Types primaryType: string } export type EIP712ObjectValue = | string | number | BigNumber | boolean | Buffer | EIP712Object | EIP712ObjectValue[] export interface EIP712Object { [key: string]: EIP712ObjectValue } export interface EIP712TypedData { types: EIP712Types & { EIP712Domain: EIP712Parameter[] } domain: EIP712Object message: EIP712Object primaryType: string } /** Array of all EIP-712 atomic type names. */ export const EIP712_ATOMIC_TYPES = [ 'bytes1', 'bytes32', 'uint8', 'uint256', 'int8', 'int256', 'bool', 'address', ] export const EIP712_DYNAMIC_TYPES = ['bytes', 'string'] export const EIP712_BUILTIN_TYPES = EIP712_ATOMIC_TYPES.concat(EIP712_DYNAMIC_TYPES) // Regular expression used to identify and parse EIP-712 array type strings. const EIP712_ARRAY_REGEXP = /^(?<memberType>[\w<>\[\]_\-]+)(\[(?<fixedLength>\d+)?\])$/ // Regular experssion used to identity EIP-712 integer types (e.g. int256, uint256, uint8). const EIP712_INT_REGEXP = /^u?int\d*$/ /** * Utility type representing an optional value in a EIP-712 compatible manner, as long as the * concrete type T is a subtype of EIP712ObjectValue. * * @remarks EIP712Optonal is not part of the EIP712 standard, but is fully compatible with it. */ // tslint:disable-next-line:interface-over-type-literal Only builds when defined as type literal. export type EIP712Optional<T extends EIP712ObjectValue> = { defined: boolean value: T } /** * Utility to build EIP712Optional<T> types to insert in EIP-712 type arrays. * @param typeName EIP-712 string type name. Should be builtin or defined in the EIP712Types * structure into which this type will be merged. */ export const eip712OptionalType = (typeName: string): EIP712Types => ({ [`Optional<${typeName}>`]: [ { name: 'defined', type: 'bool' }, { name: 'value', type: typeName }, ], }) /** Utility to construct an defined EIP712Optional value with inferred type. */ export const defined = <T extends EIP712ObjectValue>(value: T): EIP712Optional<T> => ({ defined: true, value, }) /** Undefined EIP712Optional type with value type boolean. */ export const noBool: EIP712Optional<boolean> = { defined: false, value: false, } /** Undefined EIP712Optional type with value type number. */ export const noNumber: EIP712Optional<number> = { defined: false, value: 0, } /** Undefined EIP712Optional type with value type string. */ export const noString: EIP712Optional<string> = { defined: false, value: '', } /** * Generates the EIP712 Typed Data hash for signing * @param typedData An object that conforms to the EIP712TypedData interface * @return A Buffer containing the hash of the typed data. */ export function generateTypedDataHash(typedData: EIP712TypedData): Buffer { return keccak( Buffer.concat([ Buffer.from('1901', 'hex'), structHash('EIP712Domain', typedData.domain, typedData.types), structHash(typedData.primaryType, typedData.message, typedData.types), ]) ) as Buffer } /** * Given the primary type, and dictionary of types, this function assembles a sorted list * representing the transitive dependency closure of the primary type. (Inclusive of the primary * type itself.) */ function findDependencies(primaryType: string, types: EIP712Types, found: string[] = []): string[] { // If we have aready found the dependencies of this type, or it is a builtin, return early. if (found.includes(primaryType) || EIP712_BUILTIN_TYPES.includes(primaryType)) { return [] } // If this is an array type, return the results for its member type. if (EIP712_ARRAY_REGEXP.test(primaryType)) { const match = EIP712_ARRAY_REGEXP.exec(primaryType) const memberType: string = match?.groups?.memberType! return findDependencies(memberType, types, found) } // If this is not a builtin and is not defined, we cannot correctly construct a type encoding. if (types[primaryType] === undefined) { throw new Error(`Unrecognized type ${primaryType} is not included in the EIP-712 type list`) } // Execute a depth-first search to populate the (inclusive) dependencies list. // By the first invarient of this function, the resulting list should not contain duplicates. const dependencies = [primaryType] for (const field of types[primaryType]) { dependencies.push(...findDependencies(field.type, types, found.concat(dependencies))) } return dependencies } /** * Creates a string encoding of the primary type, including all dependencies. * E.g. "Transaction(Person from,Person to,Asset tx)Asset(address token,uint256 amount)Person(address wallet,string name)" */ export function encodeType(primaryType: string, types: EIP712Types): string { let deps = findDependencies(primaryType, types) deps = deps.filter((d) => d !== primaryType) deps = [primaryType].concat(deps.sort()) let result = '' for (const dep of deps) { result += `${dep}(${types[dep].map(({ name, type }) => `${type} ${name}`).join(',')})` } return result } export function typeHash(primaryType: string, types: EIP712Types): Buffer { return keccak(encodeType(primaryType, types)) as Buffer } /** Encodes a single EIP-712 value to a 32-byte buffer */ function encodeValue(valueType: string, value: EIP712ObjectValue, types: EIP712Types): Buffer { // Encode the atomic types as their corresponding soldity ABI type. if (EIP712_ATOMIC_TYPES.includes(valueType)) { // @ts-ignore TypeScript does not believe encodeParameter exists. const hexEncoded = coder.encodeParameter(valueType, normalizeValue(valueType, value)) return Buffer.from(trimLeading0x(hexEncoded), 'hex') } // Encode `string` and `bytes` types as their keccak hash. if (valueType === 'string') { // Converting to Buffer before passing to `keccak` prevents an issue where the string is // interpretted as a hex-encoded string when is starts with 0x. // https://github.com/ethereumjs/ethereumjs-util/blob/7e3be1d97b4e11fbc4924836b8c444e644f643ac/index.js#L155-L183 return keccak(Buffer.from(value as string, 'utf8')) as Buffer } if (valueType === 'bytes') { // Allow the user to use either utf8 (plain string) or hex encoding for their bytes. // Note: keccak throws if the value cannot be converted into a Buffer, return keccak(value as string) as Buffer } // Encode structs as its hashStruct (e.g. keccak(typeHash || encodeData(struct)) ). if (types[valueType] !== undefined) { // tslint:disable-next-line:no-unnecessary-type-assertion. return structHash(valueType, value as EIP712Object, types) } // Encode arrays as the hash of the concatenated encoding of the underlying types. if (EIP712_ARRAY_REGEXP.test(valueType)) { // Note: If a fixed length is provided in the type, it is not checked. const match = EIP712_ARRAY_REGEXP.exec(valueType) const memberType: string = match?.groups?.memberType! return keccak( Buffer.concat( (value as EIP712ObjectValue[]).map((member) => encodeValue(memberType, member, types)) ) ) as Buffer } throw new Error(`Unrecognized or unsupported type in EIP-712 encoding: ${valueType}`) } function normalizeValue(type: string, value: EIP712ObjectValue): EIP712ObjectValue { const normalizedValue = EIP712_INT_REGEXP.test(type) && BigNumber.isBigNumber(value) ? value.toString() : value return normalizedValue } /** * Constructs the struct encoding of the data as the primary type. */ export function encodeData(primaryType: string, data: EIP712Object, types: EIP712Types): Buffer { const fields = types[primaryType] if (fields === undefined) { throw new Error(`Unrecognized primary type in EIP-712 encoding: ${primaryType}`) } return Buffer.concat(fields.map((field) => encodeValue(field.type, data[field.name], types))) } export function structHash(primaryType: string, data: EIP712Object, types: EIP712Types): Buffer { return keccak( Buffer.concat([typeHash(primaryType, types), encodeData(primaryType, data, types)]) ) as Buffer } /** * Produce the zero value for a given type. * * @remarks * All atomic types will encode as the 32-byte zero value. Dynamic types as an empty hash. * Dynamic arrays will return an empty array. Fixed length arrays will have members set to zero. * Structs will have the values of all fields set to zero recursively. * * Note that EIP-712 does not specify zero values, and so this is non-standard. */ export function zeroValue(primaryType: string, types: EIP712Types = {}): EIP712ObjectValue { // If the type is a built-in, return a pre-defined zero value. if (['bytes', 'bytes1', 'bytes32'].includes(primaryType)) { return Buffer.alloc(0) } if (['uint8', 'uint256', 'int8', 'int256'].includes(primaryType)) { return 0 } if (primaryType === 'bool') { return false } if (primaryType === 'address') { return NULL_ADDRESS } if (primaryType === 'string') { return '' } // If the type is an array, return an empty array or an array of the given fixed length. if (EIP712_ARRAY_REGEXP.test(primaryType)) { const match = EIP712_ARRAY_REGEXP.exec(primaryType) const memberType: string = match?.groups?.memberType! const fixedLengthStr: string | undefined = match?.groups?.fixedLength const fixedLength: number = fixedLengthStr === undefined ? 0 : parseInt(fixedLengthStr, 10) return [...Array(fixedLength).keys()].map(() => zeroValue(memberType, types)) } // Must be user-defined type. Return an object with all fields set to their zero value. const fields = types[primaryType] if (fields === undefined) { throw new Error(`Unrecognized primary type for EIP-712 zero value: ${primaryType}`) } return fields.reduce((obj, field) => ({ ...obj, [field.name]: zeroValue(field.type, types) }), {}) }
the_stack
import { mergeDefault } from '@klasa/utils'; import { Cache } from '@klasa/cache'; import { Tag, TagRequirement } from './Tag'; import type { TextBasedChannel, MessageOptions, MessageBuilder, Client, User, Message } from '@klasa/core'; import type { Usage } from './Usage'; import type { CommandUsage } from './CommandUsage'; const quotes = ['"', "'", '“”', '‘’']; export interface TextPromptOptions { /** * The intended target of this TextPrompt, if someone other than the author. * @default message.author */ target?: User; /** * The channel to prompt in, if other than this channel. * @default message.channel */ channel?: TextBasedChannel; /** * The number of re-prompts before this TextPrompt gives up. * @default Infinity */ limit?: number; /** * The time-limit for re-prompting. * @default 30000 */ time?: number; /** * Whether this prompt should respect quoted strings. * @default false */ quotedStringSupport?: boolean; /** * Whether this prompt should respect flags. * @default true */ flagSupport?: boolean; } /** * A class to handle argument collection and parameter resolution */ export class TextPrompt { /** * The client this TextPrompt was created with * @since 0.5.0 */ public readonly client!: Client; /** * The message this prompt is for * @since 0.5.0 */ public message: Message; /** * The target this prompt is for * @since 0.5.0 */ public target: User; /** * The channel to prompt in * @since 0.5.0 */ public channel: TextBasedChannel; /** * The usage for this prompt * @since 0.5.0 */ public usage: Usage | CommandUsage; /** * If the command reprompted for missing args * @since 0.0.1 */ public reprompted = false; /** * The flag arguments resolved by this class * @since 0.5.0 */ public flags: Record<string, string> = {}; /** * The string arguments derived from the usageDelim of the command * @since 0.0.1 */ public args: (string | undefined | null)[] = []; /** * The parameters resolved by this class * @since 0.0.1 */ public params: unknown[] = []; /** * The time-limit for re-prompting * @since 0.5.0 */ public time: number; /** * The number of re-prompts before this TextPrompt gives up * @since 0.5.0 */ public limit: number; /** * Whether this prompt should respect quoted strings * @since 0.5.0 */ public quotedStringSupport: boolean; /** * Whether this prompt should respect flags * @since 0.5.0 */ public flagSupport: boolean; /** * The typing state of this CommandPrompt * @since 0.5.0 */ protected typing: boolean; /** * Whether the current usage is a repeating arg * @since 0.0.1 */ #repeat = false; /** * Whether the current usage is required * @since 0.0.1 */ #required = TagRequirement.Optional; /** * How many time this class has reprompted * @since 0.0.1 */ #prompted = 0; /** * A cache of the current usage while validating * @since 0.0.1 */ #currentUsage: Tag | null = null; /** * @since 0.5.0 * @param message The message this prompt is for * @param usage The usage for this prompt * @param options The options of this prompt */ constructor(message: Message, usage: Usage, options: TextPromptOptions = {}) { options = mergeDefault(message.client.options.commands.prompts, options) as TextPromptOptions; Object.defineProperty(this, 'client', { value: message.client }); this.message = message; this.target = options.target ?? message.author; this.typing = false; this.channel = options.channel ?? message.channel; this.usage = usage; this.time = options.time as number; this.limit = options.limit as number; this.quotedStringSupport = options.quotedStringSupport as boolean; this.flagSupport = options.flagSupport as boolean; } public run(prompt: MessageOptions): Promise<unknown[]> public run(prompt: (message: MessageBuilder) => MessageBuilder | Promise<MessageBuilder>): Promise<unknown[]> /** * Runs the custom prompt. * @since 0.5.0 * @param prompt The message to initially prompt with * @returns The parameters resolved */ public async run(prompt: MessageOptions | ((message: MessageBuilder) => MessageBuilder | Promise<MessageBuilder>)): Promise<unknown[]> { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error const message = await this.prompt(prompt); this._setup(message.content); return this.validateArgs(); } private prompt(data: MessageOptions): Promise<Message> private prompt(data: (message: MessageBuilder) => MessageBuilder | Promise<MessageBuilder>): Promise<Message> /** * Prompts the target for a response * @since 0.5.0 * @param data The message to prompt with */ private async prompt(data: MessageOptions | ((message: MessageBuilder) => MessageBuilder | Promise<MessageBuilder>)): Promise<Message> { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error const [message] = await this.channel.send(data); const responses = await message.channel.awaitMessages({ idle: this.time, limit: 1, filter: ([msg]) => msg.author === this.target }); message.delete(); if (responses.size === 0) throw this.message.language.get('MESSAGE_PROMPT_TIMEOUT'); return responses.firstValue as Message; } /** * Collects missing required arguments. * @since 0.5.0 * @param prompt The reprompt error */ public async reprompt(prompt: string): Promise<unknown[]> { this.#prompted++; if (this.typing) this.message.channel.typing.stop(); const abortTerm = this.message.language.get('TEXT_PROMPT_ABORT'); const oldContent = this.message.content; const message = await this.prompt(mb => mb .setContent(this.message.language.get('MONITOR_COMMAND_HANDLER_REPROMPT', `<@!${this.target.id}>`, prompt, this.time / 1000, abortTerm)) ); if (this.message.content !== oldContent || message.prefix || message.content.toLowerCase() === abortTerm) { throw this.message.language.get('MONITOR_COMMAND_HANDLER_ABORTED'); } if (this.typing) this.message.channel.typing.start(); this.args[this.args.lastIndexOf(null)] = message.content; this.reprompted = true; if (this.usage.parsedUsage[this.params.length].repeat) return this.repeatingPrompt(); return this.validateArgs(); } /** * Collects repeating arguments. * @since 0.5.0 */ private async repeatingPrompt(): Promise<unknown[]> { if (this.typing) this.message.channel.typing.stop(); let message; const abortTerm = this.message.language.get('TEXT_PROMPT_ABORT'); try { message = await this.prompt(mb => mb // eslint-disable-next-line @typescript-eslint/no-non-null-assertion .setContent(this.message.language.get('MONITOR_COMMAND_HANDLER_REPEATING_REPROMPT', `<@!${this.message.author.id}>`, this.#currentUsage!.possibles[0].name, this.time / 1000, abortTerm)) ); } catch (err) { return this.validateArgs(); } if (message.content.toLowerCase() === abortTerm) return this.validateArgs(); if (this.typing) this.message.channel.typing.start(); this.args.push(message.content); this.reprompted = true; return this.repeatingPrompt(); } /** * Validates and resolves args into parameters * @since 0.0.1 * @returns The resolved parameters */ protected async validateArgs(): Promise<unknown[]> { if (this.params.length >= this.usage.parsedUsage.length && this.params.length >= this.args.length) { return this.finalize(); } else if (this.params.length < this.usage.parsedUsage.length) { this.#currentUsage = this.usage.parsedUsage[this.params.length]; this.#required = this.#currentUsage.required; } else if (this.#currentUsage?.repeat) { this.#required = TagRequirement.Optional; this.#repeat = true; } else { return this.finalize(); } this.#prompted = 0; return this.multiPossibles(0); } /** * Validates and resolves args into parameters, when multiple types of usage is defined * @since 0.0.1 * @param index The id of the possible usage currently being checked * @returns The resolved parameters */ private async multiPossibles(index: number): Promise<unknown[]> { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const possible = this.#currentUsage!.possibles[index]; const custom = this.usage.customResolvers.get(possible.type); const resolver = this.client.arguments.get(custom ? 'custom' : possible.type); if (possible.name in this.flags) this.args.splice(this.params.length, 0, this.flags[possible.name]); if (!resolver) { this.client.emit('warn', `Unknown Argument Type encountered: ${possible.type}`); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (this.#currentUsage!.possibles.length === (index + 1)) return this.pushParam(undefined); return this.multiPossibles(++index); } try { const res = await resolver.run(this.args[this.params.length] as string, possible, this.message, custom); if (typeof res === 'undefined' && this.#required === TagRequirement.SemiRequired) this.args.splice(this.params.length, 0, undefined); return this.pushParam(res); } catch (err) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (index < this.#currentUsage!.possibles.length - 1) return this.multiPossibles(++index); if (!this.#required) { if (this.#repeat) this.args.splice(this.params.length, 1); else this.args.splice(this.params.length, 0, undefined); return this.#repeat ? this.validateArgs() : this.pushParam(undefined); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { response } = this.#currentUsage!; const error = typeof response === 'function' ? response(this.message, possible) : response; if (this.#required === TagRequirement.SemiRequired) return this.handleError(error || err); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (this.#currentUsage!.possibles.length === 1) { return this.handleError(error || (this.args[this.params.length] === undefined ? this.message.language.get('COMMANDMESSAGE_MISSING_REQUIRED', possible.name) : err)); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this.handleError(error || this.message.language.get('COMMANDMESSAGE_NOMATCH', this.#currentUsage!.possibles.map(poss => poss.name).join(', '))); } } /** * Pushes a parameter into this.params, and resets the re-prompt count. * @since 0.5.0 * @param param The resolved parameter */ private pushParam(param: unknown): Promise<unknown[]> { this.params.push(param); return this.validateArgs(); } /** * Decides if the prompter should reprompt or throw the error found while validating. * @since 0.5.0 * @param err The error found while validating */ private async handleError(err: string): Promise<unknown[]> { this.args.splice(this.params.length, 1, null); if (this.limit && this.#prompted < this.limit) return this.reprompt(err); throw err; } /** * Finalizes parameters and arguments for this prompt. * @since 0.5.0 */ private finalize(): unknown[] { for (let i = this.params.length - 1; i >= 0 && this.params[i] === undefined; i--) this.params.pop(); for (let i = this.args.length - 1; i >= 0 && this.args[i] === undefined; i--) this.args.pop(); return this.params; } /** * Splits the original message string into arguments. * @since 0.5.0 * @param original The original message string */ private _setup(original: string): void { const { content, flags } = this.flagSupport ? (this.constructor as typeof TextPrompt).getFlags(original, this.usage.usageDelim) : { content: original, flags: {} }; this.flags = flags; this.args = this.quotedStringSupport ? (this.constructor as typeof TextPrompt).getQuotedStringArgs(content, this.usage.usageDelim).map(arg => arg.trim()) : (this.constructor as typeof TextPrompt).getArgs(content, this.usage.usageDelim).map(arg => arg.trim()); } /** * Parses a message into string args * @since 0.5.0 * @param content The remaining content * @param delim The delimiter */ private static getFlags(content: string, delim: string): { content: string, flags: Record<string, string> } { const flags: Record<string, string> = {}; content = content.replace(this.flagRegex, (_match, fl, ...quote) => { flags[fl] = (quote.slice(0, -2).find(el => el) || fl).replace(/\\/g, ''); return ''; }); if (delim) content = content.replace(this.delims.get(delim) || this.generateNewDelim(delim), '$1').trim(); return { content, flags }; } /** * Parses a message into string args * @since 0.0.1 * @param content The remaining content * @param delim The delimiter */ private static getArgs(content: string, delim: string): string[] { const args = delim !== '' ? content.split(delim) : [content]; return args.length === 1 && args[0] === '' ? [] : args; } /** * Parses a message into string args taking into account quoted strings * @since 0.0.1 * @param content The remaining content * @param delim The delimiter */ private static getQuotedStringArgs(content: string, delim: string): string[] { if (!delim || delim === '') return [content]; const args = []; for (let i = 0; i < content.length; i++) { let current = ''; if (content.slice(i, i + delim.length) === delim) { i += delim.length - 1; continue; } const quote = quotes.find(qt => qt.includes(content[i])); if (quote) { const qts = quote.split(''); while (i + 1 < content.length && (content[i] === '\\' || !qts.includes(content[i + 1]))) current += content[++i] === '\\' && qts.includes(content[i + 1]) ? '' : content[i]; i++; args.push(current); } else { current += content[i]; while (i + 1 < content.length && content.slice(i + 1, i + delim.length + 1) !== delim) current += content[++i]; args.push(current); } } return args.length === 1 && args[0] === '' ? [] : args; } /** * Generate a new delimiter's RegExp and cache it * @since 0.5.0 * @param delim The delimiter */ private static generateNewDelim(delim: string): RegExp { const regex = new RegExp(`(${delim})(?:${delim})+`, 'g'); this.delims.set(delim, regex); return regex; } /** * Map of RegExps caching usageDelim's RegExps. * @since 0.5.0 */ public static delims = new Cache<string, RegExp>(); /** * Regular Expression to match flags with quoted string support. * @since 0.5.0 */ public static flagRegex = new RegExp(`(?:--|—)(\\w[\\w-]+)(?:=(?:${quotes.map(qu => `[${qu}]((?:[^${qu}\\\\]|\\\\.)*)[${qu}]`).join('|')}|([\\w<>@#&!-]+)))?`, 'g'); }
the_stack
import {VComponent} from "./VisComponent"; import {D3Sel} from "../etc/Util"; import {SimpleEventHandler} from "../etc/SimpleEventHandler"; import {AblationUpload, GanterAPI, ImageMask} from "../api/GanterAPI"; import {isEqual} from "lodash" import * as d3 from "d3" export type GanPaintViewData = { image: HTMLImageElement, imageID?: string, resetSelection?: boolean, alpha?: number } export type GanPaintMeta = { payload: AblationUpload[], name: string, remove: boolean } export class GanPaintView extends VComponent<GanPaintViewData> { protected options = { pos: {x: 0, y: 0}, width: 256, height: 256, grid_size: 32, radius: 1, draw_color: "#0bc6d4", remove_color: "#e1484a", active_alpha: .7 }; protected css_name = "GanPaintView"; protected _current = { meta: <GanPaintMeta>null, canvas: <HTMLCanvasElement>null, new_meta: <GanPaintMeta>{}, highlight: <HTMLCanvasElement>null, empty: true, alpha: 1 }; // stack of all masks protected _maskStack: { meta: GanPaintMeta, canvas: HTMLCanvasElement }[] = []; public static events = { maskChanged: "GanPaintView_mc" } private _canvas: D3Sel; private static currentActiveWidget: GanPaintView = null; constructor(_parent: D3Sel, _eventHandler: SimpleEventHandler) { super(_parent, _eventHandler); this.superInitHTML(); // TODO:hack // this.base.attr('class', ''); this._init(); } protected _currentMouseGrid() { const [x, y] = d3.mouse(this._canvas.node()); return [ Math.floor(x / this.options.width * this.options.grid_size), Math.floor(y / this.options.height * this.options.grid_size) ] } _createNewCanvas() { const res = document.createElement('canvas'); res.width = this.options.grid_size; res.height = this.options.grid_size; return res; } protected _init() { const op = this.options; const cur = this._current; this._canvas = this.base.append('canvas') .property('width', op.width) .property('height', op.height); const ctx = (<HTMLCanvasElement>this._canvas.node()).getContext('2d'); ctx.beginPath(); ctx.fillText('< please select image from top >', 10, 10); ctx.closePath(); const drawCircle = (drawCtx: CanvasRenderingContext2D, x: number, y: number, r: number) => { drawCtx.beginPath(); const [gx, gy] = this._currentMouseGrid(); drawCtx.ellipse(gx, gy, r, r, 0, 0, 2 * Math.PI); drawCtx.fill(); drawCtx.closePath(); } const dragstarted = () => { cur.empty = false; cur.meta = cur.new_meta; cur.canvas = this._createNewCanvas(); cur.alpha = op.active_alpha; const drawCtx = cur.canvas.getContext('2d'); drawCtx.fillStyle = cur.meta.remove ? op.remove_color : op.draw_color; const x0 = d3.event.x, y0 = d3.event.y; drawCircle(drawCtx, x0, y0, op.radius); d3.event.on('drag', () => { const x = d3.event.x, y = d3.event.y; drawCircle(drawCtx, x, y, op.radius); this._render(); }); this._render(); }; const dragend = () => { this._paintFinished(); }; this._canvas.call( d3.drag() .container(() => this._canvas.node()) .on('start', dragstarted) .on('end', dragend) ); // this._canvas.on('mousedown', () => { // // console.log(onmousedown, "--- onmousedown"); // cur.empty = false; // // // NOT EQUAL ? // // if (!isEqual(cur.meta, cur.new_meta)) { // // // if not just started // // if (cur.meta !== null) { // // // push current to stack and create new one // // this._maskStack.push({ // // meta: cur.meta, // // canvas: cur.canvas // // }) // // } // // cur.meta = cur.new_meta; // cur.canvas = this._createNewCanvas(); // // // } // // // this.options.alpha = .7; // // const drawCtx = cur.canvas.getContext('2d'); // this._canvas.on("mousemove", (e) => { // drawCtx.beginPath(); // drawCtx.fillStyle = op.draw_color; // const [gx, gy] = this._currentMouseGrid(); // // drawCtx.ellipse(gx, gy, // op.radius, op.radius, // 0, 0, 2 * Math.PI); // drawCtx.fill(); // drawCtx.closePath(); // this._render(); // }); // GanPaintView.currentActiveWidget = this; // // // }); // // // // TODO: not super elegant to overwrite window listener.. // window.onmouseup = (e) => { // if (GanPaintView.currentActiveWidget == null) return; // // const that = GanPaintView.currentActiveWidget; // const callOverlay = (that._canvas.on('mousemove') !== null); // // that._canvas.on('mousemove', null); // GanPaintView.currentActiveWidget = null; // // if (callOverlay) { // console.log("callOverlay--- "); // that._paintFinished(); // } // // } } highlightCanvas(id: number, highlight = true) { if (highlight) { if (id < this._maskStack.length) { this._current.highlight = this._maskStack[id].canvas; } else if (id == this._maskStack.length) { // if the last canvas this._current.highlight = this._current.canvas; } } else { this._current.highlight = null; } this._render(); } removeCanvas(id: number, fireEvent = true) { if (id < this._maskStack.length) { this._maskStack.splice(id, 1); } else if (id == this._maskStack.length) { // if the last canvas this._current.canvas = this._createNewCanvas(); this._current.empty = true; } this._current.highlight = null; this._render(); if (fireEvent) this.eventHandler.trigger( GanPaintView.events.maskChanged, {caller: this}); } removeLast(fireEvent = true) { if (this.maskStack.length > 0) this.removeCanvas(this.maskStack.length - 1, fireEvent) } resetMasks(fireEvent = true) { this._maskStack = []; this._current.highlight = null; this._render(); if (fireEvent) this.eventHandler.trigger( GanPaintView.events.maskChanged, {caller: this}); } private _paintFinished() { const cur = this._current; if (cur.meta !== null) { // push current to stack and create new one this._maskStack.push({ meta: cur.meta, canvas: cur.canvas }) } this.eventHandler.trigger( GanPaintView.events.maskChanged, {caller: this}); } private fireMaskEvent(mask) { const imgMask: ImageMask = { id: this.renderData.imageID || -1, mask }; this.eventHandler.trigger(GanPaintView.events.maskChanged, this) } protected _wrangle(data: GanPaintViewData) { if (data.resetSelection) { this._maskStack = []; this._current.canvas = this._createNewCanvas(); } if (data.alpha !== null) { this._current.alpha = data.alpha; } return data; } protected _render(rD: GanPaintViewData = this.renderData): void { if (rD == null) return; const op = this.options; const cur = this._current; this._canvas .property('width', op.width) .property('height', op.height); const ctx = this._canvas.node().getContext('2d'); // render BG ctx.beginPath(); ctx.drawImage(rD.image, 0, 0); ctx.closePath(); if (this._current.highlight) { ctx.beginPath(); ctx.globalAlpha = op.active_alpha; ctx.drawImage(this._current.highlight, 0, 0, op.width, op.height); ctx.closePath(); } else if (this._current.canvas) { ctx.beginPath(); ctx.globalAlpha = cur.alpha; ctx.drawImage(this._current.canvas, 0, 0, op.width, op.height); ctx.closePath(); } } private resetSelection() { // this.psw.reset() } setNewMeta(d: GanPaintMeta) { this._current.new_meta = d; } changeCurrentMeta(data: GanPaintMeta) { this._current.meta = data; this._current.new_meta = data; } get currentMeta() { return this._current.meta }; get newMeta() { return this._current.new_meta }; get maskStack() { return this._maskStack; } /** get all stacked layers including current one */ get currentStack() { return this.maskStack // return [...this._maskStack, { // meta: this._current.meta, // canvas: this._current.canvas // }]; } // get image() { // return this.psw.backgroundImage; // } // get imageID() { return this.renderData.imageID; } get canvas() { return this._canvas; } // // // set zoom(z) { // this.psw.zoom = z; // } // // set opacity(o: number) { // this.psw.alpha = o; // } // // // reset(supressEvent = false) { // this.psw.reset(); // if (!supressEvent) { // this.fireMaskEvent(this.psw.currentMask) // } // } }
the_stack
export const ietfLanguageTags = [ 'af', 'af-NA', 'af-ZA', 'agq', 'agq-CM', 'ak', 'ak-GH', 'am', 'am-ET', 'ar', 'ar-001', 'ar-AE', 'ar-BH', 'ar-DJ', 'ar-DZ', 'ar-EG', 'ar-EH', 'ar-ER', 'ar-IL', 'ar-IQ', 'ar-JO', 'ar-KM', 'ar-KW', 'ar-LB', 'ar-LY', 'ar-MA', 'ar-MR', 'ar-OM', 'ar-PS', 'ar-QA', 'ar-SA', 'ar-SD', 'ar-SO', 'ar-SS', 'ar-SY', 'ar-TD', 'ar-TN', 'ar-YE', 'as', 'as-IN', 'asa', 'asa-TZ', 'ast', 'ast-ES', 'az', 'az-Cyrl', 'az-Cyrl-AZ', 'az-Latn', 'az-Latn-AZ', 'bas', 'bas-CM', 'be', 'be-BY', 'bem', 'bem-ZM', 'bez', 'bez-TZ', 'bg', 'bg-BG', 'bm', 'bm-ML', 'bn', 'bn-BD', 'bn-IN', 'bo', 'bo-CN', 'bo-IN', 'br', 'br-FR', 'brx', 'brx-IN', 'bs', 'bs-Cyrl', 'bs-Cyrl-BA', 'bs-Latn', 'bs-Latn-BA', 'ca', 'ca-AD', 'ca-ES', 'ca-ES-VALENCIA', 'ca-FR', 'ca-IT', 'ccp', 'ccp-BD', 'ccp-IN', 'ce', 'ce-RU', 'cgg', 'cgg-UG', 'chr', 'chr-US', 'ckb', 'ckb-IQ', 'ckb-IR', 'cs', 'cs-CZ', 'cu', 'cu-RU', 'cy', 'cy-GB', 'da', 'da-DK', 'da-GL', 'dav', 'dav-KE', 'de', 'de-AT', 'de-BE', 'de-CH', 'de-DE', 'de-IT', 'de-LI', 'de-LU', 'dje', 'dje-NE', 'dsb', 'dsb-DE', 'dua', 'dua-CM', 'dyo', 'dyo-SN', 'dz', 'dz-BT', 'ebu', 'ebu-KE', 'ee', 'ee-GH', 'ee-TG', 'el', 'el-CY', 'el-GR', 'en', 'en-001', 'en-150', 'en-AG', 'en-AI', 'en-AS', 'en-AT', 'en-AU', 'en-BB', 'en-BE', 'en-BI', 'en-BM', 'en-BS', 'en-BW', 'en-BZ', 'en-CA', 'en-CC', 'en-CH', 'en-CK', 'en-CM', 'en-CX', 'en-CY', 'en-DE', 'en-DG', 'en-DK', 'en-DM', 'en-ER', 'en-FI', 'en-FJ', 'en-FK', 'en-FM', 'en-GB', 'en-GD', 'en-GG', 'en-GH', 'en-GI', 'en-GM', 'en-GU', 'en-GY', 'en-HK', 'en-IE', 'en-IL', 'en-IM', 'en-IN', 'en-IO', 'en-JE', 'en-JM', 'en-KE', 'en-KI', 'en-KN', 'en-KY', 'en-LC', 'en-LR', 'en-LS', 'en-MG', 'en-MH', 'en-MO', 'en-MP', 'en-MS', 'en-MT', 'en-MU', 'en-MW', 'en-MY', 'en-NA', 'en-NF', 'en-NG', 'en-NL', 'en-NR', 'en-NU', 'en-NZ', 'en-PG', 'en-PH', 'en-PK', 'en-PN', 'en-PR', 'en-PW', 'en-RW', 'en-SB', 'en-SC', 'en-SD', 'en-SE', 'en-SG', 'en-SH', 'en-SI', 'en-SL', 'en-SS', 'en-SX', 'en-SZ', 'en-TC', 'en-TK', 'en-TO', 'en-TT', 'en-TV', 'en-TZ', 'en-UG', 'en-UM', 'en-US', 'en-US-POSIX', 'en-VC', 'en-VG', 'en-VI', 'en-VU', 'en-WS', 'en-ZA', 'en-ZM', 'en-ZW', 'eo', 'eo-001', 'es', 'es-419', 'es-AR', 'es-BO', 'es-BR', 'es-BZ', 'es-CL', 'es-CO', 'es-CR', 'es-CU', 'es-DO', 'es-EA', 'es-EC', 'es-ES', 'es-GQ', 'es-GT', 'es-HN', 'es-IC', 'es-MX', 'es-NI', 'es-PA', 'es-PE', 'es-PH', 'es-PR', 'es-PY', 'es-SV', 'es-US', 'es-UY', 'es-VE', 'et', 'et-EE', 'eu', 'eu-ES', 'ewo', 'ewo-CM', 'fa', 'fa-AF', 'fa-IR', 'ff', 'ff-Latn', 'ff-Latn-BF', 'ff-Latn-CM', 'ff-Latn-GH', 'ff-Latn-GM', 'ff-Latn-GN', 'ff-Latn-GW', 'ff-Latn-LR', 'ff-Latn-MR', 'ff-Latn-NE', 'ff-Latn-NG', 'ff-Latn-SL', 'ff-Latn-SN', 'fi', 'fi-FI', 'fil', 'fil-PH', 'fo', 'fo-DK', 'fo-FO', 'fr', 'fr-BE', 'fr-BF', 'fr-BI', 'fr-BJ', 'fr-BL', 'fr-CA', 'fr-CD', 'fr-CF', 'fr-CG', 'fr-CH', 'fr-CI', 'fr-CM', 'fr-DJ', 'fr-DZ', 'fr-FR', 'fr-GA', 'fr-GF', 'fr-GN', 'fr-GP', 'fr-GQ', 'fr-HT', 'fr-KM', 'fr-LU', 'fr-MA', 'fr-MC', 'fr-MF', 'fr-MG', 'fr-ML', 'fr-MQ', 'fr-MR', 'fr-MU', 'fr-NC', 'fr-NE', 'fr-PF', 'fr-PM', 'fr-RE', 'fr-RW', 'fr-SC', 'fr-SN', 'fr-SY', 'fr-TD', 'fr-TG', 'fr-TN', 'fr-VU', 'fr-WF', 'fr-YT', 'fur', 'fur-IT', 'fy', 'fy-NL', 'ga', 'ga-IE', 'gd', 'gd-GB', 'gl', 'gl-ES', 'gsw', 'gsw-CH', 'gsw-FR', 'gsw-LI', 'gu', 'gu-IN', 'guz', 'guz-KE', 'gv', 'gv-IM', 'ha', 'ha-GH', 'ha-NE', 'ha-NG', 'haw', 'haw-US', 'he', 'he-IL', 'hi', 'hi-IN', 'hr', 'hr-BA', 'hr-HR', 'hsb', 'hsb-DE', 'hu', 'hu-HU', 'hy', 'hy-AM', 'ia', 'ia-001', 'id', 'id-ID', 'ig', 'ig-NG', 'ii', 'ii-CN', 'is', 'is-IS', 'it', 'it-CH', 'it-IT', 'it-SM', 'it-VA', 'ja', 'ja-JP', 'jgo', 'jgo-CM', 'jmc', 'jmc-TZ', 'jv', 'jv-ID', 'ka', 'ka-GE', 'kab', 'kab-DZ', 'kam', 'kam-KE', 'kde', 'kde-TZ', 'kea', 'kea-CV', 'khq', 'khq-ML', 'ki', 'ki-KE', 'kk', 'kk-KZ', 'kkj', 'kkj-CM', 'kl', 'kl-GL', 'kln', 'kln-KE', 'km', 'km-KH', 'kn', 'kn-IN', 'ko', 'ko-KP', 'ko-KR', 'kok', 'kok-IN', 'ks', 'ks-IN', 'ksb', 'ksb-TZ', 'ksf', 'ksf-CM', 'ksh', 'ksh-DE', 'ku', 'ku-TR', 'kw', 'kw-GB', 'ky', 'ky-KG', 'lag', 'lag-TZ', 'lb', 'lb-LU', 'lg', 'lg-UG', 'lkt', 'lkt-US', 'ln', 'ln-AO', 'ln-CD', 'ln-CF', 'ln-CG', 'lo', 'lo-LA', 'lrc', 'lrc-IQ', 'lrc-IR', 'lt', 'lt-LT', 'lu', 'lu-CD', 'luo', 'luo-KE', 'luy', 'luy-KE', 'lv', 'lv-LV', 'mas', 'mas-KE', 'mas-TZ', 'mer', 'mer-KE', 'mfe', 'mfe-MU', 'mg', 'mg-MG', 'mgh', 'mgh-MZ', 'mgo', 'mgo-CM', 'mi', 'mi-NZ', 'mk', 'mk-MK', 'ml', 'ml-IN', 'mn', 'mn-MN', 'mr', 'mr-IN', 'ms', 'ms-BN', 'ms-MY', 'ms-SG', 'mt', 'mt-MT', 'mua', 'mua-CM', 'my', 'my-MM', 'mzn', 'mzn-IR', 'naq', 'naq-NA', 'nb', 'nb-NO', 'nb-SJ', 'nd', 'nd-ZW', 'nds', 'nds-DE', 'nds-NL', 'ne', 'ne-IN', 'ne-NP', 'nl', 'nl-AW', 'nl-BE', 'nl-BQ', 'nl-CW', 'nl-NL', 'nl-SR', 'nl-SX', 'nmg', 'nmg-CM', 'nn', 'nn-NO', 'nnh', 'nnh-CM', 'nus', 'nus-SS', 'nyn', 'nyn-UG', 'om', 'om-ET', 'om-KE', 'or', 'or-IN', 'os', 'os-GE', 'os-RU', 'pa', 'pa-Arab', 'pa-Arab-PK', 'pa-Guru', 'pa-Guru-IN', 'pl', 'pl-PL', 'prg', 'prg-001', 'ps', 'ps-AF', 'pt', 'pt-AO', 'pt-BR', 'pt-CH', 'pt-CV', 'pt-GQ', 'pt-GW', 'pt-LU', 'pt-MO', 'pt-MZ', 'pt-PT', 'pt-ST', 'pt-TL', 'qu', 'qu-BO', 'qu-EC', 'qu-PE', 'rm', 'rm-CH', 'rn', 'rn-BI', 'ro', 'ro-MD', 'ro-RO', 'rof', 'rof-TZ', 'root', 'ru', 'ru-BY', 'ru-KG', 'ru-KZ', 'ru-MD', 'ru-RU', 'ru-UA', 'rw', 'rw-RW', 'rwk', 'rwk-TZ', 'sah', 'sah-RU', 'saq', 'saq-KE', 'sbp', 'sbp-TZ', 'sd', 'sd-PK', 'se', 'se-FI', 'se-NO', 'se-SE', 'seh', 'seh-MZ', 'ses', 'ses-ML', 'sg', 'sg-CF', 'shi', 'shi-Latn', 'shi-Latn-MA', 'shi-Tfng', 'shi-Tfng-MA', 'si', 'si-LK', 'sk', 'sk-SK', 'sl', 'sl-SI', 'smn', 'smn-FI', 'sn', 'sn-ZW', 'so', 'so-DJ', 'so-ET', 'so-KE', 'so-SO', 'sq', 'sq-AL', 'sq-MK', 'sq-XK', 'sr', 'sr-Cyrl', 'sr-Cyrl-BA', 'sr-Cyrl-ME', 'sr-Cyrl-RS', 'sr-Cyrl-XK', 'sr-Latn', 'sr-Latn-BA', 'sr-Latn-ME', 'sr-Latn-RS', 'sr-Latn-XK', 'sv', 'sv-AX', 'sv-FI', 'sv-SE', 'sw', 'sw-CD', 'sw-KE', 'sw-TZ', 'sw-UG', 'ta', 'ta-IN', 'ta-LK', 'ta-MY', 'ta-SG', 'te', 'te-IN', 'teo', 'teo-KE', 'teo-UG', 'tg', 'tg-TJ', 'th', 'th-TH', 'ti', 'ti-ER', 'ti-ET', 'tk', 'tk-TM', 'to', 'to-TO', 'tr', 'tr-CY', 'tr-TR', 'tt', 'tt-RU', 'twq', 'twq-NE', 'tzm', 'tzm-MA', 'ug', 'ug-CN', 'uk', 'uk-UA', 'ur', 'ur-IN', 'ur-PK', 'uz', 'uz-Arab', 'uz-Arab-AF', 'uz-Cyrl', 'uz-Cyrl-UZ', 'uz-Latn', 'uz-Latn-UZ', 'vai', 'vai-Latn', 'vai-Latn-LR', 'vai-Vaii', 'vai-Vaii-LR', 'vi', 'vi-VN', 'vo', 'vo-001', 'vun', 'vun-TZ', 'wae', 'wae-CH', 'wo', 'wo-SN', 'xh', 'xh-ZA', 'xog', 'xog-UG', 'yav', 'yav-CM', 'yi', 'yi-001', 'yo', 'yo-BJ', 'yo-NG', 'yue', 'yue-Hans', 'yue-Hans-CN', 'yue-Hant', 'yue-Hant-HK', 'zgh', 'zgh-MA', 'zh', 'zh-Hans', 'zh-Hans-CN', 'zh-Hans-HK', 'zh-Hans-MO', 'zh-Hans-SG', 'zh-Hant', 'zh-Hant-HK', 'zh-Hant-MO', 'zh-Hant-TW', 'zu', 'zu-ZA' ]; /** * We support IETF language tags for sign language (https://tools.ietf.org/html/rfc5646). * * For sign language translations of strings, you can use media URLs pointing to video, video * websites or description pictures. If there are several alternatives, it's best to point to a * video. */ export const signLanguageCodes = [ 'ase', 'sgn-ase', 'sgn-ase-US', 'sgn-GH-EP', 'sgn-DZ', 'sgn-US', 'sgn-AR', 'sgn-AM', 'sgn-AU-NT', 'sgn-AU', 'sgn-AT', 'sgn-ID-BA', 'sgn-BE-VLG', 'sgn-BE-WAL', 'sgn-BO', 'sgn-BR', 'sgn-GB', 'sgn-BG', 'sgn-ES-CT', 'sgn-TD', 'sgn-CL', 'sgn-CN', 'sgn-CO', 'sgn-CR', 'sgn-CZ', 'sgn-DK', 'sgn-NL', 'sgn-EC', 'sgn-SV', 'sgn-CA-NU', 'sgn-ET', 'sgn-FI', 'sgn-CA-QC', 'sgn-FR', 'sgn-DE', 'sgn-GH', 'sgn-GR', 'sgn-GT', 'sgn-US-HI', 'sgn-HK', 'sgn-IS', 'sgn-ID', 'sgn-IN', 'sgn-IE', 'sgn-IL', 'sgn-IT', 'sgn-JM', 'sgn-JP', 'sgn-JO', 'sgn-KE', 'sgn-KR', 'sgn-MY-B', 'sgn-LV', 'sgn-LY', 'sgn-LT', 'sgn-FR-69', 'sgn-MY', 'sgn-MT', 'sgn-US-MA', 'sgn-MX-YUC', 'sgn-MX', 'sgn-VA', 'sgn-MN', 'sgn-MA', 'sgn-NA', 'sgn-NP', 'sgn-NZ', 'sgn-NI', 'sgn-NG', 'sgn-NO', 'sgn-CA-NS', 'sgn-GB-KEN', 'sgn-MY-P', 'sgn-IR', 'sgn-PE', 'sgn-PH', 'sgn-US-SD', 'sgn-PL', 'sgn-PT', 'sgn-CO-SAP', 'sgn-PR', 'sgn-SB', 'sgn-RO', 'sgn-RU', 'sgn-SA', 'sgn-SE-crp', 'sgn-SG', 'sgn-SK', 'sgn-ZA', 'sgn-ES', 'sgn-LK', 'sgn-SE', 'sgn-CH-GE', 'sgn-CH-ZH', 'sgn-CH-TI', 'sgn-TW', 'sgn-TZ', 'sgn-TH', 'sgn-TN', 'sgn-TR', 'sgn-UG', 'sgn-UA', 'sgn-BR-MA', 'sgn-UY', 'sgn-VE', 'sgn-IL-yid', 'sgn-YU', 'sgn-ZM', 'sgn-ZW', 'sgn-afr-ZA', 'sgn-chi-TW', 'sgn-dan-DK', 'sgn-dut-BE', 'sgn-dut-NL', 'sgn-eng-GB', 'sgn-eng-IE', 'sgn-eng-US', 'sgn-fin-FI', 'sgn-fre-BE', 'sgn-fre-CA', 'sgn-fre-FR', 'sgn-jpn-JP', 'sgn-nor-NO', 'sgn-por-PT', 'sgn-swe-SE' ]; export type IetfLanguageTag = | 'af' | 'af-NA' | 'af-ZA' | 'agq' | 'agq-CM' | 'ak' | 'ak-GH' | 'am' | 'am-ET' | 'ar' | 'ar-001' | 'ar-AE' | 'ar-BH' | 'ar-DJ' | 'ar-DZ' | 'ar-EG' | 'ar-EH' | 'ar-ER' | 'ar-IL' | 'ar-IQ' | 'ar-JO' | 'ar-KM' | 'ar-KW' | 'ar-LB' | 'ar-LY' | 'ar-MA' | 'ar-MR' | 'ar-OM' | 'ar-PS' | 'ar-QA' | 'ar-SA' | 'ar-SD' | 'ar-SO' | 'ar-SS' | 'ar-SY' | 'ar-TD' | 'ar-TN' | 'ar-YE' | 'as' | 'as-IN' | 'asa' | 'asa-TZ' | 'ast' | 'ast-ES' | 'az' | 'az-Cyrl' | 'az-Cyrl-AZ' | 'az-Latn' | 'az-Latn-AZ' | 'bas' | 'bas-CM' | 'be' | 'be-BY' | 'bem' | 'bem-ZM' | 'bez' | 'bez-TZ' | 'bg' | 'bg-BG' | 'bm' | 'bm-ML' | 'bn' | 'bn-BD' | 'bn-IN' | 'bo' | 'bo-CN' | 'bo-IN' | 'br' | 'br-FR' | 'brx' | 'brx-IN' | 'bs' | 'bs-Cyrl' | 'bs-Cyrl-BA' | 'bs-Latn' | 'bs-Latn-BA' | 'ca' | 'ca-AD' | 'ca-ES' | 'ca-ES-VALENCIA' | 'ca-FR' | 'ca-IT' | 'ccp' | 'ccp-BD' | 'ccp-IN' | 'ce' | 'ce-RU' | 'cgg' | 'cgg-UG' | 'chr' | 'chr-US' | 'ckb' | 'ckb-IQ' | 'ckb-IR' | 'cs' | 'cs-CZ' | 'cu' | 'cu-RU' | 'cy' | 'cy-GB' | 'da' | 'da-DK' | 'da-GL' | 'dav' | 'dav-KE' | 'de' | 'de-AT' | 'de-BE' | 'de-CH' | 'de-DE' | 'de-IT' | 'de-LI' | 'de-LU' | 'dje' | 'dje-NE' | 'dsb' | 'dsb-DE' | 'dua' | 'dua-CM' | 'dyo' | 'dyo-SN' | 'dz' | 'dz-BT' | 'ebu' | 'ebu-KE' | 'ee' | 'ee-GH' | 'ee-TG' | 'el' | 'el-CY' | 'el-GR' | 'en' | 'en-001' | 'en-150' | 'en-AG' | 'en-AI' | 'en-AS' | 'en-AT' | 'en-AU' | 'en-BB' | 'en-BE' | 'en-BI' | 'en-BM' | 'en-BS' | 'en-BW' | 'en-BZ' | 'en-CA' | 'en-CC' | 'en-CH' | 'en-CK' | 'en-CM' | 'en-CX' | 'en-CY' | 'en-DE' | 'en-DG' | 'en-DK' | 'en-DM' | 'en-ER' | 'en-FI' | 'en-FJ' | 'en-FK' | 'en-FM' | 'en-GB' | 'en-GD' | 'en-GG' | 'en-GH' | 'en-GI' | 'en-GM' | 'en-GU' | 'en-GY' | 'en-HK' | 'en-IE' | 'en-IL' | 'en-IM' | 'en-IN' | 'en-IO' | 'en-JE' | 'en-JM' | 'en-KE' | 'en-KI' | 'en-KN' | 'en-KY' | 'en-LC' | 'en-LR' | 'en-LS' | 'en-MG' | 'en-MH' | 'en-MO' | 'en-MP' | 'en-MS' | 'en-MT' | 'en-MU' | 'en-MW' | 'en-MY' | 'en-NA' | 'en-NF' | 'en-NG' | 'en-NL' | 'en-NR' | 'en-NU' | 'en-NZ' | 'en-PG' | 'en-PH' | 'en-PK' | 'en-PN' | 'en-PR' | 'en-PW' | 'en-RW' | 'en-SB' | 'en-SC' | 'en-SD' | 'en-SE' | 'en-SG' | 'en-SH' | 'en-SI' | 'en-SL' | 'en-SS' | 'en-SX' | 'en-SZ' | 'en-TC' | 'en-TK' | 'en-TO' | 'en-TT' | 'en-TV' | 'en-TZ' | 'en-UG' | 'en-UM' | 'en-US' | 'en-US-POSIX' | 'en-VC' | 'en-VG' | 'en-VI' | 'en-VU' | 'en-WS' | 'en-ZA' | 'en-ZM' | 'en-ZW' | 'eo' | 'eo-001' | 'es' | 'es-419' | 'es-AR' | 'es-BO' | 'es-BR' | 'es-BZ' | 'es-CL' | 'es-CO' | 'es-CR' | 'es-CU' | 'es-DO' | 'es-EA' | 'es-EC' | 'es-ES' | 'es-GQ' | 'es-GT' | 'es-HN' | 'es-IC' | 'es-MX' | 'es-NI' | 'es-PA' | 'es-PE' | 'es-PH' | 'es-PR' | 'es-PY' | 'es-SV' | 'es-US' | 'es-UY' | 'es-VE' | 'et' | 'et-EE' | 'eu' | 'eu-ES' | 'ewo' | 'ewo-CM' | 'fa' | 'fa-AF' | 'fa-IR' | 'ff' | 'ff-Latn' | 'ff-Latn-BF' | 'ff-Latn-CM' | 'ff-Latn-GH' | 'ff-Latn-GM' | 'ff-Latn-GN' | 'ff-Latn-GW' | 'ff-Latn-LR' | 'ff-Latn-MR' | 'ff-Latn-NE' | 'ff-Latn-NG' | 'ff-Latn-SL' | 'ff-Latn-SN' | 'fi' | 'fi-FI' | 'fil' | 'fil-PH' | 'fo' | 'fo-DK' | 'fo-FO' | 'fr' | 'fr-BE' | 'fr-BF' | 'fr-BI' | 'fr-BJ' | 'fr-BL' | 'fr-CA' | 'fr-CD' | 'fr-CF' | 'fr-CG' | 'fr-CH' | 'fr-CI' | 'fr-CM' | 'fr-DJ' | 'fr-DZ' | 'fr-FR' | 'fr-GA' | 'fr-GF' | 'fr-GN' | 'fr-GP' | 'fr-GQ' | 'fr-HT' | 'fr-KM' | 'fr-LU' | 'fr-MA' | 'fr-MC' | 'fr-MF' | 'fr-MG' | 'fr-ML' | 'fr-MQ' | 'fr-MR' | 'fr-MU' | 'fr-NC' | 'fr-NE' | 'fr-PF' | 'fr-PM' | 'fr-RE' | 'fr-RW' | 'fr-SC' | 'fr-SN' | 'fr-SY' | 'fr-TD' | 'fr-TG' | 'fr-TN' | 'fr-VU' | 'fr-WF' | 'fr-YT' | 'fur' | 'fur-IT' | 'fy' | 'fy-NL' | 'ga' | 'ga-IE' | 'gd' | 'gd-GB' | 'gl' | 'gl-ES' | 'gsw' | 'gsw-CH' | 'gsw-FR' | 'gsw-LI' | 'gu' | 'gu-IN' | 'guz' | 'guz-KE' | 'gv' | 'gv-IM' | 'ha' | 'ha-GH' | 'ha-NE' | 'ha-NG' | 'haw' | 'haw-US' | 'he' | 'he-IL' | 'hi' | 'hi-IN' | 'hr' | 'hr-BA' | 'hr-HR' | 'hsb' | 'hsb-DE' | 'hu' | 'hu-HU' | 'hy' | 'hy-AM' | 'ia' | 'ia-001' | 'id' | 'id-ID' | 'ig' | 'ig-NG' | 'ii' | 'ii-CN' | 'is' | 'is-IS' | 'it' | 'it-CH' | 'it-IT' | 'it-SM' | 'it-VA' | 'ja' | 'ja-JP' | 'jgo' | 'jgo-CM' | 'jmc' | 'jmc-TZ' | 'jv' | 'jv-ID' | 'ka' | 'ka-GE' | 'kab' | 'kab-DZ' | 'kam' | 'kam-KE' | 'kde' | 'kde-TZ' | 'kea' | 'kea-CV' | 'khq' | 'khq-ML' | 'ki' | 'ki-KE' | 'kk' | 'kk-KZ' | 'kkj' | 'kkj-CM' | 'kl' | 'kl-GL' | 'kln' | 'kln-KE' | 'km' | 'km-KH' | 'kn' | 'kn-IN' | 'ko' | 'ko-KP' | 'ko-KR' | 'kok' | 'kok-IN' | 'ks' | 'ks-IN' | 'ksb' | 'ksb-TZ' | 'ksf' | 'ksf-CM' | 'ksh' | 'ksh-DE' | 'ku' | 'ku-TR' | 'kw' | 'kw-GB' | 'ky' | 'ky-KG' | 'lag' | 'lag-TZ' | 'lb' | 'lb-LU' | 'lg' | 'lg-UG' | 'lkt' | 'lkt-US' | 'ln' | 'ln-AO' | 'ln-CD' | 'ln-CF' | 'ln-CG' | 'lo' | 'lo-LA' | 'lrc' | 'lrc-IQ' | 'lrc-IR' | 'lt' | 'lt-LT' | 'lu' | 'lu-CD' | 'luo' | 'luo-KE' | 'luy' | 'luy-KE' | 'lv' | 'lv-LV' | 'mas' | 'mas-KE' | 'mas-TZ' | 'mer' | 'mer-KE' | 'mfe' | 'mfe-MU' | 'mg' | 'mg-MG' | 'mgh' | 'mgh-MZ' | 'mgo' | 'mgo-CM' | 'mi' | 'mi-NZ' | 'mk' | 'mk-MK' | 'ml' | 'ml-IN' | 'mn' | 'mn-MN' | 'mr' | 'mr-IN' | 'ms' | 'ms-BN' | 'ms-MY' | 'ms-SG' | 'mt' | 'mt-MT' | 'mua' | 'mua-CM' | 'my' | 'my-MM' | 'mzn' | 'mzn-IR' | 'naq' | 'naq-NA' | 'nb' | 'nb-NO' | 'nb-SJ' | 'nd' | 'nd-ZW' | 'nds' | 'nds-DE' | 'nds-NL' | 'ne' | 'ne-IN' | 'ne-NP' | 'nl' | 'nl-AW' | 'nl-BE' | 'nl-BQ' | 'nl-CW' | 'nl-NL' | 'nl-SR' | 'nl-SX' | 'nmg' | 'nmg-CM' | 'nn' | 'nn-NO' | 'nnh' | 'nnh-CM' | 'nus' | 'nus-SS' | 'nyn' | 'nyn-UG' | 'om' | 'om-ET' | 'om-KE' | 'or' | 'or-IN' | 'os' | 'os-GE' | 'os-RU' | 'pa' | 'pa-Arab' | 'pa-Arab-PK' | 'pa-Guru' | 'pa-Guru-IN' | 'pl' | 'pl-PL' | 'prg' | 'prg-001' | 'ps' | 'ps-AF' | 'pt' | 'pt-AO' | 'pt-BR' | 'pt-CH' | 'pt-CV' | 'pt-GQ' | 'pt-GW' | 'pt-LU' | 'pt-MO' | 'pt-MZ' | 'pt-PT' | 'pt-ST' | 'pt-TL' | 'qu' | 'qu-BO' | 'qu-EC' | 'qu-PE' | 'rm' | 'rm-CH' | 'rn' | 'rn-BI' | 'ro' | 'ro-MD' | 'ro-RO' | 'rof' | 'rof-TZ' | 'root' | 'ru' | 'ru-BY' | 'ru-KG' | 'ru-KZ' | 'ru-MD' | 'ru-RU' | 'ru-UA' | 'rw' | 'rw-RW' | 'rwk' | 'rwk-TZ' | 'sah' | 'sah-RU' | 'saq' | 'saq-KE' | 'sbp' | 'sbp-TZ' | 'sd' | 'sd-PK' | 'se' | 'se-FI' | 'se-NO' | 'se-SE' | 'seh' | 'seh-MZ' | 'ses' | 'ses-ML' | 'sg' | 'sg-CF' | 'shi' | 'shi-Latn' | 'shi-Latn-MA' | 'shi-Tfng' | 'shi-Tfng-MA' | 'si' | 'si-LK' | 'sk' | 'sk-SK' | 'sl' | 'sl-SI' | 'smn' | 'smn-FI' | 'sn' | 'sn-ZW' | 'so' | 'so-DJ' | 'so-ET' | 'so-KE' | 'so-SO' | 'sq' | 'sq-AL' | 'sq-MK' | 'sq-XK' | 'sr' | 'sr-Cyrl' | 'sr-Cyrl-BA' | 'sr-Cyrl-ME' | 'sr-Cyrl-RS' | 'sr-Cyrl-XK' | 'sr-Latn' | 'sr-Latn-BA' | 'sr-Latn-ME' | 'sr-Latn-RS' | 'sr-Latn-XK' | 'sv' | 'sv-AX' | 'sv-FI' | 'sv-SE' | 'sw' | 'sw-CD' | 'sw-KE' | 'sw-TZ' | 'sw-UG' | 'ta' | 'ta-IN' | 'ta-LK' | 'ta-MY' | 'ta-SG' | 'te' | 'te-IN' | 'teo' | 'teo-KE' | 'teo-UG' | 'tg' | 'tg-TJ' | 'th' | 'th-TH' | 'ti' | 'ti-ER' | 'ti-ET' | 'tk' | 'tk-TM' | 'to' | 'to-TO' | 'tr' | 'tr-CY' | 'tr-TR' | 'tt' | 'tt-RU' | 'twq' | 'twq-NE' | 'tzm' | 'tzm-MA' | 'ug' | 'ug-CN' | 'uk' | 'uk-UA' | 'ur' | 'ur-IN' | 'ur-PK' | 'uz' | 'uz-Arab' | 'uz-Arab-AF' | 'uz-Cyrl' | 'uz-Cyrl-UZ' | 'uz-Latn' | 'uz-Latn-UZ' | 'vai' | 'vai-Latn' | 'vai-Latn-LR' | 'vai-Vaii' | 'vai-Vaii-LR' | 'vi' | 'vi-VN' | 'vo' | 'vo-001' | 'vun' | 'vun-TZ' | 'wae' | 'wae-CH' | 'wo' | 'wo-SN' | 'xh' | 'xh-ZA' | 'xog' | 'xog-UG' | 'yav' | 'yav-CM' | 'yi' | 'yi-001' | 'yo' | 'yo-BJ' | 'yo-NG' | 'yue' | 'yue-Hans' | 'yue-Hans-CN' | 'yue-Hant' | 'yue-Hant-HK' | 'zgh' | 'zgh-MA' | 'zh' | 'zh-Hans' | 'zh-Hans-CN' | 'zh-Hans-HK' | 'zh-Hans-MO' | 'zh-Hans-SG' | 'zh-Hant' | 'zh-Hant-HK' | 'zh-Hant-MO' | 'zh-Hant-TW' | 'zu' | 'zu-ZA'; /** * We assume that IETF language tags will be extended with sign language codes (as proposed by * http://www.evertype.com/standards/iso639/sign-language.html) eventually, so our language tags * support them already. * * For sign language translations of strings, you can use media URLs pointing to videos or * description pictures. */ export type SignLanguageCode = 'ase' | 'sgn-ase' | 'sgn-ase-US' | 'sgn-GH-EP' | 'sgn-DZ' | 'sgn-US' | 'sgn-AR' | 'sgn-AM' | 'sgn-AU-NT' | 'sgn-AU' | 'sgn-AT' | 'sgn-ID-BA' | 'sgn-BE-VLG' | 'sgn-BE-WAL' | 'sgn-BO' | 'sgn-BR' | 'sgn-GB' | 'sgn-BG' | 'sgn-ES-CT' | 'sgn-TD' | 'sgn-CL' | 'sgn-CN' | 'sgn-CO' | 'sgn-CR' | 'sgn-CZ' | 'sgn-DK' | 'sgn-NL' | 'sgn-EC' | 'sgn-SV' | 'sgn-CA-NU' | 'sgn-ET' | 'sgn-FI' | 'sgn-CA-QC' | 'sgn-FR' | 'sgn-DE' | 'sgn-GH' | 'sgn-GR' | 'sgn-GT' | 'sgn-US-HI' | 'sgn-HK' | 'sgn-IS' | 'sgn-ID' | 'sgn-IN' | 'sgn-IE' | 'sgn-IL' | 'sgn-IT' | 'sgn-JM' | 'sgn-JP' | 'sgn-JO' | 'sgn-KE' | 'sgn-KR' | 'sgn-MY-B' | 'sgn-LV' | 'sgn-LY' | 'sgn-LT' | 'sgn-FR-69' | 'sgn-MY' | 'sgn-MT' | 'sgn-US-MA' | 'sgn-MX-YUC' | 'sgn-MX' | 'sgn-VA' | 'sgn-MN' | 'sgn-MA' | 'sgn-NA' | 'sgn-NP' | 'sgn-NZ' | 'sgn-NI' | 'sgn-NG' | 'sgn-NO' | 'sgn-CA-NS' | 'sgn-GB-KEN' | 'sgn-MY-P' | 'sgn-IR' | 'sgn-PE' | 'sgn-PH' | 'sgn-US-SD' | 'sgn-PL' | 'sgn-PT' | 'sgn-CO-SAP' | 'sgn-PR' | 'sgn-SB' | 'sgn-RO' | 'sgn-RU' | 'sgn-SA' | 'sgn-SE-crp' | 'sgn-SG' | 'sgn-SK' | 'sgn-ZA' | 'sgn-ES' | 'sgn-LK' | 'sgn-SE' | 'sgn-CH-GE' | 'sgn-CH-ZH' | 'sgn-CH-TI' | 'sgn-TW' | 'sgn-TZ' | 'sgn-TH' | 'sgn-TN' | 'sgn-TR' | 'sgn-UG' | 'sgn-UA' | 'sgn-BR-MA' | 'sgn-UY' | 'sgn-VE' | 'sgn-IL-yid' | 'sgn-YU' | 'sgn-ZM' | 'sgn-ZW' | 'sgn-afr-ZA' | 'sgn-chi-TW' | 'sgn-dan-DK' | 'sgn-dut-BE' | 'sgn-dut-NL' | 'sgn-eng-GB' | 'sgn-eng-IE' | 'sgn-eng-US' | 'sgn-fin-FI' | 'sgn-fre-BE' | 'sgn-fre-CA' | 'sgn-fre-FR' | 'sgn-jpn-JP' | 'sgn-nor-NO' | 'sgn-por-PT' | 'sgn-swe-SE'; /** * We assume that IETF language tags will be extended with sign language codes (as proposed by * http://www.evertype.com/standards/iso639/sign-language.html) eventually, so our language tags * support them already. * * For sign language translations of strings, you can use media URLs pointing to videos or * description pictures. */ export const ietfLanguageTagsAndSignLanguageCodes = ietfLanguageTags.concat(signLanguageCodes); /** * We assume that IETF language tags will be extended with sign language codes (as proposed by * http://www.evertype.com/standards/iso639/sign-language.html) eventually, so our language tags * support them already. * * For sign language translations of strings, you can use media URLs pointing to videos or * description pictures. */ export type IetfLanguageTagOrSignLanguageCode = IetfLanguageTag | SignLanguageCode;
the_stack
export const enum Direction { Normal = 'normal', Reverse = 'reverse', Random = 'random', } /** * All available ken burns CSS animations. */ export const animationNames = [ 'ken-burns-bottom-right', 'ken-burns-top-left', 'ken-burns-bottom-left', 'ken-burns-top-right', 'ken-burns-middle-left', 'ken-burns-middle-right', 'ken-burns-top-middle', 'ken-burns-bottom-middle', 'ken-burns-center', ]; const enum Attributes { AnimationDirection = 'animation-direction', AnimationNames = 'animation-names', FadeDuration = 'fade-duration', Images = 'images', SlideDuration = 'slide-duration', } const template = document.createElement('template') as HTMLTemplateElement; template.innerHTML = ` <style> :host { overflow: hidden; position: relative; } div, img { height: 100%; width: 100%; } div { position: absolute; will-change: transform; } img { filter: var(--img-filter); object-fit: cover; } @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } } @keyframes ken-burns-bottom-right { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(-10%, -7%, 0); } } @keyframes ken-burns-top-right { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(-10%, 7%, 0); } } @keyframes ken-burns-top-left { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(10%, 7%, 0); } } @keyframes ken-burns-bottom-left { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(10%, -7%, 0); } } @keyframes ken-burns-middle-left { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(10%, 0, 0); } } @keyframes ken-burns-middle-right { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(-10%, 0, 0); } } @keyframes ken-burns-top-middle { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(0, 10%, 0); } } @keyframes ken-burns-bottom-middle { to { transform: scale3d(1.5, 1.5, 1.5) translate3d(0, -10%, 0); } } @keyframes ken-burns-center { to { transform: scale3d(1.5, 1.5, 1.5); } } </style> `; if (typeof (window as any).ShadyCSS === 'object') { (window as any).ShadyCSS.prepareTemplate(template, 'ken-burns-carousel'); } /** * `ken-burns-carousel` * * Displays a set of images in a smoothly-fading ken burns style carousel. * * @demo ../demo/index.html */ export default class KenBurnsCarousel extends HTMLElement { static get observedAttributes(): string[] { return [ Attributes.AnimationDirection, Attributes.AnimationNames, Attributes.FadeDuration, Attributes.Images, Attributes.SlideDuration, ]; } /** * Specifies the list of ken burns animations to apply to the elements. * * This allows customizing the built-in animations to your liking by overriding * the ones you don't like with custom CSS animations. * * This can also be set via setting the `animation-names`-attribute to a space- * separated list of CSS animation names. * * @type String[] */ animationNames: string[] = animationNames; /** * The direction to play the animations in. * * Defaults to Direction.Random, meaning that with each image the associated ken * burns animation is either played forwards or backwards adding additional visual * diversity. * * This can also be set via the `animation-direction`-attribute. * * @type Direction */ animationDirection: Direction = Direction.Random; private _fadeDuration: number = 2500; private _imgList: string[] = []; private _slideDuration: number = 20000; private _timeout: number = 0; private _zCounter: number = 0; /** * The duration of the crossfading animation in millseconds. * * Must be smaller than the slide duration. Defaults to 2500ms. * This can also be set via the `fade-duration`-attribute. * * @type number */ get fadeDuration() { return this._fadeDuration; } set fadeDuration(val: number) { if (val > this.slideDuration) { throw new RangeError("Fade duration must be smaller than slide duration"); } this._fadeDuration = val; } /** * The list of URLs to the images to display. * * You can either set this property directly, or set the `images`-attribute * to a space-separated list of URLs. * * The element will dirty-check this property to avoid switching to the next image * even if the images set were the same. If you forcefully want to rerender, ensure * you pass a different array because the dirty-check will check for identity. * * @type string[] */ get images(): string[] { return this._imgList; } set images(images: string[]) { if (arraysEqual(this._imgList, images)) { return; } this._imgList = images; if (images.length > 0) { this.animateImages(images); } else { this.stop(); } } /** * The duration of the sliding (or ken burns) animation in millseconds. * * Must be greater than or equal to the fade duration. Defaults to 20s. * This can also be set via the `slide-duration`-attribute. * * @type number */ get slideDuration() { return this._slideDuration; } set slideDuration(val: number) { if (val < this.fadeDuration) { throw new RangeError("Slide duration must be greater than fade duration"); } this._slideDuration = val; } constructor() { super(); this.attachShadow({ mode: 'open' }); this.shadowRoot!.appendChild(template.content.cloneNode(true)); } attributeChangedCallback(name: string, oldVal: string, newVal: string) { switch (name) { case Attributes.AnimationDirection: this.animationDirection = newVal as Direction; break; case Attributes.AnimationNames: this.animationNames = newVal ? newVal.split(' ').filter(name => name) : animationNames; break; case Attributes.FadeDuration: this.fadeDuration = Number(newVal); break; case Attributes.Images: this.images = newVal ? newVal.split(' ').filter(url => url) : []; break; case Attributes.SlideDuration: this.slideDuration = Number(newVal); break; } } connectedCallback() { if (typeof (window as any).ShadyCSS === 'object') { (window as any).ShadyCSS.styleElement(this); } } private animateImages(images: string[]) { const insert = (index: number, img: HTMLImageElement) => { const random = Math.random(); const animationIndex = Math.floor(random * this.animationNames.length); const direction = this.animationDirection === Direction.Random ? random > .5 ? 'normal' : 'reverse' : this.animationDirection; /* * Here we wrap the image element into a surrounding div that is promoted * onto a separate GPU layer using `will-change: transform`. The wrapping div * is then ken-burns-animated instead of the image itself. * * This leads the browser to pre-computing the image filter (--img-filter) * instead of computing it every frame. This can be a massive performance boost * if the filter is expensive. * * See https://developers.google.com/web/updates/2017/10/animated-blur for * more information. */ const wrap = document.createElement('div'); wrap.appendChild(img); wrap.style.animationName = `${this.animationNames[animationIndex]}, fade-in`; wrap.style.animationDuration = `${this.slideDuration}ms, ${this.fadeDuration}ms`; wrap.style.animationDirection = `${direction}, normal`; wrap.style.animationTimingFunction = 'linear, ease'; wrap.style.zIndex = String(this._zCounter++); this.shadowRoot!.appendChild(wrap); setTimeout(() => wrap.remove(), this.slideDuration); // Preload next image and place it in browser cache const nextIndex = (index + 1) % images.length; const next = document.createElement('img') as HTMLImageElement; next.src = images[nextIndex]; this._timeout = setTimeout( () => insert(nextIndex, next), this.slideDuration - this.fadeDuration, ); }; const img = document.createElement('img') as HTMLImageElement; img.src = images[0]; img.onload = () => { /* * Prevent race condition leading to wrong list being displayed. * * The problem arose when you were switching out the image list before * this callback had fired. The callback of a later list could have fired * faster than the one of earlier lists, which lead to the later slideshow * (the right one) being cancelled when the previous one became available. * * We now check whether we're still displaying the list we started * with and only then proceed with actually stopping the old slideshow * and displaying it. */ if (!arraysEqual(this._imgList, images)) { return; } this.stop(); insert(0, img); }; } private stop() { clearTimeout(this._timeout); this._timeout = 0; } } function arraysEqual<T>(arr1: T[] | null, arr2: T[] | null) { // tslint:disable-next-line:triple-equals if (arr1 === arr2 || (!arr1 && !arr2)) { // undefined == null here return true; } if (!arr1 || !arr2 || arr1.length !== arr2.length) { return false; } for (let i = 0; i < arr1.length; i++) { if (arr1[i] !== arr2[i]) { return false; } } return true; }
the_stack
import {DEFAULT_ROTATION_CONFIG, ILogger, HEARTBEAT_TIME_MAX, MESSENGER_ACTION_SERVICE, SOCKET_FILE_NAME, MsgReloadPayload, MsgHeartbeatPayload, MsgSendStrategyPayload, RotationStrategy, MsgPkg} from './domain'; import assert = require('assert'); import * as $ from 'pandora-dollar'; import {MessengerServer, default as Messenger} from 'pandora-messenger'; import moment = require('moment'); import fs = require('mz/fs'); import ms = require('humanize-ms'); const ERROR_MSG_TIMER_BEEN_REMOVED = 'TIMER_BEEN_REMOVED'; const MIN_INTERVAL = 60 * 1000; export class LoggerRotator { protected logger: ILogger = <ILogger> { log: console.log, debug: console.log, warn: console.warn, info: console.info, error: console.error }; protected messengerServer: MessengerServer; protected strategyMap: Map<string, RotationStrategy> = new Map; protected strategyHeartbeat: Map<string, number> = new Map; protected timerClearances: { clear(): void }[] = []; protected heartbeatCheckTime = 10000; protected heartbeatTimeMax = HEARTBEAT_TIME_MAX; constructor(options?: { logger?: ILogger; heartbeatCheckTime?: number; heartbeatTimeMax?: number; }) { options = options || {}; if(options.logger) { this.logger = options.logger; } if(options.heartbeatCheckTime) { this.heartbeatCheckTime = options.heartbeatCheckTime; } if(options.heartbeatTimeMax) { this.heartbeatTimeMax = options.heartbeatTimeMax; } } /** * Start logger rotator service * @return {Promise<void>} */ public async startService(): Promise<void> { this.messengerServer = Messenger.getServer({ name: SOCKET_FILE_NAME }); this.messengerServer.on(MESSENGER_ACTION_SERVICE, (message: MsgPkg, reply) => { if(message.type === 'logger-send-strategy') { const payload: MsgSendStrategyPayload = <MsgSendStrategyPayload> message.payload; const strategy = payload.strategy; try { this.receiveStrategy(strategy); } catch (err) { reply({ error: err }); return; } reply({ error: null, result: 'ok' }); return; } if(message.type === 'logger-heartbeat') { const payload: MsgHeartbeatPayload = <MsgHeartbeatPayload> message.payload; const uuid = payload.uuid; if(this.strategyMap.has(uuid)) { const now = Date.now(); this.strategyHeartbeat.set(uuid, now); } } }); // Support `kill -USR1` to trigger reload logs process.on('SIGUSR1', () => { this.broadcastReload(); }); // Start to handing heartbeat this.startHeartbeatWhile().catch((err) => { this.logger.error(err); throw err; }); await new Promise((resolve) => { this.messengerServer.ready(resolve); }); this.logger.info('[loggerRotator] started service.'); } /** * Receive a log rotator strategy * @param {RotationStrategy} strategy */ public receiveStrategy (strategy: RotationStrategy) { strategy = Object.assign({}, DEFAULT_ROTATION_CONFIG, strategy); const uuid: string = strategy.uuid; assert(!this.strategyMap.has(uuid), 'Strategy uuid ' + uuid + ' already has'); this.strategyMap.set(uuid, strategy); const now = Date.now(); this.strategyHeartbeat.set(uuid, now); this.start(); } /** * Reentry while */ protected start () { if(this.timerClearances.length) { for(let {clear} of this.timerClearances ) { clear(); } this.timerClearances.length = 0; } this.startLogRotateByDateTimer().catch((err) => { if(err.message !== ERROR_MSG_TIMER_BEEN_REMOVED) { this.logger.error(err); } }); this.startLogRotateBySize().catch((err) => { if(err.message !== ERROR_MSG_TIMER_BEEN_REMOVED) { this.logger.error(err); } }); } /** * start heartbeat while * @return {Promise<void>} */ protected async startHeartbeatWhile(): Promise<void> { while (true) { await $.promise.delay(this.heartbeatCheckTime); const now = Date.now(); let needRestart = false; for(let [uuid, beatTime] of this.strategyHeartbeat.entries()) { if((now - beatTime) > this.heartbeatTimeMax) { const strategy = this.strategyMap.get(uuid); this.logger.warn(`logger ${ strategy.file } heartbeat timeout will remove log rotate task`); this.removeStrategyWithoutRestart(uuid); needRestart = true; } } if(needRestart) { this.start(); } } } /** * Start fileSize cutting while * @return {Promise<void>} */ protected async startLogRotateBySize(): Promise<void> { while (true) { const dealyMs = this.caclIntervalForRotateLogBySize(); this.logger.info(`will rotate by size after ${ms(dealyMs)} ${this.getStrategiesRotateBySize().map((x) => x.file).join(', ')}`); await this.delayOnOptimisticLock(dealyMs); await this.rotateLogBySize(); } } /** * Start date cutting while * @return {Promise<void>} */ protected async startLogRotateByDateTimer(): Promise<void> { while (true) { const now = moment(); const ONE_DAY = ms('1d'); // 计算离0点还差的时间间隔 const dealyMs = now.clone().add(ONE_DAY, 'ms').startOf('day').diff(now); this.logger.info(`will rotate by date after ${ms(dealyMs)} ${this.getStrategiesRotateByDate().map((x) => x.file).join(', ')}`); await this.delayOnOptimisticLock(dealyMs); await this.rotateLogByDate(); } } /** * Cut log file by date * @return {Promise<void>} */ protected async rotateLogByDate(): Promise<void> { const strategiesRotateByDate = this.getStrategiesRotateByDate(); this.logger.info(`start rename files:\n${strategiesRotateByDate.map(x => x.file).join('\n')}`); for(let strategy of strategiesRotateByDate) { try { await this.renameLogfile(strategy.file); } catch (err) { this.logger.error(err); } } this.broadcastReload(); } /** * Rename log file, put date as affix * @param {string} logfile * @return {Promise<void>} */ protected async renameLogfile(logfile: string): Promise<void> { const logname = moment().subtract(1, 'days').format('.YYYY-MM-DD'); const newLogfile = logfile + logname; try { const exists = await fs.exists(newLogfile); if (exists) { return this.logger.error(`logfile ${newLogfile} exists!!!`); } await fs.rename(logfile, newLogfile); } catch (err) { err.message = `rename logfile ${logfile} to ${newLogfile} ${err.message}`; this.logger.error(err); } } /** * A cycle to find out which log file needs to cut * @return {Promise<void>} */ protected async rotateLogBySize(): Promise<void> { for(let item of this.getStrategiesRotateBySize()) { try { let logfile = item.file; let maxFileSize = item.maxFileSize; const exists = await fs.exists(logfile); if (exists) { const stat = await fs.stat(logfile); if (stat.size >= maxFileSize) { this.logger.info(`File ${logfile} reach the maximum file size, current size: ${stat.size}, max size: ${maxFileSize}`); await this.rotateBySize(item); } } } catch (e) { e.message = `${e.message}`; this.logger.error(e); } } } /** * Cut log file by size * @param {RotationStrategy} strategy * @return {Promise<void>} */ protected async rotateBySize(strategy: RotationStrategy): Promise<void> { let logfile = strategy.file; let maxFiles = strategy.maxFiles; const exists = await fs.exists(logfile); if (!exists) { return; } // remove max let maxFileName = `${logfile}.${maxFiles}`; const maxExists = await fs.exists(maxFileName); if (maxExists) { await fs.unlink(maxFileName); } // 2->3, 1->2 for (let i = maxFiles - 1; i >= 1; i--) { await this.renameOrDelete(`${logfile}.${i}`, `${logfile}.${i + 1}`); } // logfile => logfile.1 await fs.rename(logfile, `${logfile}.1`); this.broadcastReload(); } /** * If file exist, try backup. If backup filed, remove it. * This operation for the file size cutting only. * @param targetPath * @param backupPath * @return {Promise<void>} */ protected async renameOrDelete(targetPath, backupPath): Promise<void> { const targetExists = await fs.exists(targetPath); if (!targetExists) { return; } const backupExists = await fs.exists(backupPath); if (backupExists) { await fs.unlink(targetPath); } else { await fs.rename(targetPath, backupPath); } } /** * Calculate interval time for rotate log by size * @return {number} */ protected caclIntervalForRotateLogBySize() { const userSpecedDurations = this.getStrategiesRotateBySize().map((x: RotationStrategy) => x.rotateDuration) // the const interval could be Infinity if this.getStrategiesRotateBySize() get an empty array, given a default value next line .concat([MIN_INTERVAL * 10]); const interval = Math.max(Math.min.apply(Math, userSpecedDurations), MIN_INTERVAL); return interval; } /** * Broadcast reload message to all client * @param {string} uuid */ protected broadcastReload(uuid?: string) { this.messengerServer.broadcast(MESSENGER_ACTION_SERVICE, <MsgPkg> { type: 'logger-reload', payload: <MsgReloadPayload> { uuid: uuid } }); } /** * Produce a delay on an optimistic lock, optimistic lock can broke this delay * @param ms * @return {Promise<any>} */ protected delayOnOptimisticLock(ms): Promise<any> { return new Promise((resolve, reject) => { let emit = false; const timer = setTimeout(() => { if(emit) { return; } emit = true; removeTimerClearance(); resolve(); }, ms); const timerClearance = { clear: () => { if(emit) { return; } emit = true; removeTimerClearance(); reject(new Error(ERROR_MSG_TIMER_BEEN_REMOVED)); clearTimeout(timer); } }; const removeTimerClearance = () => { const idx = this.timerClearances.indexOf(timerClearance); if(-1 !== idx) { this.timerClearances.slice(idx, 1); } }; this.timerClearances.push(timerClearance); }); } /** * Get unique strategies list * @return {RotationStrategy[]} */ protected getFilteredStrategiesList(): RotationStrategy[] { const ret = []; const fileHashFilter: Map<string, RotationStrategy> = new Map; for (let strategy of this.strategyMap.values()) { if (!fileHashFilter.has(strategy.file)) { ret.push(strategy); fileHashFilter.set(strategy.file, strategy); } } return ret; } /** * Get all the strategies of the rotate by date * @return {RotationStrategy[]} */ protected getStrategiesRotateByDate(): RotationStrategy[] { const ret = []; for (let strategy of this.getFilteredStrategiesList()) { if (strategy.type === 'date') { ret.push(strategy); } } return ret; } /** * Get all the strategies of the rotate by size * @return {RotationStrategy[]} */ protected getStrategiesRotateBySize(): RotationStrategy[] { const ret = []; for (let strategy of this.getFilteredStrategiesList()) { if (strategy.type === 'size') { ret.push(strategy); } } return ret; } /** * Remove a strategy without restart * @param uuid */ protected removeStrategyWithoutRestart(uuid) { assert(this.strategyMap.has(uuid), 'Could not found strategy uuid ' + uuid + ''); this.strategyMap.delete(uuid); this.strategyHeartbeat.delete(uuid); } }
the_stack
import "jest"; import { inMemory } from "@hickory/in-memory"; import { NavType } from "@hickory/root"; import { createRouter, prepareRoutes } from "@curi/router"; describe("createRouter", () => { describe("constructor", () => { // these tests rely on the fact that the pathname interaction is built-in it("registers routes", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Contact", path: "contact" } ]); let router = createRouter(inMemory, routes); let names = ["Home", "About", "Contact"]; names.forEach(n => { expect(router.route(n)).toBeDefined(); }); }); it("registers nested routes", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Contact", path: "contact", children: [ { name: "Email", path: "email" }, { name: "Phone", path: "phone" } ] } ]); let router = createRouter(inMemory, routes); let names = ["Email", "Phone"]; names.forEach(n => { expect(router.route(n)).toBeDefined(); }); }); it("makes routes available through router.route", () => { let routes = prepareRoutes([{ name: "Home", path: "" }]); let router = createRouter(inMemory, routes); let route = router.route("Home"); expect(route).toMatchObject({ name: "Home" }); }); describe("options", () => { describe("sideEffects", () => { it("calls side effect methods AFTER a response is generated, passing response, navigation, and router", done => { let routes = prepareRoutes([{ name: "All", path: "(.*)" }]); let sideEffect = jest.fn(); let router = createRouter(inMemory, routes, { sideEffects: [sideEffect] }); router.once(({ response, navigation }) => { expect(sideEffect.mock.calls.length).toBe(1); expect(sideEffect.mock.calls[0][0].response).toBe(response); expect(sideEffect.mock.calls[0][0].navigation).toBe(navigation); expect(sideEffect.mock.calls[0][0].router).toBe(router); done(); }); }); it("passes response, navigation, and router object to side effect", done => { let routes = prepareRoutes([{ name: "All", path: "(.*)" }]); let sideEffect = function({ response, navigation, router }) { expect(response).toMatchObject({ name: "All", location: { pathname: "/" } }); expect(navigation).toMatchObject({ action: "push" }); expect(router).toBe(router); done(); }; let router = createRouter(inMemory, routes, { sideEffects: [sideEffect] }); }); }); describe("invisibleRedirects", () => { it("emits redirects by default", () => { let routes = prepareRoutes([ { name: "Start", path: "", respond: () => { return { redirect: { name: "Other" } }; } }, { name: "Other", path: "other" } ]); let call = 0; let logger = ({ response }) => { switch (call++) { case 0: expect(response.name).toBe("Start"); break; } }; let router = createRouter(inMemory, routes, { sideEffects: [logger] }); }); it("does not emit redirects when invisibleRedirects = true", done => { let routes = prepareRoutes([ { name: "Start", path: "", respond: () => { return { redirect: { name: "Other" } }; } }, { name: "Other", path: "other" } ]); let router = createRouter(inMemory, routes, { invisibleRedirects: true }); // the first emitted response is the location that was redirected to router.once(({ response }) => { expect(response.name).toBe("Other"); done(); }); }); it("emits external redirects when invisibleRedirect = true", () => { let routes = prepareRoutes([ { name: "Start", path: "", respond: () => { return { redirect: { externalURL: "https://example.com" } }; } }, { name: "Other", path: "other" } ]); let router = createRouter(inMemory, routes, { invisibleRedirects: true }); let { response } = router.current(); expect(response).toMatchObject({ name: "Start", redirect: { externalURL: "https://example.com" } }); }); }); describe("external", () => { it("gets passed to resolve functions", done => { let external = "hey!"; let routes = prepareRoutes([ { name: "Start", path: "", resolve(match, e) { expect(e).toBe(external); done(); return Promise.resolve(true); } }, { name: "Other", path: "other" }, { name: "Not Found", path: "(.*)" } ]); let router = createRouter(inMemory, routes, { external }); }); it("gets passed to response function", () => { let external = "hey!"; let routes = prepareRoutes([ { name: "Start", path: "", respond({ external: e }) { expect(e).toBe(external); return {}; } }, { name: "Not Found", path: "(.*)" } ]); let router = createRouter(inMemory, routes, { external }); }); it("is available from the router", () => { let external = "hey!"; let routes = prepareRoutes([ { name: "Not Found", path: "(.*)" } ]); let router = createRouter(inMemory, routes, { external }); expect(router.external).toBe(external); }); }); }); describe("sync/async matching", () => { it("does synchronous matching by default", () => { let routes = prepareRoutes([{ name: "Home", path: "" }]); let router = createRouter(inMemory, routes); let after = jest.fn(); router.once(r => { expect(after.mock.calls.length).toBe(0); }); after(); }); it("does asynchronous matching when route.resolve isn't empty", () => { let routes = prepareRoutes([ { name: "Home", path: "", resolve() { return Promise.resolve(); } } ]); let router = createRouter(inMemory, routes); let after = jest.fn(); router.once(r => { expect(after.mock.calls.length).toBe(1); }); after(); }); it("still does synchronous matching when a different route is async", done => { let routes = prepareRoutes([ { name: "Parent", path: "parent", children: [ { name: "Child", path: "child", resolve() { return Promise.resolve(); } } ] } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/parent/child" }] } }); let after = jest.fn(); let navigated = false; router.observe(r => { if (!navigated) { navigated = true; let url = router.url({ name: "Parent" }); router.navigate({ url }); after(); return; } expect(after.mock.calls.length).toBe(0); done(); }); }); }); }); describe("current", () => { describe("sync", () => { it("initial value is an object with resolved response and navigation properties", () => { let routes = prepareRoutes([{ name: "Catch All", path: "(.*)" }]); let router = createRouter(inMemory, routes); expect(router.current()).toMatchObject({ response: { name: "Catch All" }, navigation: { action: "push" } }); }); }); describe("async", () => { it("initial value is an object with undefined response and navigation properties", () => { let routes = prepareRoutes([ { name: "Catch All", path: "(.*)", resolve() { return Promise.resolve(); } } ]); let router = createRouter(inMemory, routes); expect(router.current()).toMatchObject({ response: undefined, navigation: undefined }); }); }); it("response and navigation are the last resolved response and navigation", () => { let routes = prepareRoutes([{ name: "Home", path: "" }]); let router = createRouter(inMemory, routes); router.once(({ response, navigation }) => { expect(router.current()).toMatchObject({ response, navigation }); }); }); it("updates properties when a new response is resolved", done => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" } ]); let router = createRouter(inMemory, routes); let calls = 0; router.observe(({ response, navigation }) => { calls++; expect(router.current()).toMatchObject({ response, navigation }); if (calls === 2) { done(); } else { let url = router.url({ name: "About" }); router.navigate({ url }); } }); }); }); describe("observe(fn)", () => { it("returns a function to unsubscribe when called", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Next", path: "next" }, { name: "Not Found", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let sub1 = jest.fn(); let sub2 = jest.fn(); // wait for the first response to be generated to ensure that both // response handler functions are called when subscribing let unsub1 = router.observe(sub1, { initial: false }); let unsub2 = router.observe(sub2, { initial: false }); expect(sub1.mock.calls.length).toBe(0); expect(sub2.mock.calls.length).toBe(0); unsub1(); let url = router.url({ name: "Next" }); router.navigate({ url }); expect(sub1.mock.calls.length).toBe(0); expect(sub2.mock.calls.length).toBe(1); }); describe("response handler", () => { it("is passed object with response, navigation, and router", done => { let routes = prepareRoutes([{ name: "All", path: "(.*)" }]); let responseHandler = function({ response, navigation, router }) { expect(response).toMatchObject({ name: "All", location: { pathname: "/" } }); expect(navigation).toMatchObject({ action: "push" }); expect(router).toBe(router); done(); }; let router = createRouter(inMemory, routes); router.observe(responseHandler); }); it("is called when response is emitted", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Contact", path: "contact", children: [{ name: "How", path: ":method" }] } ]); let check = ({ response, navigation }) => { expect(response).toMatchObject({ name: "How", params: { method: "mail" } }); expect(navigation).toMatchObject({ action: "push" }); }; let router = createRouter(inMemory, routes); // register before navigation, but don't call with existing response router.observe(check, { initial: false }); let url = router.url({ name: "How", params: { method: "mail" } }); router.navigate({ url }); }); it("is re-called for new responses", done => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Contact", path: "contact" }, { name: "Not Found", path: "(.*)" } ]); let everyTime = jest.fn(); let called = false; let responseHandler = jest.fn(() => { if (called) { expect(everyTime.mock.calls.length).toBe(2); expect(responseHandler.mock.calls.length).toBe(2); done(); } else { called = true; // trigger another navigation to verify that the observer // is called again let url = router.url({ name: "Contact" }); router.navigate({ url }); } }); let router = createRouter(inMemory, routes); router.observe(everyTime); router.observe(responseHandler); }); it("is called BEFORE once() response handlers", done => { // need to use an async route so that handlers are registered before // the initial response is ready let routes = prepareRoutes([ { name: "Home", path: "", resolve() { return Promise.resolve(); } }, { name: "Catch All", path: "(.*)" } ]); let oneTime = jest.fn(); let called = false; let responseHandler = jest.fn(() => { expect(oneTime.mock.calls.length).toBe(0); done(); }); let router = createRouter(inMemory, routes); router.once(oneTime); router.observe(responseHandler); }); describe("matched route is async", () => { it("is called AFTER promises have resolved", done => { let promiseResolved = false; let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Contact", path: "contact", children: [ { name: "How", path: ":method", resolve() { promiseResolved = true; return Promise.resolve(promiseResolved); } } ] } ]); let check = response => { expect(promiseResolved).toBe(true); done(); }; let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/contact/phone" }] } }); router.observe(check); }); it("does not emit responses for cancelled navigation", done => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Contact", path: "contact", children: [ { name: "How", path: ":method", resolve() { return Promise.resolve(); } } ] } ]); let check = ({ response }) => { expect(response.params.method).toBe("mail"); done(); }; let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/contact/fax" }] } }); router.observe(check); let phoneURL = router.url({ name: "How", params: { method: "phone" } }); let mailURL = router.url({ name: "How", params: { method: "mail" } }); router.navigate({ url: phoneURL }); router.navigate({ url: mailURL }); }); }); }); describe("response handler options", () => { describe("{ initial: true } (default)", () => { it("immediately called with most recent response/navigation", () => { let routes = prepareRoutes([{ name: "Home", path: "" }]); let sub = jest.fn(); let router = createRouter(inMemory, routes); let { response, navigation } = router.current(); router.observe(sub, { initial: true }); expect(sub.mock.calls.length).toBe(1); let { response: mockResponse, navigation: mockNavigation } = sub.mock.calls[0][0]; expect(mockResponse).toBe(response); expect(mockNavigation).toBe(navigation); }); it("[async] immediately called if initial response has resolved", done => { let routes = prepareRoutes([ { name: "Home", path: "", resolve() { return Promise.resolve(); } } ]); let sub = jest.fn(); let router = createRouter(inMemory, routes); router.once(() => { router.observe(sub, { initial: true }); expect(sub.mock.calls.length).toBe(1); done(); }); }); it("[async] not immediately called if initial response hasn't resolved", () => { let routes = prepareRoutes([ { name: "Home", path: "", resolve() { return Promise.resolve(); } } ]); let sub = jest.fn(); let router = createRouter(inMemory, routes); router.observe(sub, { initial: true }); expect(sub.mock.calls.length).toBe(0); }); }); describe("{ initial: false }", () => { it("has response, is not immediately called", done => { let routes = prepareRoutes([{ name: "Home", path: "" }]); let everyTime = jest.fn(); let router = createRouter(inMemory, routes); router.once(() => { router.observe(everyTime, { initial: false }); expect(everyTime.mock.calls.length).toBe(0); done(); }); }); it("is called AFTER next navigation", done => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Catch All", path: "(.*)" } ]); let everyTime = jest.fn(({ response }) => { expect(response.name).toBe("About"); done(); }); let router = createRouter(inMemory, routes); router.once(() => { router.observe(everyTime, { initial: false }); expect(everyTime.mock.calls.length).toBe(0); let url = router.url({ name: "About" }); router.navigate({ url }); }); }); }); }); }); describe("once(fn)", () => { describe("response handler", () => { it("is passed object with response, navigation, and router", done => { let routes = prepareRoutes([{ name: "All", path: "(.*)" }]); let responseHandler = function({ response, navigation, router }) { expect(response).toMatchObject({ name: "All", location: { pathname: "/" } }); expect(navigation).toMatchObject({ action: "push" }); expect(router).toBe(router); done(); }; let router = createRouter(inMemory, routes); router.once(responseHandler); }); it("is called when response is emitted", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Contact", path: "contact" }, { name: "Not Found", path: "(.*)" } ]); let oneTime = jest.fn(); let router = createRouter(inMemory, routes); router.once(oneTime); expect(oneTime.mock.calls.length).toBe(1); }); it("isn't re-called for new responses", () => { // let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Contact", path: "contact" }, { name: "Not Found", path: "(.*)" } ]); let firstOnce = jest.fn(); let secondOnce = jest.fn(); let router = createRouter(inMemory, routes); router.once(firstOnce); expect(firstOnce.mock.calls.length).toBe(1); expect(firstOnce.mock.calls[0][0].response).toMatchObject({ name: "Home" }); let url = router.url({ name: "Contact" }); router.navigate({ url }); // register a second one time response handler // to verify that another response is emitted, // but first one timer isn't re-called router.once(secondOnce); expect(secondOnce.mock.calls.length).toBe(1); expect(secondOnce.mock.calls[0][0].response).toMatchObject({ name: "Contact" }); expect(firstOnce.mock.calls.length).toBe(1); }); it("is called AFTER observe() response handlers", done => { // need to use an async route so that handlers are registered before // the initial response is ready let routes = prepareRoutes([ { name: "Home", path: "", resolve() { return Promise.resolve(); } }, { name: "Catch All", path: "(.*)" } ]); let oneTime = jest.fn(() => { expect(responseHandler.mock.calls.length).toBe(1); done(); }); let called = false; let responseHandler = jest.fn(); let router = createRouter(inMemory, routes); router.once(oneTime); router.observe(responseHandler); }); describe("matched route is async", () => { it("is called AFTER promises have resolved", done => { let promiseResolved = false; let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Contact", path: "contact", children: [ { name: "How", path: ":method", resolve() { promiseResolved = true; return Promise.resolve(promiseResolved); } } ] } ]); let check = response => { expect(promiseResolved).toBe(true); done(); }; let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/contact/phone" }] } }); router.once(check); }); it("does not emit responses for cancelled navigation", done => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Contact", path: "contact", children: [ { name: "How", path: ":method", resolve() { return Promise.resolve(); } } ] } ]); let check = ({ response }) => { expect(response.params.method).toBe("mail"); done(); }; let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/contact/fax" }] } }); router.once(check); let phoneURL = router.url({ name: "How", params: { method: "phone" } }); let mailURL = router.url({ name: "How", params: { method: "mail" } }); router.navigate({ url: phoneURL }); router.navigate({ url: mailURL }); }); }); }); describe("response handler options", () => { describe("{ initial: true } (default)", () => { it("immediately called with most recent response/navigation", () => { let routes = prepareRoutes([{ name: "Home", path: "" }]); let sub = jest.fn(); let router = createRouter(inMemory, routes); let { response, navigation } = router.current(); router.once(sub, { initial: true }); expect(sub.mock.calls.length).toBe(1); let { response: mockResponse, navigation: mockNavigation } = sub.mock.calls[0][0]; expect(mockResponse).toBe(response); expect(mockNavigation).toBe(navigation); }); it("[async] immediately called if initial response has resolved", done => { let routes = prepareRoutes([ { name: "Home", path: "", resolve() { return Promise.resolve(); } } ]); let sub = jest.fn(); let router = createRouter(inMemory, routes); router.once(() => { router.once(sub, { initial: true }); expect(sub.mock.calls.length).toBe(1); done(); }); }); it("[async] not immediately called if initial response hasn't resolved", () => { let routes = prepareRoutes([ { name: "Home", path: "", resolve() { return Promise.resolve(); } } ]); let sub = jest.fn(); let router = createRouter(inMemory, routes); router.once(sub, { initial: true }); expect(sub.mock.calls.length).toBe(0); }); }); describe("{ initial: false }", () => { it("has response, is not immediately called", done => { let routes = prepareRoutes([{ name: "Home", path: "" }]); let oneTime = jest.fn(); let router = createRouter(inMemory, routes); router.once(() => { router.once(oneTime, { initial: false }); expect(oneTime.mock.calls.length).toBe(0); done(); }); }); it("is called AFTER next navigation", done => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Catch All", path: "(.*)" } ]); let oneTime = jest.fn(({ response }) => { expect(response.name).toBe("About"); done(); }); let router = createRouter(inMemory, routes); router.once(() => { router.once(oneTime, { initial: false }); expect(oneTime.mock.calls.length).toBe(0); let url = router.url({ name: "About" }); router.navigate({ url }); }); }); }); }); }); describe("url()", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Contact", path: "contact", children: [{ name: "Method", path: ":method" }] }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); it("generates the expected pathname", () => { let url = router.url({ name: "Contact" }); router.navigate({ url }); expect(url).toEqual("/contact"); }); it("uses params to create pathname", () => { let url = router.url({ name: "Method", params: { method: "fax" } }); router.navigate({ url }); expect(url).toEqual("/contact/fax"); }); it("returns URL with no pathname if name is not provided", () => { let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/test" }] } }); let url = router.url({ hash: "test" }); expect(url).toEqual("#test"); }); it("includes the provided hash", () => { let url = router.url({ name: "Home", hash: "trending" }); expect(url).toEqual("/#trending"); }); it("includes the provided query", () => { let url = router.url({ name: "Home", query: "key=value" }); expect(url).toEqual("/?key=value"); }); }); describe("navigate()", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Contact", path: "contact", children: [{ name: "Method", path: ":method" }] }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let mockNavigate = jest.fn(); router.history.navigate = mockNavigate; afterEach(() => { mockNavigate.mockReset(); }); describe("navigation method", () => { it("lets the history object decide if no method is provided", () => { let router = createRouter(inMemory, routes); expect(() => { let url = router.url({ name: "Contact" }); router.navigate({ url }); }).not.toThrow(); }); it("anchor", () => { let url = router.url({ name: "Contact" }); router.navigate({ url, method: "anchor" }); expect(mockNavigate.mock.calls[0][1]).toBe("anchor"); }); it("push", () => { let url = router.url({ name: "Contact" }); router.navigate({ url, method: "push" }); expect(mockNavigate.mock.calls[0][1]).toBe("push"); }); it("replace", () => { let url = router.url({ name: "Contact" }); router.navigate({ url, method: "replace" }); expect(mockNavigate.mock.calls[0][1]).toBe("replace"); }); it("throws if given a bad navigation type", () => { let router = createRouter(inMemory, routes); expect(() => { let url = router.url({ name: "Contact" }); router.navigate({ url, method: "BAAAAAAD" as NavType }); }).toThrow(); }); }); it("includes the provided state", () => { let state = { test: true }; let url = router.url({ name: "Home" }); router.navigate({ url, state }); expect(mockNavigate.mock.calls[0][0]).toMatchObject({ state }); }); it("location inherits pathname when navigating to URL with no pathname", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Contact", path: "contact", children: [{ name: "Method", path: ":method" }] }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/contact/phone" }] } }); let url = router.url({ hash: "test" }); router.navigate({ url }); let { response } = router.current(); expect(response.location).toMatchObject({ pathname: "/contact/phone" }); }); describe("return value", () => { it("returns a function if a finished property is passed to navigate", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Contact", path: "contact", children: [{ name: "Method", path: ":method" }] }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let url = router.url({ name: "Contact" }); let fn = router.navigate({ url, finished: () => {} }); expect(fn).not.toBeUndefined(); }); it("returns a function if a cancelled property is passed to navigate", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Contact", path: "contact", children: [{ name: "Method", path: ":method" }] }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let url = router.url({ name: "Contact" }); let fn = router.navigate({ url, cancelled: () => {} }); expect(fn).not.toBeUndefined(); }); it("returns undefind if neither finished nor cancelled properties are provided", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Contact", path: "contact", children: [{ name: "Method", path: ":method" }] }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let url = router.url({ name: "Contact" }); let fn = router.navigate({ url }); expect(fn).toBeUndefined(); }); }); describe("cancelling a navigation", () => { it("calls the navigation's cancelled function", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Slow", path: "slow", resolve() { // takes 500ms to resolve return new Promise(resolve => { setTimeout(() => { resolve("done"); }, 500); }); } }, { name: "Fast", path: "fast", resolve() { return Promise.resolve("complete"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancelled = jest.fn(); let slowURL = router.url({ name: "Slow" }); router.navigate({ url: slowURL, cancelled }); expect(cancelled.mock.calls.length).toBe(0); let fastURL = router.url({ name: "Fast" }); router.navigate({ url: fastURL }); expect(cancelled.mock.calls.length).toBe(1); }); it("does not call the previous navigation's cancelled function", done => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Loader", path: "loader/:id", resolve() { return Promise.resolve("complete"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancelled = jest.fn(); let oneURL = router.url({ name: "Loader", params: { id: 1 } }); router.navigate({ url: oneURL, cancelled }); router.once( ({ response }) => { // verify this is running after the first navigation completes expect(response.name).toBe("Loader"); expect(cancelled.mock.calls.length).toBe(0); let twoURL = router.url({ name: "Loader", params: { id: 2 } }); router.navigate({ url: twoURL }); expect(cancelled.mock.calls.length).toBe(0); done(); }, { initial: false } ); }); }); describe("finishing a navigation", () => { it("does not calls the navigation's finished function when the navigation is cancelled", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Slow", path: "slow", resolve() { // takes 500ms to resolve return new Promise(resolve => { setTimeout(() => { resolve("done"); }, 500); }); } }, { name: "Fast", path: "fast", resolve() { return Promise.resolve("complete"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let finished = jest.fn(); let slowURL = router.url({ name: "Slow" }); router.navigate({ url: slowURL, finished }); let fastURL = router.url({ name: "Fast" }); router.navigate({ url: fastURL }); expect(finished.mock.calls.length).toBe(0); }); it("calls the navigation's finished function", done => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Loader", path: "loader/:id", resolve() { return Promise.resolve("complete"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let finished = jest.fn(); let url = router.url({ name: "Loader", params: { id: 1 } }); router.navigate({ url, finished }); router.once( ({ response }) => { // verify this is running after the first navigation completes expect(response.name).toBe("Loader"); expect(finished.mock.calls.length).toBe(1); done(); }, { initial: false } ); }); }); describe("cancelling callbacks", () => { it("does not call finish callback after navigation finishes", done => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Loader", path: "loader/:id", resolve() { return Promise.resolve("complete"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let finished = jest.fn(); let loaderURL = router.url({ name: "Loader", params: { id: 1 } }); let cancelCallbacks = router.navigate({ url: loaderURL, finished }) as () => void; cancelCallbacks(); router.once( ({ response }) => { // verify this is running after the first navigation completes expect(response.name).toBe("Loader"); expect(finished.mock.calls.length).toBe(0); done(); }, { initial: false } ); }); it("does not call cancel callback after navigation is cancelled", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Slow", path: "slow", resolve() { // takes 500ms to resolve return new Promise(resolve => { setTimeout(() => { resolve("done"); }, 500); }); } }, { name: "Fast", path: "fast", resolve() { return Promise.resolve("complete"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancelled = jest.fn(); let slowURL = router.url({ name: "Slow" }); let cancelCallbacks = router.navigate({ url: slowURL, cancelled }) as () => void; cancelCallbacks(); let fastURL = router.url({ name: "Fast" }); router.navigate({ url: fastURL }); expect(cancelled.mock.calls.length).toBe(0); }); }); }); describe("cancel(fn)", () => { it("does not call function for sync routes", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancellable = jest.fn(); router.cancel(cancellable); let url = router.url({ name: "About" }); router.navigate({ url }); let { response } = router.current(); // just to verify that navigation did occur expect(response.name).toBe("About"); expect(cancellable.mock.calls.length).toBe(0); }); it("calls function with cancel fn when navigating to async routes", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about", resolve() { return Promise.resolve("wait"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancellable = jest.fn(); router.cancel(cancellable); let url = router.url({ name: "About" }); router.navigate({ url }); // called immediately after navigation expect(cancellable.mock.calls.length).toBe(1); expect(typeof cancellable.mock.calls[0][0]).toBe("function"); }); describe("another navigation", () => { it("stays active when a second async navigation starts", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about", resolve() { return new Promise(resolve => { setTimeout(() => { resolve("about"); }, 50); }); } }, { name: "Contact", path: "contact", resolve() { return new Promise(resolve => { setTimeout(() => { resolve("contact"); }, 50); }); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancellable = jest.fn(); router.cancel(cancellable); let aboutURL = router.url({ name: "About" }); router.navigate({ url: aboutURL }); expect(cancellable.mock.calls.length).toBe(1); let contactURL = router.url({ name: "Contact" }); router.navigate({ url: contactURL }); expect(cancellable.mock.calls.length).toBe(1); }); it("is cancelled when a sync navigation starts", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about", resolve() { return new Promise(resolve => { setTimeout(() => { resolve("about"); }, 50); }); } }, { name: "Contact", path: "contact" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancellable = jest.fn(); router.cancel(cancellable); let aboutURL = router.url({ name: "About" }); router.navigate({ url: aboutURL }); expect(cancellable.mock.calls.length).toBe(1); expect(typeof cancellable.mock.calls[0][0]).toBe("function"); let contactURL = router.url({ name: "Contact" }); router.navigate({ url: contactURL }); expect(cancellable.mock.calls.length).toBe(2); expect(cancellable.mock.calls[1][0]).toBeUndefined(); }); }); describe("non-cancelled navigation", () => { it("calls function with no args once async actions are complete", done => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about", resolve() { return Promise.resolve("wait"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancellable = jest.fn(); router.cancel(cancellable); let aboutURL = router.url({ name: "About" }); router.navigate({ url: aboutURL }); router.once( ({ response }) => { expect(response.name).toBe("About"); // second call is for deactivation expect(cancellable.mock.calls.length).toBe(2); expect(cancellable.mock.calls[1][0]).toBeUndefined(); done(); }, { initial: false } ); }); }); describe("cancelling active navigation", () => { it("deactivates immediately if cancel function is called", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about", resolve() { return Promise.resolve("wait"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancel; let cancellable = jest.fn(cancelFn => { cancel = cancelFn; }); router.cancel(cancellable); let aboutURL = router.url({ name: "About" }); router.navigate({ url: aboutURL }); // called immediately after navigation expect(cancellable.mock.calls.length).toBe(1); cancel(); // called after navigation is cancelled expect(cancellable.mock.calls.length).toBe(2); }); it("doesn't change locations", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about", resolve() { return Promise.resolve("wait"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancel; let cancellable = jest.fn(cancelFn => { cancel = cancelFn; }); router.cancel(cancellable); let { response: beforeResponse } = router.current(); expect(beforeResponse.name).toBe("Home"); let aboutURL = router.url({ name: "About" }); router.navigate({ url: aboutURL }); // called immediately after navigation expect(cancellable.mock.calls.length).toBe(1); cancel(); let { response: afterResponse } = router.current(); expect(afterResponse.name).toBe("Home"); }); }); it("returns a function to stop being called", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about", resolve() { return Promise.resolve("wait"); } }, { name: "Contact", path: "contact", resolve() { return Promise.resolve("wait"); } }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); let cancellable = jest.fn(); let stopCancelling = router.cancel(cancellable); let aboutURL = router.url({ name: "About" }); router.navigate({ url: aboutURL }); expect(cancellable.mock.calls.length).toBe(1); stopCancelling(); let url = router.url({ name: "Contact" }); router.navigate({ url }); expect(cancellable.mock.calls.length).toBe(1); }); }); describe("route matching", () => { describe("no matching routes", () => { it("no response is emitted", () => { // suppress the warning let realWarn = console.warn; console.warn = () => {}; let routes = prepareRoutes([]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/test" }] } }); let observer = jest.fn(); router.once(observer); expect(observer.mock.calls.length).toBe(0); console.warn = realWarn; }); it("warns that no route matched", () => { let realWarn = console.warn; let fakeWarn = (console.warn = jest.fn()); let routes = prepareRoutes([]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/test" }] } }); let observer = jest.fn(); router.once(observer); expect(fakeWarn.mock.calls[0][0]).toBe( `The current location (/test) has no matching route, so a response could not be emitted. A catch-all route ({ path: "(.*)" }) can be used to match locations with no other matching route.` ); console.warn = realWarn; }); }); describe("response generation", () => { describe("response object", () => { describe("properties", () => { describe("location", () => { it("is the location used to match routes", () => { let routes = prepareRoutes([{ name: "Catch All", path: "(.*)" }]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/other-page" }] } }); let { response } = router.current(); expect(response.location).toBe(router.history.location); }); }); describe("body", () => { it("exists on response as undefined if not set by route.respond()", () => { let routes = prepareRoutes([ { name: "Test", path: "test" } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/test" }] } }); let { response } = router.current(); expect(response.hasOwnProperty("body")).toBe(true); expect(response.body).toBeUndefined(); }); it("is the body value of the object returned by route.respond()", () => { let body = () => "anybody out there?"; let routes = prepareRoutes([ { name: "Test", path: "test", respond: () => { return { body: body }; } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/test" }] } }); let { response } = router.current(); expect(response.body).toBe(body); }); }); describe("meta", () => { it("exists on the response as undefined if not set by route.respond()", () => { let routes = prepareRoutes([ { name: "Contact", path: "contact", children: [ { name: "Email", path: "email" }, { name: "Phone", path: "phone" } ] } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/contact" }] } }); let { response } = router.current(); expect(response.hasOwnProperty("meta")).toBe(true); expect(response.meta).toBeUndefined(); }); it("is the meta value of object returned by route.respond()", () => { let routes = prepareRoutes([ { name: "A Route", path: "", respond: () => { return { meta: { title: "A Route", status: 451 } }; } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/" }] } }); let { response } = router.current(); expect(response.meta).toMatchObject({ title: "A Route", status: 451 }); }); }); describe("data", () => { it("exists on response as undefined if not set by route.respond()", () => { let routes = prepareRoutes([ { name: "A Route", path: "" } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/" }] } }); let { response } = router.current(); expect(response.hasOwnProperty("data")).toBe(true); expect(response.data).toBeUndefined(); }); it("is the data value of the object returned by route.respond()", () => { let routes = prepareRoutes([ { name: "A Route", path: "", respond: () => { return { data: { test: "value" } }; } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/" }] } }); let { response } = router.current(); expect(response.data).toMatchObject({ test: "value" }); }); }); describe("name", () => { it("is the name of the best matching route", () => { let routes = prepareRoutes([ { name: "A Route", path: "a-route" } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/a-route" }] } }); let { response } = router.current(); expect(response.name).toBe("A Route"); }); }); describe("params", () => { it("includes params from partially matched routes", () => { let routes = prepareRoutes([ { name: "State", path: ":state", children: [ { name: "City", path: ":city" } ] } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/MT/Bozeman" }] } }); let { response } = router.current(); expect(response.params).toEqual({ state: "MT", city: "Bozeman" }); }); it("overwrites param name conflicts", () => { let routes = prepareRoutes([ { name: "One", path: ":id", children: [{ name: "Two", path: ":id" }] } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/1/2" }] } }); let { response } = router.current(); expect(response.params["id"]).toBe("2"); }); describe("parsing params", () => { it("uses route.params to parse params", () => { let routes = prepareRoutes([ { name: "number", path: ":num", params: { num: n => parseInt(n, 10) } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/123" }] } }); let { response } = router.current(); expect(response.params).toEqual({ num: 123 }); }); it("parses params from parent routes", () => { let routes = prepareRoutes([ { name: "first", path: ":first", children: [ { name: "second", path: ":second", params: { second: n => parseInt(n, 10) } } ], params: { first: n => parseInt(n, 10) } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/123/456" }] } }); let { response } = router.current(); expect(response.params).toEqual({ first: 123, second: 456 }); }); it("decodes param using decodeURIComponent if param has no function", () => { let routes = prepareRoutes([ { name: "combo", path: ":first/:second", params: { first: n => parseInt(n, 10) } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/123/test%20ing" }] } }); let { response } = router.current(); expect(response.params).toEqual({ first: 123, second: "test ing" }); }); it("does not include optional param if it does not exist", () => { let routes = prepareRoutes([ { name: "Profile", path: "user/:firstName/:lastName?" } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/user/tina" }] } }); let { response } = router.current(); expect(response.name).toBe("Profile"); expect("firstName" in response.params).toBe(true); expect("lastName" in response.params).toBe(false); }); it("throws if param parser throws", () => { let routes = prepareRoutes([ { name: "number", path: "(.*)" } ]); expect(() => { let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/%" }] } }); }).toThrow(); }); }); }); describe("redirect", () => { it("contains the expected properties", () => { let routes = prepareRoutes([ { name: "A Route", path: "", respond: () => { return { redirect: { name: "B Route", params: { id: "bee" }, hash: "bay", query: "type=honey", state: { why: "not" } } }; } }, { name: "B Route", path: "b/:id" } ]); let firstCall = true; let logger = ({ response }) => { if (firstCall) { expect(response.redirect).toMatchObject({ hash: "bay", query: "type=honey", url: "/b/bee?type=honey#bay", state: { why: "not" }, name: "B Route", params: { id: "bee" } }); firstCall = false; } }; let router = createRouter(inMemory, routes, { sideEffects: [logger], history: { locations: [{ url: "/" }] } }); }); it("works with redirect that provides URL", () => { let routes = prepareRoutes([ { name: "A Route", path: "", respond: () => { return { redirect: { externalURL: "/some-page" } }; } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/" }] } }); let { response } = router.current(); expect(response.redirect).toMatchObject({ externalURL: "/some-page" }); }); it("works with external redirects", () => { let routes = prepareRoutes([ { name: "A Route", path: "", respond: () => { return { redirect: { externalURL: "https://example.com" } }; } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/" }] } }); let { response } = router.current(); expect(response.redirect).toMatchObject({ externalURL: "https://example.com" }); }); }); describe("[invalid properties]", () => { it("warns when returned object has an invalid property", () => { let realWarn = console.warn; let fakeWarn = (console.warn = jest.fn()); let routes = prepareRoutes([ { name: "Contact", path: "contact", // @ts-ignore respond() { return { bad: "property" }; } } ]); expect(fakeWarn.mock.calls.length).toBe(0); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/contact" }] } }); let { response } = router.current(); expect(fakeWarn.mock.calls.length).toBe(1); // @ts-ignore expect(response.bad).toBeUndefined(); console.warn = realWarn; }); }); describe("[undefined properties]", () => { it("are set to undefined on the response", () => { let routes = prepareRoutes([ { name: "A Route", path: "", respond: () => { return { body: "body", meta: undefined }; } } ]); let router = createRouter(inMemory, routes); let { response } = router.current(); expect(response.name).toBe("A Route"); expect(response.hasOwnProperty("body")).toBe(true); expect(response.hasOwnProperty("meta")).toBe(true); expect(response.meta).toBeUndefined(); }); }); describe("route.respond doesn't return anything", () => { it("warns", () => { let realWarn = console.warn; console.warn = jest.fn(); let routes = prepareRoutes([ { name: "A Route", path: "", // @ts-ignore respond: () => {} } ]); let router = createRouter(inMemory, routes); expect((console.warn as jest.Mock).mock.calls[0][0]).toBe( `"A Route"'s response function did not return anything. Did you forget to include a return statement?` ); console.warn = realWarn; }); }); }); }); describe("resolve", () => { describe("calling functions", () => { it("is called with location, matched route name, and params", done => { let spy = jest.fn(route => { expect(route).toMatchObject({ params: { anything: "hello" }, location: { pathname: "/hello", query: "one=two" }, name: "Catch All" }); done(); return Promise.resolve(); }); let routes = prepareRoutes([ { name: "Catch All", path: ":anything", resolve: spy } ]); createRouter(inMemory, routes, { history: { locations: [{ url: "/hello?one=two" }] } }); }); it("is called with external provided to router", done => { let external = "test"; let spy = jest.fn((_, e) => { expect(e).toBe(external); done(); return Promise.resolve(); }); let routes = prepareRoutes([ { name: "Catch All", path: ":anything", resolve: spy } ]); createRouter(inMemory, routes, { external, history: { locations: [{ url: "/hello?one=two" }] } }); }); }); describe("respond", () => { it("is not called if the navigation has been cancelled", done => { let responseSpy = jest.fn(); let firstHasResolved = false; let spy = jest.fn(() => { return new Promise((resolve, reject) => { setTimeout(() => { firstHasResolved = true; resolve(); }, 15); }); }); let routes = prepareRoutes([ { name: "First", path: "first", resolve: spy, respond: responseSpy }, { name: "Second", path: "second", respond: () => { expect(firstHasResolved).toBe(true); expect(spy.mock.calls.length).toBe(2); expect(responseSpy.mock.calls.length).toBe(0); done(); return {}; }, // re-use the spy so that this route's response // fn isn't call until after the first route's spy // fn has resolved resolve: spy } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/first" }] } }); let url = router.url({ name: "Second" }); router.navigate({ url }); }); describe("resolved", () => { it("is null when route has no resolve functions", () => { let routes = prepareRoutes([ { name: "Catch All", path: ":anything", respond: ({ resolved }) => { expect(resolved).toBe(null); return {}; } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/hello?one=two" }] } }); }); it("is null when a resolve function throws", () => { let routes = prepareRoutes([ { name: "Catch All", path: ":anything", resolve() { return Promise.reject("woops!"); }, respond: ({ resolved }) => { expect(resolved).toBe(null); return {}; } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/hello?one=two" }] } }); }); it("is the resolve results", () => { let routes = prepareRoutes([ { name: "Catch All", path: ":anything", respond: ({ resolved }) => { expect(resolved.test).toBe(1); expect(resolved.yo).toBe("yo!"); return {}; }, resolve() { return Promise.resolve({ test: 1, yo: "yo!" }); } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/hello?one=two" }] } }); }); }); describe("error", () => { it("receives the error rejected by a resolve function", done => { let spy = jest.fn(({ error }) => { expect(error).toBe("rejected"); done(); return {}; }); let routes = prepareRoutes([ { name: "Catch All", path: ":anything", respond: spy, resolve() { return Promise.reject("rejected"); } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/hello?one=two" }] } }); }); it("is null when all resolve functions succeed", done => { let spy = jest.fn(({ error }) => { expect(error).toBe(null); done(); return {}; }); let routes = prepareRoutes([ { name: "Catch All", path: ":anything", respond: spy, resolve() { return Promise.resolve("hurray!"); } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/hello?one=two" }] } }); }); }); describe("match", () => { it("receives the response properties based on the matched route", () => { let routes = prepareRoutes([ { name: "Catch All", path: ":anything", respond: props => { expect(props.match).toMatchObject({ name: "Catch All", params: { anything: "hello" }, location: { pathname: "/hello", query: "one=two" } }); return {}; } } ]); let router = createRouter(inMemory, routes, { history: { locations: [{ url: "/hello?one=two" }] } }); }); }); }); }); describe("redirect responses", () => { // these tests mock history.navigate to track how many times // it is called. it("automatically redirects for internal redirects", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Redirects", path: "redirects", respond: () => { return { redirect: { name: "Other" } }; } }, { name: "Other", path: "other" } ]); let router = createRouter(inMemory, routes); let history = router.history; let realNavigate = history.navigate; history.navigate = jest.fn((...args) => { realNavigate(...args); }); expect((history.navigate as jest.Mock).mock.calls.length).toBe(0); let url = router.url({ name: "Redirects" }); router.navigate({ url }); expect((history.navigate as jest.Mock).mock.calls.length).toBe(2); }); it("does not try to redirect to external redirects", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "Redirects", path: "redirects", respond: () => { return { redirect: { externalURL: "https://example.com" } }; } }, { name: "Other", path: "other" } ]); let router = createRouter(inMemory, routes); let history = router.history; let realNavigate = history.navigate; history.navigate = jest.fn((...args) => { realNavigate(...args); }); expect((history.navigate as jest.Mock).mock.calls.length).toBe(0); let redirectsURL = router.url({ name: "Redirects" }); router.navigate({ url: redirectsURL }); expect((history.navigate as jest.Mock).mock.calls.length).toBe(1); let otherURL = router.url({ name: "Other" }); router.navigate({ url: otherURL }); expect((history.navigate as jest.Mock).mock.calls.length).toBe(2); }); it("triggers a replace navigation AFTER emitting initial response", done => { let routes = prepareRoutes([ { name: "A Route", path: "", respond: () => { return { redirect: { name: "B Route" } }; } }, { name: "B Route", path: "somewhere-else" } ]); let calls = 0; let router = createRouter(inMemory, routes, { sideEffects: [ ({ response, navigation }) => { switch (calls++) { case 0: expect(response.name).toBe("A Route"); break; case 1: expect(response.name).toBe("B Route"); expect(navigation.action).toBe("replace"); done(); } } ] }); }); }); }); }); describe("destroy", () => { it("doesn't navigate after destroyed", () => { let routes = prepareRoutes([ { name: "Home", path: "" }, { name: "About", path: "about" }, { name: "Catch All", path: "(.*)" } ]); let router = createRouter(inMemory, routes); expect(router.current()).toMatchObject({ response: { name: "Home" } }); router.destroy(); router.navigate({ url: "/about" }); expect(router.current()).toMatchObject({ response: { name: "Home" } }); }); }); });
the_stack
import { MeshPlatform, MeshTag, MeshTenant, MeshTenantCost, } from "../mesh/mesh-tenant.model.ts"; import { isSubscription, Tag } from "./azure.model.ts"; import { AzureCliFacade } from "./azure-cli-facade.ts"; import { MeshAdapter } from "../mesh/mesh-adapter.ts"; import { moment } from "../deps.ts"; import { CLICommand, CLIName, loadConfig } from "../config/config.model.ts"; import { AzureErrorCode, MeshAzurePlatformError, MeshError, } from "../errors.ts"; import { TimeWindow, TimeWindowCalculator, } from "../mesh/time-window-calculator.ts"; import { MeshPrincipalType, MeshRoleAssignmentSource, MeshTenantRoleAssignment, } from "../mesh/mesh-iam-model.ts"; import { MeshTenantChangeDetector } from "../mesh/mesh-tenant-change-detector.ts"; export class AzureMeshAdapter implements MeshAdapter { constructor( private readonly azureCli: AzureCliFacade, private readonly timeWindowCalculator: TimeWindowCalculator, private readonly tenantChangeDetector: MeshTenantChangeDetector, ) {} async attachTenantCosts( tenants: MeshTenant[], startDate: Date, endDate: Date, ): Promise<void> { // Only work on Azure tenants const azureTenants = tenants.filter((t) => isSubscription(t.nativeObj)); if (moment(endDate).isBefore(moment(startDate))) { throw new MeshError("endDate must be after startDate"); } const config = loadConfig(); if (config.azure.parentManagementGroups.length == 0) { console.log( "It seems you have not configured a Azure Management Group for Subscription lookup. " + `Because of a bug in the Azure API, ${CLIName} can not detect this automatically. By ` + "configuring an Azure management group, cost & usage information lookups are significantly faster. " + `Run '${CLICommand} config azure -h' for more information.`, ); await this.getTenantCostsWithSingleQueries( azureTenants, startDate, endDate, ); } else { await this.getTenantCostsWithManagementGroupQuery( config.azure.parentManagementGroups, azureTenants, startDate, endDate, ); } } private async getTenantCostsWithManagementGroupQuery( managementGroupIds: string[], azureTenants: MeshTenant[], startDate: Date, endDate: Date, ): Promise<void> { // Only work on Azure tenants const from = moment(startDate).format("YYYY-MM-DDT00:00:00"); const to = moment(endDate).format("YYYY-MM-DDT23:59:59"); const costInformations = []; for (const mgmntGroupId of managementGroupIds) { const costInformation = await this.azureCli.getCostManagementInfo( mgmntGroupId, from, to, ); costInformations.push(...costInformation); } const summedCosts = new Map<string, number>(); const currencySymbols = new Map<string, string>(); for (const ci of costInformations) { if (!currencySymbols.has(ci.subscriptionId)) { currencySymbols.set(ci.subscriptionId, ci.currency); } else { // Make sure we only collect the same currency for one tenant. // Multiple currency for the same tenant are currently not supported. if (currencySymbols.get(ci.subscriptionId) !== ci.currency) { throw new MeshAzurePlatformError( AzureErrorCode.AZURE_CLI_GENERAL, "Encountered two different currencies within one Subscription during cost collection. This is currently not supported.", ); } } let currentCost = summedCosts.get(ci.subscriptionId) || 0; currentCost += ci.amount; summedCosts.set(ci.subscriptionId, currentCost); } for (const t of azureTenants) { const summedCost = summedCosts.get(t.platformTenantId) || 0; const currencySymbol = currencySymbols.get(t.platformTenantId) || ""; t.costs.push({ currency: currencySymbol, cost: summedCost.toString(), from: startDate, to: endDate, details: [], }); } } private async getTenantCostsWithSingleQueries( azureTenants: MeshTenant[], startDate: Date, endDate: Date, ): Promise<void> { const timeWindows = this.timeWindowCalculator.calculateTimeWindows( startDate, endDate, ); for (const t of azureTenants) { const results = []; for (const tw of timeWindows) { console.debug( `Quering Azure for tenant ${t.platformTenantName}: ${ JSON.stringify(tw) }`, ); try { const result = await this.getTenantCostsForWindow(t, tw); results.push(result); } catch (e) { if ( e instanceof MeshAzurePlatformError && e.errorCode === AzureErrorCode.AZURE_INVALID_SUBSCRIPTION ) { console.error( `The Subscription ${t.platformTenantId} can not be cost collected as Azure only supports Enterprise Agreement, Web Direct and Customer Agreements offer type Subscriptions to get cost collected via API.`, ); } } } t.costs.push(...results); } } private async getTenantCostsForWindow( tenant: MeshTenant, timeWindow: TimeWindow, ): Promise<MeshTenantCost> { if (!isSubscription(tenant.nativeObj)) { throw new MeshAzurePlatformError( AzureErrorCode.AZURE_TENANT_IS_NOT_SUBSCRIPTION, "Given tenant did not contain an Azure Subscription native object", ); } // This can throw an error because of too many requests. We should catch this and // wait here. const tenantCostInfo = await this.azureCli.getConsumptionInformation( tenant.nativeObj, timeWindow.from, timeWindow.to, ); console.debug(`Fetched ${tenantCostInfo.length} cost infos from Azure`); const totalUsagePretaxCost = [ 0.0, ...tenantCostInfo.map((tci) => parseFloat(tci.pretaxCost)), ].reduce((acc, val) => acc + val); let currencySymbol = ""; if (tenantCostInfo.length > 0) { currencySymbol = tenantCostInfo[0].currency; for (const tci of tenantCostInfo) { if (tci.currency !== currencySymbol) { throw new MeshAzurePlatformError( AzureErrorCode.AZURE_CLI_GENERAL, `Encountered two different currency during cost collection for tenant ${tenant.platformTenantId}. This is currently not supported.`, ); } } } return { currency: currencySymbol, cost: totalUsagePretaxCost.toFixed(2), details: [], // Can hold daily usages from: timeWindow.from, to: timeWindow.to, }; } async getMeshTenants(): Promise<MeshTenant[]> { const subscriptions = await this.azureCli.listAccounts(); return Promise.all( subscriptions.map(async (sub) => { const tags = await this.azureCli.listTags(sub); const meshTags = this.convertTags(tags); return { platformTenantId: sub.id, tags: meshTags, platformTenantName: sub.name, platform: MeshPlatform.Azure, nativeObj: sub, costs: [], roleAssignments: [], }; }), ); } async attachTenantRoleAssignments(tenants: MeshTenant[]): Promise<void> { // Only work on Azure tenants const azureTenants = tenants.filter((t) => isSubscription(t.nativeObj)); for (const t of azureTenants) { const roleAssignments = await this.loadRoleAssignmentsForTenant(t); t.roleAssignments.push(...roleAssignments); } } private async loadRoleAssignmentsForTenant( tenant: MeshTenant, ): Promise<MeshTenantRoleAssignment[]> { if (!isSubscription(tenant.nativeObj)) { throw new MeshAzurePlatformError( AzureErrorCode.AZURE_TENANT_IS_NOT_SUBSCRIPTION, "Given tenant did not contain an Azure Subscription native object", ); } const roleAssignments = await this.azureCli.getRoleAssignments( tenant.nativeObj, ); return roleAssignments.map((x) => { const { assignmentSource, assignmentId } = this.getAssignmentFromScope( x.scope, ); return { principalId: x.principalId, principalName: x.principalName, principalType: this.toMeshPrincipalType(x.principalType), roleId: x.roleDefinitionId, roleName: x.roleDefinitionName, assignmentSource, assignmentId, }; }); } private toMeshPrincipalType(principalType: string): MeshPrincipalType { switch (principalType) { case "User": return MeshPrincipalType.User; case "Group": return MeshPrincipalType.Group; case "ServicePrincipal": return MeshPrincipalType.TechnicalUser; default: throw new MeshAzurePlatformError( AzureErrorCode.AZURE_UNKNOWN_PRINCIPAL_TYPE, "Found unknown principalType for Azure: " + principalType, ); } } private convertTags(tags: Tag[]): MeshTag[] { return tags.map<MeshTag>((t) => { const tagValues = t.values.map((tv) => tv.tagValue); return { tagName: t.tagName, tagValues }; }); } private getAssignmentFromScope( scope: string, ): { assignmentId: string; assignmentSource: MeshRoleAssignmentSource } { const map: { [key in MeshRoleAssignmentSource]: RegExp } = { Organization: /^\/$/, // This means string should equal exactly to "/". Ancestor: /\/managementGroups\//, Tenant: /\/subscriptions\//, }; for (const key in map) { // Looping through an enum-key map sucks a bit: https://github.com/microsoft/TypeScript/issues/33123 if (map[key as MeshRoleAssignmentSource].test(scope)) { return { assignmentId: scope.split(map[key as MeshRoleAssignmentSource])[1], assignmentSource: key as MeshRoleAssignmentSource, }; } } throw new MeshAzurePlatformError( AzureErrorCode.AZURE_UNKNOWN_PRINCIPAL_ASSIGNMENT_SOURCE, "Could not detect assignment source from scope: " + scope, ); } async updateMeshTenant( updatedTenant: MeshTenant, originalTenant: MeshTenant, ): Promise<void> { if (!isSubscription(updatedTenant.nativeObj)) { return Promise.resolve(); } const changedTags = this.tenantChangeDetector.getChangedTags( updatedTenant.tags, originalTenant.tags, ); await this.azureCli.putTags( updatedTenant.nativeObj, changedTags.map((x) => ({ tagName: x.tagName, values: x.tagValues })), ); } }
the_stack
import { NOT_FOUND_PATH } from '../constants' import { RouteInspector } from '../debug/inspector' import { Input, MatchedValue, Matcher, MatchingProp, Nullable, ProcessInputResult, Route, RouteParams, RoutePath, RoutingState, Session, } from '../models' import { cloneObject } from '../utils' import { getEmptyAction, getNotFoundAction, getPathParamsFromPathPayload, isPathPayload, pathParamsToParams, } from './router-utils' export class Router { routes: Route[] routeInspector: RouteInspector constructor( routes: Route[], routeInspector: RouteInspector | undefined = undefined ) { this.routes = routes this.routeInspector = routeInspector || new RouteInspector() } /** * Processes an input and return a representation of the new bot state. * The algorithm is splitted in two main parts: * 1. Getting the current routing state. * 2. Given a routing state, resolve the different possible scenarios and return the new bot state. * The new bot state can return three type of actions: * - action: an action directly resolved from a matching route * - emptyAction: optional action that can exists or not only within childRoutes * - fallbackAction: any other action that acts as a fallback (404, ) */ // eslint-disable-next-line complexity processInput( input: Input, session: Session, lastRoutePath: RoutePath = null ): ProcessInputResult { session.__retries = session?.__retries ?? 0 // 1. Getting the current routing state. const { currentRoute, matchedRoute, params, isFlowBroken, } = this.getRoutingState(input, session, lastRoutePath) const currentRoutePath = currentRoute?.path ?? null const matchedRoutePath = matchedRoute?.path ?? null // 2. Given a routing state, resolve the different possible scenarios and return the new bot state. /** * Redirect Scenario: * We have matched a redirect route with a given redirection path, so we try to obtain the redirectionRoute with getRouteByPath. * Independently of whether the redirectionRoute is found or not, the intent is to trigger a redirection which by definition breaks the flow, so retries are set to 0. * It has preference over ignoring retries. */ if (matchedRoute && matchedRoute.redirect) { session.__retries = 0 const redirectionRoute = this.getRouteByPath(matchedRoute.redirect) if (redirectionRoute) { return { action: redirectionRoute.action, emptyAction: getEmptyAction(redirectionRoute.childRoutes), fallbackAction: null, lastRoutePath: matchedRoute.redirect, params, } } return { action: null, emptyAction: null, fallbackAction: getNotFoundAction(input, this.routes), lastRoutePath: null, params, } } /** * Ignore Retry Scenario: * We have matched a route with an ignore retry, so we return directly the new bot state. The intent is to break the flow, so retries are set to 0. */ if (matchedRoute && matchedRoute.ignoreRetry) { session.__retries = 0 return { action: matchedRoute.action, emptyAction: getEmptyAction(matchedRoute.childRoutes), fallbackAction: null, lastRoutePath: matchedRoutePath, params, } } /** * Retry Scenario: * We were in a route which had retries enabled, so we check if the number of retries is exceeded. * If we have not surpassed the limit of retries and we haven't matched an ignoreRetry route, update them, and then return the new bot state. */ if ( isFlowBroken && currentRoute && currentRoute.retry && session.__retries < currentRoute.retry ) { session.__retries = session.__retries !== 0 ? session.__retries + 1 : 1 if (matchedRoute && matchedRoutePath !== NOT_FOUND_PATH) { return { action: currentRoute.action, emptyAction: getEmptyAction(matchedRoute.childRoutes), fallbackAction: matchedRoute.action, lastRoutePath: currentRoutePath, params, } } return { action: currentRoute.action ?? null, emptyAction: getEmptyAction(currentRoute.childRoutes), fallbackAction: getNotFoundAction(input, this.routes), lastRoutePath: currentRoutePath, params, } } /** * Default Scenario: * We have matched a route or not, but we don't need to execute retries logic, so retries stay to 0. */ session.__retries = 0 /** * Matching Route Scenario: * We have matched a route, so we return the new bot state. */ if (matchedRoute && matchedRoutePath !== NOT_FOUND_PATH) { return { action: matchedRoute.action ?? null, emptyAction: getEmptyAction(matchedRoute.childRoutes), fallbackAction: null, lastRoutePath: matchedRoutePath, params, } } /** * 404 Scenario (No Route Found): * We have not matched any route, so we return the new bot state. */ return { action: null, emptyAction: null, fallbackAction: getNotFoundAction(input, this.routes), params, lastRoutePath: currentRoutePath, } } /** * Find the route that matches the given input, if it match with some of the entries, return the whole Route of the entry with optional params captured if matcher was a regex. * IMPORTANT: It returns a cloned route instead of the route itself to avoid modifying original routes and introduce side effects * */ getRoute( input: Input | Partial<Input>, routes: Route[], session: Session, lastRoutePath: RoutePath ): RouteParams | null { let params = {} const route = routes.find(r => Object.entries(r) .filter( ([key, _]) => key !== 'action' && key !== 'childRoutes' && key !== 'path' ) .some(([key, value]) => { const match = this.matchRoute( r, key as MatchingProp, value as Matcher, input as Input, session, lastRoutePath ) try { if (match !== null && typeof match !== 'boolean' && match.groups) { // Strip '[Object: null prototype]' from groups result: https://stackoverflow.com/a/62945609/6237608 params = { ...match.groups } } } catch (e) {} return Boolean(match) }) ) if (route) return { route: cloneObject(route), params } return null } /** * Find the route that matches the given path. Path can include concatenations, e.g: 'Flow1/Subflow1.1'. * IMPORTANT: It returns a cloned route instead of the route itself to avoid modifying original routes and introduce side effects * */ getRouteByPath( path: RoutePath, routeList: Route[] = this.routes ): Nullable<Route> { if (!path) return null const [currentPath, ...childPath] = path.split('/') for (const route of routeList) { // iterate over all routeList if (route.path === currentPath) { if ( route.childRoutes && route.childRoutes.length && childPath.length > 0 ) { // evaluate childroute over next actions const computedRoute = this.getRouteByPath( childPath.join('/'), route.childRoutes ) // IMPORTANT: Returning a new object to avoid modifying dev routes and introduce side effects if (computedRoute) return cloneObject(computedRoute) } else if (childPath.length === 0) { return cloneObject(route) // last action and found route } } } return null } /** * Returns the matched value for a specific route. * Matching Props: ('text' | 'payload' | 'intent' | 'type' | 'input' | 'session' | 'request' ...) * Matchers: (string: exact match | regex: regular expression match | function: return true) * input: user input object, e.g.: {type: 'text', data: 'Hi'} * */ matchRoute( route: Route, prop: MatchingProp, matcher: Matcher, input: Input, session: Session, lastRoutePath: RoutePath ): MatchedValue { let value: any = null if (Object.keys(input).indexOf(prop) > -1) value = input[prop] else if (prop === 'input') value = input else if (prop === 'session') value = session else if (prop === 'request') value = { input, session, lastRoutePath } const matched = this.matchValue(matcher, value) if (matched) { this.routeInspector.routeMatched(route, prop, matcher, value) } else { this.routeInspector.routeNotMatched(route, prop, matcher, value) } return matched } /** * Runs the matcher against the given value. * If there is a match, it will return a truthy value (true, RegExp result), o.w., it will return a falsy value. * */ matchValue(matcher: Matcher, value: any): MatchedValue { if (typeof matcher === 'string') return value === matcher if (matcher instanceof RegExp) { if (value === undefined || value === null) return false return matcher.exec(value) } if (typeof matcher === 'function') return matcher(value) return false } /** * It resolves the current state of navigation. Two scenarios: * 1. Given a path payload input (__PATH_PAYLOAD__somePath?someParam=someValue), we can resolve the routing state directly from it (using getRouteByPath). * 2. Given any other type of input, we resolve the routing state with normal resolution (using getRoute). * */ getRoutingState( input: Input, session: Session, lastRoutePath: RoutePath ): RoutingState { const currentRoute = this.getRouteByPath(lastRoutePath) if (currentRoute && lastRoutePath) currentRoute.path = lastRoutePath if (typeof input.payload === 'string' && isPathPayload(input.payload)) { return this.getRoutingStateFromPathPayload(currentRoute, input.payload) } return this.getRoutingStateFromInput(currentRoute, input, session) } /** * Given a non path payload input, try to run it against the routes, update matching routes information in consequence and dictamine if the flow has been broken. * */ getRoutingStateFromInput( currentRoute: Nullable<Route>, input: Input, session: Session ): RoutingState { // get route depending of current ChildRoutes if (currentRoute && currentRoute.childRoutes) { const routeParams = this.getRoute( input, currentRoute.childRoutes, session, currentRoute.path ) if (routeParams) { return { currentRoute, matchedRoute: { ...routeParams.route, path: routeParams.route && currentRoute.path ? `${currentRoute.path}/${routeParams.route.path}` : currentRoute.path, }, params: routeParams.params, isFlowBroken: false, } } } /** * we couldn't find a route in the state of the currentRoute childRoutes, * so let's find in the general routes */ const routeParams = this.getRoute( input, this.routes, session, currentRoute?.path ?? null ) const isFlowBroken = Boolean(currentRoute?.path) if (routeParams?.route) { return { currentRoute, matchedRoute: { ...routeParams.route, path: routeParams.route?.path ?? null, }, params: routeParams.params, isFlowBroken, } } return { currentRoute, matchedRoute: null, params: {}, isFlowBroken, } } /** * Given a path payload input, try to run the path against the routes, update matching routes information in consequence and dictamine if the flow has been broken. * */ getRoutingStateFromPathPayload( currentRoute: Nullable<Route>, pathPayload: string ): RoutingState { const { path, params } = getPathParamsFromPathPayload(pathPayload) /** * shorthand function to update the matching information given a path */ const getRoutingStateFromPath = (seekPath: string): RoutingState => { const matchedRoute = this.getRouteByPath(seekPath) if (!matchedRoute) { return { currentRoute, matchedRoute: null, params: {}, isFlowBroken: true, } } return { currentRoute, matchedRoute: { ...matchedRoute, path: seekPath }, params, isFlowBroken: false, } } /** * Given a valid path: 'Flow1/Subflow1' we are in one of the two scenarios below. */ // 1. Received __PATH_PAYLOAD__Subflow2, so we need to first try to concatenate it with Flow1 (lastRoutePath) if (currentRoute?.path) { const routingState = getRoutingStateFromPath( `${currentRoute.path}/${path}` ) if (routingState.matchedRoute) return routingState } // 2. Received __PATH_PAYLOAD__Flow1/Subflow1, so we can resolve it directly return getRoutingStateFromPath(path as string) } }
the_stack
import * as chai from 'chai'; import * as request from 'superagent'; import {Server} from '../../src/server'; import {FixtureLoader} from '../../fixtures/FixtureLoader'; import {JwtUtils} from '../../src/security/JwtUtils'; import {User} from '../../src/models/User'; import {errorCodes} from '../../src/config/errorCodes'; import {FixtureUtils} from '../../fixtures/FixtureUtils'; import {IUser} from '../../../shared/models/IUser'; import {allRoles} from '../../src/config/roles'; import chaiHttp = require('chai-http'); import fs = require('fs'); chai.use(chaiHttp); const should = chai.should(); const app = new Server().app; const BASE_URL = '/api/users'; const ROLE_URL = BASE_URL + '/roles'; const Search_URL = BASE_URL + '/members/search'; const fixtureLoader = new FixtureLoader(); describe('User', () => { // Before each test we reset the database beforeEach(async () => { await fixtureLoader.load(); }); describe(`GET ${BASE_URL}`, () => { it('should return all users', async () => { const teacher = await FixtureUtils.getRandomTeacher(); const res = await chai.request(app) .get(BASE_URL) .set('Cookie', `token=${JwtUtils.generateToken(teacher)}`); res.status.should.be.equal(200); res.body.should.be.a('array'); res.body.length.should.be.equal(await FixtureUtils.getUserCount()); }); it('should fail with wrong authorization', async () => { const res = await chai.request(app) .get(BASE_URL) .set('Authorization', 'JWT asdf') .catch(err => err.response); res.status.should.be.equal(401); }); it('should return the requested user object', async () => { const admin = await FixtureUtils.getRandomAdmin(); const res = await chai.request(app) .get(`${BASE_URL}/${admin._id}`) .set('Cookie', `token=${JwtUtils.generateToken(admin)}`); res.status.should.be.equal(200); res.body._id.should.be.equal(admin._id.toString()); res.body.email.should.be.equal(admin.email); }); }); describe(`GET ${ROLE_URL}`, () => { it('should fail with permission denied', async () => { const student = await FixtureUtils.getRandomStudent(); const res = await chai.request(app) .get(ROLE_URL) .set('Cookie', `token=${JwtUtils.generateToken(student)}`) .catch(err => err.response); res.status.should.be.equal(403); }); it('should return an array with the defined roles', async () => { const admin = await FixtureUtils.getRandomAdmin(); const res = await chai.request(app) .get(ROLE_URL) .set('Cookie', `token=${JwtUtils.generateToken(admin)}`); res.status.should.be.equal(200); res.body.should.be.a('array'); res.body.length.should.be.equal(allRoles.length); res.body.should.have.same.members(allRoles); }); }); describe(`GET ${Search_URL}`, () => { it('should search for a student', async () => { const teacher = await FixtureUtils.getRandomTeacher(); const newUser: IUser = new User({ uid: '487895', email: 'test@local.tv', password: 'test123456', profile: { firstName: 'Max', lastName: 'Mustermann' }, role: 'student' }); const createdUser = await User.create(newUser); const res = await chai.request(app) .get(Search_URL) .query({ role: newUser.role, query: newUser.uid + ' ' + newUser.email + ' ' + newUser.profile.firstName + ' ' + newUser.profile.lastName, limit: 1 }) .set('Cookie', `token=${JwtUtils.generateToken(teacher)}`); res.status.should.be.equal(200); res.body.meta.count.should.be.greaterThan(0); res.body.users.length.should.be.greaterThan(0); res.body.users[0].profile.firstName.should.be.equal(newUser.profile.firstName); res.body.users[0].profile.firstName.should.be.equal(newUser.profile.firstName); res.body.users[0].uid.should.be.equal(newUser.uid); res.body.users[0].email.should.be.equal(newUser.email); }); it('should search for a teacher', async () => { const teacher = await FixtureUtils.getRandomTeacher(); const newUser: IUser = new User({ uid: '487895', email: 'test@local.tv', password: 'test123456', profile: { firstName: 'Max', lastName: 'Mustermann' }, role: 'teacher' }); const createdUser = await User.create(newUser); const res = await chai.request(app) .get(Search_URL) .query({ role: 'teacher', query: newUser.uid + ' ' + newUser.email + ' ' + newUser.profile.firstName + ' ' + newUser.profile.lastName }) .set('Cookie', `token=${JwtUtils.generateToken(teacher)}`); res.status.should.be.equal(200); res.body.meta.count.should.be.greaterThan(0); res.body.users.length.should.be.greaterThan(0); res.body.users[0].profile.firstName.should.be.equal(newUser.profile.firstName); res.body.users[0].profile.firstName.should.be.equal(newUser.profile.firstName); res.body.users[0].uid.should.be.equal(newUser.uid); res.body.users[0].email.should.be.equal(newUser.email); }); }); describe(`PUT ${BASE_URL}`, () => { function requestUserUpdate(currentUser: IUser, updatedUser: IUser) { return chai.request(app) .put(`${BASE_URL}/${updatedUser._id}`) .set('Cookie', `token=${JwtUtils.generateToken(currentUser)}`) .send(updatedUser); } function requestUserUpdateAndCatch(currentUser: IUser, updatedUser: IUser) { return requestUserUpdate(currentUser, updatedUser).catch(err => err.response); } function assertFailure(res: request.Response, status: number, name: string, message: string) { res.status.should.be.equal(status); res.body.name.should.be.equal(name); res.body.message.should.be.equal(message); } it('should fail with bad request (revoke own admin privileges)', async () => { const admin = await FixtureUtils.getRandomAdmin(); const updatedUser = admin; updatedUser.role = 'teacher'; const res = await requestUserUpdateAndCatch(admin, updatedUser); assertFailure(res, 400, 'BadRequestError', errorCodes.user.cantChangeOwnRole.text); }); it('should fail with bad request (email already in use)', async () => { const admin = await FixtureUtils.getRandomAdmin(); const updatedUser = await FixtureUtils.getRandomStudent(); updatedUser.email = admin.email; const res = await requestUserUpdateAndCatch(admin, updatedUser); assertFailure(res, 400, 'BadRequestError', errorCodes.user.emailAlreadyInUse.text); }); // This test is disabled because there currently is no role beneath 'admin' that is allowed to edit other users. // Reactivate and adjust this test if such a role should become available in the future. // (Previously teachers had permission to change some parts of any student's profile.) /* it('should fail changing other user\'s uid with wrong authorization (not admin)', async () => { const teacher = await FixtureUtils.getRandomTeacher(); const updatedUser = await FixtureUtils.getRandomStudent(); updatedUser.uid = '987456'; const res = await requestUserUpdateAndCatch(teacher, updatedUser); assertFailure(res, 403, 'ForbiddenError', errorCodes.user.onlyAdminsCanChangeUids.text); }); */ it('should fail changing other user\'s name with wrong authorization (low edit level)', async () => { const [student, updatedUser] = await FixtureUtils.getRandomStudents(2, 2); updatedUser.profile.firstName = 'TEST'; const res = await requestUserUpdateAndCatch(student, updatedUser); assertFailure(res, 403, 'ForbiddenError', errorCodes.user.cantChangeUserWithHigherRole.text); }); it('should update user base data without password', async () => { const student = await FixtureUtils.getRandomStudent(); const updatedUser = student; updatedUser.password = undefined; updatedUser.profile.firstName = 'Updated'; updatedUser.profile.lastName = 'User'; updatedUser.email = 'student2@updated.local'; const res = await requestUserUpdate(student, updatedUser); res.status.should.be.equal(200); res.body.profile.firstName.should.be.equal('Updated'); res.body.profile.lastName.should.be.equal('User'); res.body.email.should.be.equal('student2@updated.local'); }); it('should update user data', async () => { const student = await FixtureUtils.getRandomStudent(); const updatedUser = student; updatedUser.password = ''; updatedUser.profile.firstName = 'Updated'; updatedUser.profile.lastName = 'User'; updatedUser.email = 'student1@updated.local'; const res = await requestUserUpdate(student, updatedUser); res.status.should.be.equal(200); res.body.profile.firstName.should.be.equal('Updated'); res.body.profile.lastName.should.be.equal('User'); res.body.email.should.be.equal('student1@updated.local'); }); it('should update user base data without password', async () => { const student = await FixtureUtils.getRandomStudent(); const updatedUser = student; updatedUser.password = undefined; updatedUser.profile.firstName = 'Updated'; updatedUser.profile.lastName = 'User'; updatedUser.email = 'student@updated.local'; const res = await requestUserUpdate(student, updatedUser); res.status.should.be.equal(200); res.body.profile.firstName.should.be.equal('Updated'); res.body.profile.lastName.should.be.equal('User'); res.body.email.should.be.equal('student@updated.local'); }); it('should keep a existing uid', async () => { const admin = await FixtureUtils.getRandomAdmin(); const student = await FixtureUtils.getRandomStudent(); const origUid = student.uid; const updatedUser = student; updatedUser.uid = null; updatedUser.password = ''; updatedUser.profile.firstName = 'Updated'; updatedUser.profile.lastName = 'User'; updatedUser.email = 'student@updated.local'; const res = await requestUserUpdate(admin, updatedUser); res.status.should.be.equal(200); res.body.uid.should.be.equal(origUid); res.body.profile.firstName.should.be.equal('Updated'); res.body.profile.lastName.should.be.equal('User'); res.body.email.should.be.equal('student@updated.local'); }); }); describe(`POST ${BASE_URL}/picture`, () => { async function requestAddUserPicture(currentUser: IUser, targetUser: IUser) { return await chai.request(app) .post(`${BASE_URL}/picture/${targetUser._id}`) .set('Cookie', `token=${JwtUtils.generateToken(currentUser)}`) .attach('file', fs.readFileSync('test/resources/test.png'), 'test.png'); } function assertSuccess(res: request.Response) { res.status.should.be.equal(200); res.body.profile.picture.should.be.an('object'); res.body.profile.picture.should.have.all.keys('alias', 'name', 'path'); res.body.profile.picture.alias.should.be.equal('test.png'); } it('should upload a new user picture', async () => { const admin = await FixtureUtils.getRandomAdmin(); const res = await requestAddUserPicture(admin, admin); assertSuccess(res); }); it('should fail to upload a new picture for another user (as student)', async () => { const [student, targetUser] = await FixtureUtils.getRandomStudents(2, 2); const res = await requestAddUserPicture(student, targetUser); res.status.should.be.equal(403); res.body.name.should.be.equal('ForbiddenError'); res.body.message.should.be.equal(errorCodes.user.cantChangeUserWithHigherRole.text); }); it('should upload a new picture for another user (as admin)', async () => { const admin = await FixtureUtils.getRandomAdmin(); const targetUser = await FixtureUtils.getRandomStudent(); const res = await requestAddUserPicture(admin, targetUser); assertSuccess(res); }); it('should block non images when uploading new user picture', async () => { const admin = await FixtureUtils.getRandomAdmin(); const res = await chai.request(app) .post(`${BASE_URL}/picture/${admin._id}`) .set('Cookie', `token=${JwtUtils.generateToken(admin)}`) .attach('file', fs.readFileSync('test/resources/wrong-format.rtf'), 'wrong-format.txt'); res.status.should.be.equal(403); res.body.name.should.be.equal('ForbiddenError'); }); }); describe(`DELETE ${BASE_URL}`, () => { async function ensureOnlyOneAdmin() { const admins = await FixtureUtils.getRandomAdmins(1, 2); admins.length.should.be.eq(1); return admins[0]; } it('should fail to delete the only admin', async () => { const admin = await ensureOnlyOneAdmin(); const res = await chai.request(app) .del(`${BASE_URL}/${admin._id}`) .set('Cookie', `token=${JwtUtils.generateToken(admin)}`) .catch(err => err.response); res.status.should.be.equal(400); res.body.name.should.be.equal('BadRequestError'); res.body.message.should.be.equal(errorCodes.user.noOtherAdmins.text); }); it('should fail to delete another user, if not admin', async () => { const teacher = await FixtureUtils.getRandomTeacher(); const studtent = await FixtureUtils.getRandomStudent(); const res = await chai.request(app) .del(`${BASE_URL}/${studtent._id}`) .set('Cookie', `token=${JwtUtils.generateToken(teacher)}`) .catch(err => err.response); res.status.should.be.equal(400); res.body.name.should.be.equal('BadRequestError'); res.body.message.should.be.equal(errorCodes.user.cantDeleteOtherUsers.text); }); it('should (promote a teacher to admin and) let the old admin delete itself', async () => { const admin = await ensureOnlyOneAdmin(); const promotedUser = await FixtureUtils.getRandomTeacher(); { // Promote the teacher to admin promotedUser.role = 'admin'; const res = await chai.request(app) .put(`${BASE_URL}/${promotedUser._id}`) .set('Cookie', `token=${JwtUtils.generateToken(admin)}`) .send(promotedUser); res.status.should.be.equal(200); res.body.role.should.be.equal('admin'); } { // Delete the old admin const res = await chai.request(app) .del(`${BASE_URL}/${admin._id}`) .set('Cookie', `token=${JwtUtils.generateToken(admin)}`); res.status.should.be.equal(200); } }); it('should send delete request', async () => { const teacher = await FixtureUtils.getRandomTeacher(); const res = await chai.request(app) .del(`${BASE_URL}/${teacher._id}`) .set('Cookie', `token=${JwtUtils.generateToken(teacher)}`) .catch(err => err.response); const userDeleteRequest = User.findById(teacher._id); should.exist(userDeleteRequest, 'User doesnt exist anymore.'); res.status.should.be.equal(200); }); it('should delete a student', async () => { const admin = await FixtureUtils.getRandomAdmin(); const student = await FixtureUtils.getRandomStudent(); const res = await chai.request(app) .del(`${BASE_URL}/${student._id}`) .set('Cookie', `token=${JwtUtils.generateToken(admin)}`); res.status.should.be.equal(200); res.body.result.should.be.equal(true); }); }); });
the_stack
// This file was automatically generated by elastic/elastic-client-generator-js // DO NOT MODIFY IT BY HAND. Instead, modify the source open api file, // and elastic/elastic-client-generator-js to regenerate this file again. import AsyncSearchApi from './api/async_search' import AutoscalingApi from './api/autoscaling' import bulkApi from './api/bulk' import CatApi from './api/cat' import CcrApi from './api/ccr' import clearScrollApi from './api/clear_scroll' import closePointInTimeApi from './api/close_point_in_time' import ClusterApi from './api/cluster' import countApi from './api/count' import createApi from './api/create' import DanglingIndicesApi from './api/dangling_indices' import deleteApi from './api/delete' import deleteByQueryApi from './api/delete_by_query' import deleteByQueryRethrottleApi from './api/delete_by_query_rethrottle' import deleteScriptApi from './api/delete_script' import EnrichApi from './api/enrich' import EqlApi from './api/eql' import existsApi from './api/exists' import existsSourceApi from './api/exists_source' import explainApi from './api/explain' import FeaturesApi from './api/features' import fieldCapsApi from './api/field_caps' import FleetApi from './api/fleet' import getApi from './api/get' import getScriptApi from './api/get_script' import getScriptContextApi from './api/get_script_context' import getScriptLanguagesApi from './api/get_script_languages' import getSourceApi from './api/get_source' import GraphApi from './api/graph' import IlmApi from './api/ilm' import indexApi from './api/index' import IndicesApi from './api/indices' import infoApi from './api/info' import IngestApi from './api/ingest' import knnSearchApi from './api/knn_search' import LicenseApi from './api/license' import LogstashApi from './api/logstash' import mgetApi from './api/mget' import MigrationApi from './api/migration' import MlApi from './api/ml' import MonitoringApi from './api/monitoring' import msearchApi from './api/msearch' import msearchTemplateApi from './api/msearch_template' import mtermvectorsApi from './api/mtermvectors' import NodesApi from './api/nodes' import openPointInTimeApi from './api/open_point_in_time' import pingApi from './api/ping' import putScriptApi from './api/put_script' import rankEvalApi from './api/rank_eval' import reindexApi from './api/reindex' import reindexRethrottleApi from './api/reindex_rethrottle' import renderSearchTemplateApi from './api/render_search_template' import RollupApi from './api/rollup' import scriptsPainlessExecuteApi from './api/scripts_painless_execute' import scrollApi from './api/scroll' import searchApi from './api/search' import searchMvtApi from './api/search_mvt' import searchShardsApi from './api/search_shards' import searchTemplateApi from './api/search_template' import SearchableSnapshotsApi from './api/searchable_snapshots' import SecurityApi from './api/security' import ShutdownApi from './api/shutdown' import SlmApi from './api/slm' import SnapshotApi from './api/snapshot' import SqlApi from './api/sql' import SslApi from './api/ssl' import TasksApi from './api/tasks' import termsEnumApi from './api/terms_enum' import termvectorsApi from './api/termvectors' import TextStructureApi from './api/text_structure' import TransformApi from './api/transform' import updateApi from './api/update' import updateByQueryApi from './api/update_by_query' import updateByQueryRethrottleApi from './api/update_by_query_rethrottle' import WatcherApi from './api/watcher' import XpackApi from './api/xpack' export default interface API { new(): API asyncSearch: AsyncSearchApi autoscaling: AutoscalingApi bulk: typeof bulkApi cat: CatApi ccr: CcrApi clearScroll: typeof clearScrollApi closePointInTime: typeof closePointInTimeApi cluster: ClusterApi count: typeof countApi create: typeof createApi danglingIndices: DanglingIndicesApi delete: typeof deleteApi deleteByQuery: typeof deleteByQueryApi deleteByQueryRethrottle: typeof deleteByQueryRethrottleApi deleteScript: typeof deleteScriptApi enrich: EnrichApi eql: EqlApi exists: typeof existsApi existsSource: typeof existsSourceApi explain: typeof explainApi features: FeaturesApi fieldCaps: typeof fieldCapsApi fleet: FleetApi get: typeof getApi getScript: typeof getScriptApi getScriptContext: typeof getScriptContextApi getScriptLanguages: typeof getScriptLanguagesApi getSource: typeof getSourceApi graph: GraphApi ilm: IlmApi index: typeof indexApi indices: IndicesApi info: typeof infoApi ingest: IngestApi knnSearch: typeof knnSearchApi license: LicenseApi logstash: LogstashApi mget: typeof mgetApi migration: MigrationApi ml: MlApi monitoring: MonitoringApi msearch: typeof msearchApi msearchTemplate: typeof msearchTemplateApi mtermvectors: typeof mtermvectorsApi nodes: NodesApi openPointInTime: typeof openPointInTimeApi ping: typeof pingApi putScript: typeof putScriptApi rankEval: typeof rankEvalApi reindex: typeof reindexApi reindexRethrottle: typeof reindexRethrottleApi renderSearchTemplate: typeof renderSearchTemplateApi rollup: RollupApi scriptsPainlessExecute: typeof scriptsPainlessExecuteApi scroll: typeof scrollApi search: typeof searchApi searchMvt: typeof searchMvtApi searchShards: typeof searchShardsApi searchTemplate: typeof searchTemplateApi searchableSnapshots: SearchableSnapshotsApi security: SecurityApi shutdown: ShutdownApi slm: SlmApi snapshot: SnapshotApi sql: SqlApi ssl: SslApi tasks: TasksApi termsEnum: typeof termsEnumApi termvectors: typeof termvectorsApi textStructure: TextStructureApi transform: TransformApi update: typeof updateApi updateByQuery: typeof updateByQueryApi updateByQueryRethrottle: typeof updateByQueryRethrottleApi watcher: WatcherApi xpack: XpackApi } const kAsyncSearch = Symbol('AsyncSearch') const kAutoscaling = Symbol('Autoscaling') const kCat = Symbol('Cat') const kCcr = Symbol('Ccr') const kCluster = Symbol('Cluster') const kDanglingIndices = Symbol('DanglingIndices') const kEnrich = Symbol('Enrich') const kEql = Symbol('Eql') const kFeatures = Symbol('Features') const kFleet = Symbol('Fleet') const kGraph = Symbol('Graph') const kIlm = Symbol('Ilm') const kIndices = Symbol('Indices') const kIngest = Symbol('Ingest') const kLicense = Symbol('License') const kLogstash = Symbol('Logstash') const kMigration = Symbol('Migration') const kMl = Symbol('Ml') const kMonitoring = Symbol('Monitoring') const kNodes = Symbol('Nodes') const kRollup = Symbol('Rollup') const kSearchableSnapshots = Symbol('SearchableSnapshots') const kSecurity = Symbol('Security') const kShutdown = Symbol('Shutdown') const kSlm = Symbol('Slm') const kSnapshot = Symbol('Snapshot') const kSql = Symbol('Sql') const kSsl = Symbol('Ssl') const kTasks = Symbol('Tasks') const kTextStructure = Symbol('TextStructure') const kTransform = Symbol('Transform') const kWatcher = Symbol('Watcher') const kXpack = Symbol('Xpack') export default class API { [kAsyncSearch]: symbol | null [kAutoscaling]: symbol | null [kCat]: symbol | null [kCcr]: symbol | null [kCluster]: symbol | null [kDanglingIndices]: symbol | null [kEnrich]: symbol | null [kEql]: symbol | null [kFeatures]: symbol | null [kFleet]: symbol | null [kGraph]: symbol | null [kIlm]: symbol | null [kIndices]: symbol | null [kIngest]: symbol | null [kLicense]: symbol | null [kLogstash]: symbol | null [kMigration]: symbol | null [kMl]: symbol | null [kMonitoring]: symbol | null [kNodes]: symbol | null [kRollup]: symbol | null [kSearchableSnapshots]: symbol | null [kSecurity]: symbol | null [kShutdown]: symbol | null [kSlm]: symbol | null [kSnapshot]: symbol | null [kSql]: symbol | null [kSsl]: symbol | null [kTasks]: symbol | null [kTextStructure]: symbol | null [kTransform]: symbol | null [kWatcher]: symbol | null [kXpack]: symbol | null constructor () { this[kAsyncSearch] = null this[kAutoscaling] = null this[kCat] = null this[kCcr] = null this[kCluster] = null this[kDanglingIndices] = null this[kEnrich] = null this[kEql] = null this[kFeatures] = null this[kFleet] = null this[kGraph] = null this[kIlm] = null this[kIndices] = null this[kIngest] = null this[kLicense] = null this[kLogstash] = null this[kMigration] = null this[kMl] = null this[kMonitoring] = null this[kNodes] = null this[kRollup] = null this[kSearchableSnapshots] = null this[kSecurity] = null this[kShutdown] = null this[kSlm] = null this[kSnapshot] = null this[kSql] = null this[kSsl] = null this[kTasks] = null this[kTextStructure] = null this[kTransform] = null this[kWatcher] = null this[kXpack] = null } } API.prototype.bulk = bulkApi API.prototype.clearScroll = clearScrollApi API.prototype.closePointInTime = closePointInTimeApi API.prototype.count = countApi API.prototype.create = createApi API.prototype.delete = deleteApi API.prototype.deleteByQuery = deleteByQueryApi API.prototype.deleteByQueryRethrottle = deleteByQueryRethrottleApi API.prototype.deleteScript = deleteScriptApi API.prototype.exists = existsApi API.prototype.existsSource = existsSourceApi API.prototype.explain = explainApi API.prototype.fieldCaps = fieldCapsApi API.prototype.get = getApi API.prototype.getScript = getScriptApi API.prototype.getScriptContext = getScriptContextApi API.prototype.getScriptLanguages = getScriptLanguagesApi API.prototype.getSource = getSourceApi API.prototype.index = indexApi API.prototype.info = infoApi API.prototype.knnSearch = knnSearchApi API.prototype.mget = mgetApi API.prototype.msearch = msearchApi API.prototype.msearchTemplate = msearchTemplateApi API.prototype.mtermvectors = mtermvectorsApi API.prototype.openPointInTime = openPointInTimeApi API.prototype.ping = pingApi API.prototype.putScript = putScriptApi API.prototype.rankEval = rankEvalApi API.prototype.reindex = reindexApi API.prototype.reindexRethrottle = reindexRethrottleApi API.prototype.renderSearchTemplate = renderSearchTemplateApi API.prototype.scriptsPainlessExecute = scriptsPainlessExecuteApi API.prototype.scroll = scrollApi API.prototype.search = searchApi API.prototype.searchMvt = searchMvtApi API.prototype.searchShards = searchShardsApi API.prototype.searchTemplate = searchTemplateApi API.prototype.termsEnum = termsEnumApi API.prototype.termvectors = termvectorsApi API.prototype.update = updateApi API.prototype.updateByQuery = updateByQueryApi API.prototype.updateByQueryRethrottle = updateByQueryRethrottleApi Object.defineProperties(API.prototype, { asyncSearch: { get () { return this[kAsyncSearch] === null ? (this[kAsyncSearch] = new AsyncSearchApi(this.transport)) : this[kAsyncSearch] } }, autoscaling: { get () { return this[kAutoscaling] === null ? (this[kAutoscaling] = new AutoscalingApi(this.transport)) : this[kAutoscaling] } }, cat: { get () { return this[kCat] === null ? (this[kCat] = new CatApi(this.transport)) : this[kCat] } }, ccr: { get () { return this[kCcr] === null ? (this[kCcr] = new CcrApi(this.transport)) : this[kCcr] } }, cluster: { get () { return this[kCluster] === null ? (this[kCluster] = new ClusterApi(this.transport)) : this[kCluster] } }, danglingIndices: { get () { return this[kDanglingIndices] === null ? (this[kDanglingIndices] = new DanglingIndicesApi(this.transport)) : this[kDanglingIndices] } }, enrich: { get () { return this[kEnrich] === null ? (this[kEnrich] = new EnrichApi(this.transport)) : this[kEnrich] } }, eql: { get () { return this[kEql] === null ? (this[kEql] = new EqlApi(this.transport)) : this[kEql] } }, features: { get () { return this[kFeatures] === null ? (this[kFeatures] = new FeaturesApi(this.transport)) : this[kFeatures] } }, fleet: { get () { return this[kFleet] === null ? (this[kFleet] = new FleetApi(this.transport)) : this[kFleet] } }, graph: { get () { return this[kGraph] === null ? (this[kGraph] = new GraphApi(this.transport)) : this[kGraph] } }, ilm: { get () { return this[kIlm] === null ? (this[kIlm] = new IlmApi(this.transport)) : this[kIlm] } }, indices: { get () { return this[kIndices] === null ? (this[kIndices] = new IndicesApi(this.transport)) : this[kIndices] } }, ingest: { get () { return this[kIngest] === null ? (this[kIngest] = new IngestApi(this.transport)) : this[kIngest] } }, license: { get () { return this[kLicense] === null ? (this[kLicense] = new LicenseApi(this.transport)) : this[kLicense] } }, logstash: { get () { return this[kLogstash] === null ? (this[kLogstash] = new LogstashApi(this.transport)) : this[kLogstash] } }, migration: { get () { return this[kMigration] === null ? (this[kMigration] = new MigrationApi(this.transport)) : this[kMigration] } }, ml: { get () { return this[kMl] === null ? (this[kMl] = new MlApi(this.transport)) : this[kMl] } }, monitoring: { get () { return this[kMonitoring] === null ? (this[kMonitoring] = new MonitoringApi(this.transport)) : this[kMonitoring] } }, nodes: { get () { return this[kNodes] === null ? (this[kNodes] = new NodesApi(this.transport)) : this[kNodes] } }, rollup: { get () { return this[kRollup] === null ? (this[kRollup] = new RollupApi(this.transport)) : this[kRollup] } }, searchableSnapshots: { get () { return this[kSearchableSnapshots] === null ? (this[kSearchableSnapshots] = new SearchableSnapshotsApi(this.transport)) : this[kSearchableSnapshots] } }, security: { get () { return this[kSecurity] === null ? (this[kSecurity] = new SecurityApi(this.transport)) : this[kSecurity] } }, shutdown: { get () { return this[kShutdown] === null ? (this[kShutdown] = new ShutdownApi(this.transport)) : this[kShutdown] } }, slm: { get () { return this[kSlm] === null ? (this[kSlm] = new SlmApi(this.transport)) : this[kSlm] } }, snapshot: { get () { return this[kSnapshot] === null ? (this[kSnapshot] = new SnapshotApi(this.transport)) : this[kSnapshot] } }, sql: { get () { return this[kSql] === null ? (this[kSql] = new SqlApi(this.transport)) : this[kSql] } }, ssl: { get () { return this[kSsl] === null ? (this[kSsl] = new SslApi(this.transport)) : this[kSsl] } }, tasks: { get () { return this[kTasks] === null ? (this[kTasks] = new TasksApi(this.transport)) : this[kTasks] } }, textStructure: { get () { return this[kTextStructure] === null ? (this[kTextStructure] = new TextStructureApi(this.transport)) : this[kTextStructure] } }, transform: { get () { return this[kTransform] === null ? (this[kTransform] = new TransformApi(this.transport)) : this[kTransform] } }, watcher: { get () { return this[kWatcher] === null ? (this[kWatcher] = new WatcherApi(this.transport)) : this[kWatcher] } }, xpack: { get () { return this[kXpack] === null ? (this[kXpack] = new XpackApi(this.transport)) : this[kXpack] } } })
the_stack
import { expect } from "chai"; import { GeometryQuery } from "../../curve/GeometryQuery"; import { LineSegment3d } from "../../curve/LineSegment3d"; import { LineString3d } from "../../curve/LineString3d"; import { Geometry } from "../../Geometry"; import { Angle } from "../../geometry3d/Angle"; import { Point3d, Vector3d } from "../../geometry3d/Point3dVector3d"; import { Point2d} from "../../geometry3d/Point2dVector2d"; import { Transform } from "../../geometry3d/Transform"; import { HalfEdge, HalfEdgeGraph, HalfEdgeMask } from "../../topology/Graph"; import { HalfEdgeGraphSearch } from "../../topology/HalfEdgeGraphSearch"; import { HalfEdgeMaskValidation, HalfEdgePointerInspector } from "../../topology/HalfEdgeGraphValidation"; import { HalfEdgeGraphMerge } from "../../topology/Merging"; import { Checker } from "../Checker"; import { GeometryCoreTestIO } from "../GeometryCoreTestIO"; import { NodeXYZUV } from "../../topology/HalfEdgeNodeXYZUV"; import { HalfEdgePositionDetail, HalfEdgeTopo } from "../../topology/HalfEdgePositionDetail"; import { InsertAndRetriangulateContext } from "../../topology/InsertAndRetriangulateContext"; import { OutputManager } from "../clipping/ClipPlanes.test"; function logGraph(graph: HalfEdgeGraph, title: any) { console.log(` == begin == ${title}`); for (const he of graph.allHalfEdges) { console.log(HalfEdge.nodeToIdXYString(he)); } console.log(` ==end== ${title}`); } export class GraphChecker { public static captureAnnotatedGraph(data: GeometryQuery[], graph: HalfEdgeGraph | undefined, dx: number = 0, dy: number = 0) { if (graph === undefined) return; const maxTick = 0.01; const numTick = 20; const allNodes = graph.allHalfEdges; const xyzA = Point3d.create(); const xyz = Point3d.create(); // work point const xyzB = Point3d.create(); const vectorAB = Vector3d.create(); const perpAB = Vector3d.create(); const perpAC = Vector3d.create(); const vectorAC = Vector3d.create(); const count0 = data.length; for (const nodeA of allNodes) { const nodeB = nodeA.faceSuccessor; const nodeC = nodeA.vertexSuccessor; Point3d.create(nodeA.x, nodeA.y, 0, xyzA); Point3d.create(nodeB.x, nodeB.y, 0, xyzB); // if both ends are trivial, just put out the stroke . .. if (nodeA.countEdgesAroundVertex() <= 1 && nodeB.countEdgesAroundVertex() <= 1) { data.push(LineSegment3d.create(xyzA, xyzB)); } else { nodeA.vectorToFaceSuccessor(vectorAB); nodeC.vectorToFaceSuccessor(vectorAC); vectorAB.unitPerpendicularXY(perpAB); vectorAC.unitPerpendicularXY(perpAC); const dAB = xyzA.distanceXY(xyzB); const dTick = Math.min(dAB / numTick, maxTick); const tickFraction = Geometry.safeDivideFraction(dTick, dAB, 0.0); perpAB.scaleInPlace(dTick); const linestring = LineString3d.create(); linestring.clear(); linestring.addPoint(xyzA); xyzA.plusScaled(vectorAB, 2 * tickFraction, xyz); if (nodeC === nodeA) linestring.addPoint(xyz); linestring.addPoint(xyz.plus(perpAB, xyz)); linestring.addPoint(xyzB); data.push(linestring); if (!vectorAB.isParallelTo(vectorAC)) { let theta = vectorAB.angleToXY(vectorAC); if (theta.radians < 0.0) theta = Angle.createDegrees(theta.degrees + 360); if (vectorAB.tryNormalizeInPlace() && vectorAC.tryNormalizeInPlace()) { const linestringV = LineString3d.create(); linestringV.clear(); linestringV.addPoint(xyzA.plusScaled(vectorAB, dTick)); if (theta.degrees > 90) { let numStep = 3; if (theta.degrees > 180) numStep = 5; if (theta.degrees > 270) numStep = 7; const stepRadians = theta.radians / numStep; for (let i = 1; i <= numStep; i++) { vectorAB.rotateXY(Angle.createRadians(stepRadians), vectorAB); linestringV.addPoint(xyzA.plusScaled(vectorAB, dTick)); } } linestringV.addPoint(xyzA.plusScaled(vectorAC, dTick)); data.push(linestringV); } } } } const transform = Transform.createTranslationXYZ(dx, dy, 0); for (let i = count0; i < data.length; i++) data[i].tryTransformInPlace(transform); } public static printToConsole = true; public static dumpGraph(graph: HalfEdgeGraph) { const faces = graph.collectFaceLoops(); const vertices = graph.collectVertexLoops(); const faceData = []; for (const f of faces) { faceData.push(f.collectAroundFace(HalfEdge.nodeToIdXYString)); } if (this.printToConsole) { console.log(`"**FACE LOOPS ${faces.length}`); console.log(faceData); } const vData = []; for (const v of vertices) { const totalDistance = v.sumAroundVertex((node: HalfEdge) => node.distanceXY(v)); if (totalDistance !== 0) { // output full coordinates all the way around. vData.push("INCONSISTENT VERTEX XY"); vData.push(JSON.stringify(v.collectAroundVertex(HalfEdge.nodeToIdMaskXY))); } else vData.push([HalfEdge.nodeToIdXYString(v), v.collectAroundVertex(HalfEdge.nodeToId)]); } if (this.printToConsole) { console.log(`"**VERTEX LOOPS ${vertices.length}`); console.log(vData); } } /** * * call various "fast" mask methods at every node. * * call expensive methods (those requiring full graph search) for a few nodes. */ public static exerciseMaskMethods(ck: Checker, graph: HalfEdgeGraph) { const myMask = HalfEdgeMask.PRIMARY_EDGE; graph.clearMask(myMask); const numNode = graph.allHalfEdges.length; ck.testExactNumber(0, graph.countMask(myMask), "graph.setMask"); graph.clearMask(HalfEdgeMask.VISITED); graph.setMask(myMask); ck.testExactNumber(numNode, graph.countMask(myMask), "graph.clearMask"); graph.clearMask(myMask); let numSet = 0; // do some tedious stuff at "a few" nodes .. 0,3,9,21.... const mask1 = graph.grabMask(); const mask2 = graph.grabMask(); let numMask2InSet = 0; graph.clearMask(mask1); ck.testExactNumber(0, graph.countMask(mask1), `clear mask ${mask1}`); for (let i = 0; i < numNode; i += 3 + i) { const node = graph.allHalfEdges[i]; ck.testFalse(node.isMaskSet(myMask), "0 mask"); ck.testTrue(node.testAndSetMask(myMask) === 0, "testAndSet from 0"); ck.testTrue(node.isMaskSet(myMask), "after testAndSet"); numSet++; // confirm "around vertex ops" -- some tests are full-graph sweeps. graph.clearMask(mask1); const numNodesAroundVertex = node.countEdgesAroundVertex(); const numNodesAroundFace = node.countEdgesAroundFace(); ck.testExactNumber(numNodesAroundVertex, node.countMaskAroundVertex(mask1, false), "count unmasked around vertex"); ck.testExactNumber(numNodesAroundFace, node.countMaskAroundFace(mask1, false), "count unmasked around face"); node.setMaskAroundVertex(mask1); ck.testExactNumber(numNodesAroundFace - 1, node.countMaskAroundFace(mask1, false), "count unmasked around face after vertex set"); const nodesAroundVertex = node.collectAroundVertex(); ck.testExactNumber(numNodesAroundVertex, nodesAroundVertex.length, "count nodes == collected array length"); const masksAroundVertex = node.countMaskAroundVertex(mask1); ck.testExactNumber(nodesAroundVertex.length, masksAroundVertex); ck.testExactNumber(nodesAroundVertex.length, graph.countMask(mask1), "confirm count for setMaskAroundVertex"); node.clearMaskAroundVertex(mask1); ck.testExactNumber(0, graph.countMask(mask1), "clear around vertex"); const numMask2ThisFace = node.countMaskAroundFace(mask2); node.setMaskAroundFace(mask2); ck.testExactNumber(numNodesAroundFace, node.countMaskAroundFace(mask2)); numMask2InSet += node.countMaskAroundFace(mask2) - numMask2ThisFace; ck.testExactNumber(numMask2InSet, graph.countMask(mask2), "global mask count versus per-face update"); } ck.testExactNumber(numSet, graph.countMask(myMask), " count mask after various testAndSet"); graph.reverseMask(myMask); ck.testExactNumber(numNode - numSet, graph.countMask(myMask), "count mask after reverse"); graph.dropMask(mask1); graph.dropMask(mask2); } public static validateCleanLoopsAndCoordinates(ck: Checker, graph: HalfEdgeGraph) { for (const he of graph.allHalfEdges) { ck.testTrue(he === he.vertexSuccessor.vertexPredecessor, "vertex successor/predecessor relation"); ck.testTrue(he === he.faceSuccessor.facePredecessor, "face successor/predecessor relation"); const vs = he.vertexSuccessor; const faceSuccessor = he.faceSuccessor; ck.testTrue(he.isEqualXY(vs), "Exact xy around vertex loop"); ck.testFalse(he.isEqualXY(faceSuccessor), "different xy around face loop"); ck.testTrue(he === HalfEdge.nodeToSelf(he), "HalfEdge.nodeToSelf"); ck.testExactNumber(he.faceStepY(0), he.y); ck.testExactNumber(he.faceStepY(1), he.faceSuccessor.y); ck.testExactNumber(he.faceStepY(2), he.faceSuccessor.faceSuccessor.y); ck.testExactNumber(he.faceStepY(-1), he.facePredecessor.y); ck.testExactNumber(he.faceStepY(-2), he.facePredecessor.facePredecessor.y); } } public static verifyMaskAroundFaces(ck: Checker, graph: HalfEdgeGraph, mask: HalfEdgeMask): boolean { // is EXTERIOR_MASK consistent around all faces? let maskErrors = 0; for (const node of graph.allHalfEdges) { if (node.isMaskSet(mask) !== node.faceSuccessor.isMaskSet(mask)) maskErrors++; } if (maskErrors !== 0) ck.announceError(`EXTERIOR_MASK inconsistent at ${maskErrors} nodes`); return maskErrors === 0; } /** * * @param ck checker for error reports * @param graph graph to inspect * @param checkConsistentExteriorMask if true, verify that HalfEdgeMask.EXTERIOR is consistent within each face (entirely on or entirely off) * @param numFace (optional) precise expected face count * @param numVertex (optional) precise expected vertex count * @param positiveFaceAreaSum (optional) precise expected positive area face sum */ public static verifyGraphCounts(ck: Checker, graph: HalfEdgeGraph, checkConsistentExteriorMask: boolean, numFace: number | undefined, numVertex: number | undefined, positiveFaceAreaSum: undefined | number) { const error0 = ck.getNumErrors(); const faces = graph.collectFaceLoops(); const vertices = graph.collectVertexLoops(); if (numFace) ck.testExactNumber(numFace, faces.length, "face count"); if (numFace) ck.testExactNumber(numFace, graph.countFaceLoops(), "face count"); if (numVertex) ck.testExactNumber(numVertex, vertices.length, "vertex count"); if (numVertex) ck.testExactNumber(numVertex, graph.countVertexLoops(), "vertex count"); if (checkConsistentExteriorMask) this.verifyMaskAroundFaces(ck, graph, HalfEdgeMask.EXTERIOR); if (positiveFaceAreaSum) { let sum = 0.0; for (const face of faces) { const faceArea = face.signedFaceArea(); if (faceArea > 0.0) sum += faceArea; } ck.testCoordinate(positiveFaceAreaSum, sum, "area sum"); } if (ck.getNumErrors() > error0) GraphChecker.dumpGraph(graph); } /** * Return arrays with faces, distributed by sign of face area. * @param graph */ public static collectFacesByArea(graph: HalfEdgeGraph): any { const faces = graph.collectFaceLoops(); const result: any = {}; result.absAreaSum = 0; result.zeroAreaTolerance = 0; result.positiveFaces = []; result.negativeFaces = []; result.nearZeroFaces = []; for (const face of faces) { result.absAreaSum += Math.abs(face.signedFaceArea()); result.zeroAreaTolerance = 1.0e-12 * result.absAreaSum; } for (const face of faces) { const a = face.signedFaceArea(); if (Math.abs(a) <= result.zeroAreaTolerance) result.nearZeroFaces.push(face); else if (a > 0.0) result.positiveFaces.push(face); else /* strict negative */ result.negativeFaces.push(face); } return result; } public static verifySignedFaceCounts(ck: Checker, graph: HalfEdgeGraph, numPositive: number | undefined, numNegative: number | undefined, numNearZero: number | undefined): boolean { const faceData = this.collectFacesByArea(graph); const okPositive = numPositive === undefined || faceData.positiveFaces.length === numPositive; const okNegative = numNegative === undefined || faceData.negativeFaces.length === numNegative; const okNearZero = numNearZero === undefined || faceData.nearZeroFaces.length === numNearZero; ck.testTrue(okPositive, "PositiveAreaFaceCount ", numPositive); ck.testTrue(okNegative, "NegativeAreaFaceCount ", numNegative); ck.testTrue(okPositive, "PositiveAreaFaceCount ", numNearZero); return okPositive && okNegative && okNearZero; } } describe("VUGraph", () => { it("HelloWorld", () => { const ck = new Checker(); const graph = new HalfEdgeGraph(); const numX = 2; const numY = 2; ck.checkpoint("HelloWorld"); // make horizontal edges for (let j = 0; j < numY; j++) { for (let i = 0; i < numX; i++) graph.addEdgeXY(i, j, i + 1, j); } // make horizontal edges for (let i = 0; i < numX; i++) { for (let j = 0; j < numY; j++) graph.addEdgeXY(i, j, i, j + 1); } ck.testTrue(HalfEdgePointerInspector.inspectGraph(graph, true), "Isolated edge graph HalfEdgeGraph pointer properties"); // The edges form squares with danglers on the right and type . . // // // | | | | // | | | | // +-----+-----+-----+----- // | | | | // | | | | // +-----+-----+-----+----- // | | | | // | | | | // +-----+-----+-----+----- // // before merging, each edge hangs alone in space and creates a face and two vertices . . const numEdge = 2 * numX * numY; GraphChecker.verifyGraphCounts(ck, graph, true, numEdge, 2 * numEdge, undefined); ck.testExactNumber(2 * numEdge, graph.countNodes(), "dangling nodes"); const geometry: GeometryQuery[] = []; GraphChecker.captureAnnotatedGraph(geometry, graph, 0, 0); HalfEdgeGraphMerge.clusterAndMergeXYTheta(graph); // after merge, there are interior faces and a single exterior face . . const numInteriorFaces = (numX - 1) * (numY - 1); const numFaces = numInteriorFaces + 1; GraphChecker.verifyGraphCounts(ck, graph, true, numFaces, (numX + 1) * (numY + 1) - 1, undefined); GraphChecker.dumpGraph(graph); GraphChecker.captureAnnotatedGraph(geometry, graph, 0, 10); const segments = graph.collectSegments(); ck.testExactNumber(numEdge, segments.length, "segmentCount"); GeometryCoreTestIO.saveGeometry(geometry, "Graph", "GridFixup"); const componentsB = HalfEdgeGraphSearch.collectConnectedComponentsWithExteriorParityMasks(graph, undefined, HalfEdgeMask.EXTERIOR); ck.testTrue(HalfEdgeMaskValidation.isMaskConsistentAroundAllFaces(graph, HalfEdgeMask.EXTERIOR), "ParitySearch makes valid exterior Masks"); if (ck.testExactNumber(1, componentsB.length, "Expect single component")) { ck.testExactNumber(numFaces, componentsB[0].length, "face count from search"); } ck.testExactNumber(1, graph.countFaceLoopsWithMaskFilter(HalfEdge.filterIsMaskOn, HalfEdgeMask.EXTERIOR), "Single exterior after parity"); ck.testExactNumber(numInteriorFaces, graph.countFaceLoopsWithMaskFilter(HalfEdge.filterIsMaskOff, HalfEdgeMask.EXTERIOR), "Single exterior after parity"); GraphChecker.validateCleanLoopsAndCoordinates(ck, graph); ck.testTrue(HalfEdgePointerInspector.inspectGraph(graph, true), "Merged Graph HalfEdgeGraph pointer properties"); ck.testTrue(HalfEdgePointerInspector.inspectGraph(graph, false), "Merged Graph HalfEdgeGraph pointer properties"); // interior faces should have area 1 and perimeter 4 .. for (const component of componentsB) { for (const faceSeed of component) { const area1 = faceSeed.signedFaceArea(); if (faceSeed.isMaskSet(HalfEdgeMask.EXTERIOR)) { ck.testLT(area1, 0, "exterior loop has negative area"); } else { // We know the interior loops are all unit squares . . ck.testCoordinate(1.0, area1, "unit face area"); const lengthSum = faceSeed.sumAroundFace( (node: HalfEdge) => node.vectorToFaceSuccessorXY().magnitude()); ck.testCoordinate(4.0, lengthSum); } } } GraphChecker.exerciseMaskMethods(ck, graph); graph.decommission(); expect(ck.getNumErrors()).equals(0); }); it("SimpleQueries", () => { const graph = new HalfEdgeGraph(); const node = graph.addEdgeXY(1, 2, 3, 4); const node1 = node.facePredecessor; if (GraphChecker.printToConsole) { console.log("NodeToId:", HalfEdge.nodeToId(node1)); console.log("nodeToIdString:", HalfEdge.nodeToIdString(node1)); console.log("nodeToXY:", HalfEdge.nodeToXY(node1)); console.log("nodeToIdXYString:", HalfEdge.nodeToIdXYString(node1)); console.log("nodeToIdMaskXY:", HalfEdge.nodeToIdMaskXY(node1)); console.log("nodeToMaskString:", HalfEdge.nodeToMaskString(node1)); } }); it("NullFaceGraph", () => { const ck = new Checker(); const graph = new HalfEdgeGraph(); const inside0 = graph.addEdgeXY(0, 0, 10, 0); const inside1 = graph.addEdgeXY(10, 0, 5, 5); const inside2 = graph.addEdgeXY(5, 5, 0, 0); const null0 = graph.addEdgeXY(3, 4, 3, 5); const outside0 = inside2.faceSuccessor; const outside1 = inside0.faceSuccessor; const outside2 = inside1.faceSuccessor; const null1 = null0.faceSuccessor; HalfEdge.pinch(inside0, outside0); HalfEdge.pinch(inside1, outside1); HalfEdge.pinch(inside2, outside2); inside0.setMaskAroundFace(HalfEdgeMask.BOUNDARY_EDGE | HalfEdgeMask.PRIMARY_EDGE); outside0.setMaskAroundFace(HalfEdgeMask.BOUNDARY_EDGE); outside0.setMaskAroundFace(HalfEdgeMask.PRIMARY_EDGE); HalfEdge.pinch(null0, inside0); HalfEdge.pinch(null1, inside1); const summary = HalfEdgeGraphSearch.collectFaceAreaSummary(graph, true); ck.testExactNumber(summary.numZero, summary.zeroItemArray!.length); ck.testExactNumber(1, summary.numPositive); ck.testExactNumber(1, summary.numNegative); ck.testExactNumber(1, summary.numZero); ck.testTrue(HalfEdgeMaskValidation.isMaskConsistentAroundAllFaces(graph, HalfEdgeMask.EXTERIOR)); outside2.setMask(HalfEdgeMask.EXTERIOR); ck.testFalse(HalfEdgeMaskValidation.isMaskConsistentAroundAllFaces(graph, HalfEdgeMask.EXTERIOR)); outside2.setMaskAroundFace(HalfEdgeMask.EXTERIOR); ck.testTrue(HalfEdgeMaskValidation.isMaskConsistentAroundAllFaces(graph, HalfEdgeMask.EXTERIOR)); const xy2 = HalfEdge.nodeToXY(inside2); ck.testExactNumber(xy2[0], inside2.x); ck.testExactNumber(xy2[1], inside2.y); const maskBP = HalfEdge.nodeToMaskString(inside0); const maskBPX = HalfEdge.nodeToMaskString(outside2); ck.testTrue(maskBP === "BP" || maskBP === "PB"); ck.testTrue(maskBPX === "BPX"); const mask1 = HalfEdge.nodeToIdXYString(outside2); const jNode = HalfEdge.nodeToIdMaskXY(outside2); ck.testTrue(jNode.id.toString() === HalfEdge.nodeToIdString(outside2)); ck.testTrue(jNode.xy[0] === outside2.x); ck.testTrue(jNode.xy[1] === outside2.y); const ii = mask1.lastIndexOf("]"); ck.testExactNumber(ii + 1, mask1.length, "IdXYString"); if (ck.getNumErrors() !== 0) logGraph(graph, "NullFace and mask string tests"); expect(ck.getNumErrors()).equals(0); }); it("HorizontalScanFraction", () => { const ck = new Checker(); const graph = new HalfEdgeGraph(); const y0 = 2; const y1 = 5; const f = 0.4; const ym = Geometry.interpolate(y0, f, y1); const y0Edge = graph.addEdgeXY(0, y0, 10, y0); const y01Edge = graph.addEdgeXY(1, y0, 10, y1); const q = HalfEdge.horizontalScanFraction(y0Edge, y0); const q1 = HalfEdge.horizontalScanFraction(y0Edge, y1); ck.testUndefined(q1); ck.testTrue(q instanceof HalfEdge && q === y0Edge); const fm = HalfEdge.horizontalScanFraction(y01Edge, ym); ck.testTrue(Number.isFinite(fm as number) && Geometry.isSameCoordinate(f, fm as number)); const f0 = HalfEdge.horizontalScanFraction(y01Edge, y0); ck.testTrue(Number.isFinite(f0 as number) && Geometry.isSameCoordinate(0, f0 as number)); expect(ck.getNumErrors()).equals(0); }); it("CoordinatesOnEdges", () => { const ck = new Checker(); const graph = new HalfEdgeGraph(); const edgeA = graph.addEdgeXY(1, 2, 4, 3); const edgeB = graph.addEdgeXY(2, -1, 3, 4); const uvAB = HalfEdge.transverseIntersectionFractions(edgeA, edgeB); if (ck.testPointer(uvAB, "intersection of edges exists") && uvAB) { const pointA = edgeA.fractionToPoint2d(uvAB.x); const pointB = edgeB.fractionToPoint2d(uvAB.y); ck.testPoint2d(pointA, pointB, "intersection xy"); } ck.testUndefined(HalfEdge.transverseIntersectionFractions(edgeA, edgeA), "identical edges"); expect(ck.getNumErrors()).equals(0); }); it("InSector", () => { const ck = new Checker(); const graph = new HalfEdgeGraph(); const originEdges = []; const edge0 = graph.addEdgeXY(0, 0, 1, 0); const edge90 = graph.addEdgeXY(0, 0, 0, 1); const edge180 = graph.addEdgeXY(0, 0, -1, 0); const edge270 = graph.addEdgeXY(0, 0, 0, -1); originEdges.push(edge0, edge90, edge180, edge270); HalfEdge.pinch(edge0, edge90); HalfEdge.pinch(edge90, edge180); HalfEdge.pinch(edge180, edge270); const danglers = []; for (const e of originEdges) { const outerNode = e.faceSuccessor; const edgeVector = e.vectorToFaceSuccessor(); const perpEdge = graph.addEdgeXY(outerNode.x, outerNode.y, outerNode.x - edgeVector.y, outerNode.y + outerNode.x); HalfEdge.pinch(outerNode, perpEdge); danglers.push(perpEdge.faceSuccessor); } const aroundOrigin = edge0.collectAroundVertex(); const aroundSpider = edge0.collectAroundFace(); ck.testExactNumber(4, aroundOrigin.length); ck.testExactNumber(16, aroundSpider.length); for (const sectorAtOrigin of originEdges) { const nodeA = sectorAtOrigin.faceSuccessor; // That's on an axis const nodeB = nodeA.faceSuccessor; // That's rotated into the sector containing originEdge // const nodeC = nodeB.vertexSuccessor; // That's on the axis but strictly on the other side of the sector. Nebulous containment status !! // nodeB is "in" sectorAtOrigin but NOT in any of the other sectors around the origin. for (const nodeE of originEdges) { ck.testBoolean(nodeE === sectorAtOrigin, HalfEdge.isNodeVisibleInSector(nodeB, nodeE)); } ck.testTrue(HalfEdge.isNodeVisibleInSector(sectorAtOrigin, nodeB)); } // build a degenerate face !!! const edgeQ0 = graph.addEdgeXY(2, 0, 3, 0); const edgeQ1 = graph.addEdgeXY(2, 0, 3, 0); HalfEdge.pinch(edgeQ0, edgeQ1); HalfEdge.pinch(edgeQ0.faceSuccessor, edgeQ1.faceSuccessor); ck.testTrue(HalfEdge.isNodeVisibleInSector(edgeQ0, edgeQ0.faceSuccessor), "null face inside"); ck.testTrue(HalfEdge.isNodeVisibleInSector(edgeQ1, edgeQ1.faceSuccessor), " null face inside"); ck.testFalse(HalfEdge.isNodeVisibleInSector(edgeQ1, edgeQ0), "null face outside"); ck.testFalse(HalfEdge.isNodeVisibleInSector(edgeQ0, edgeQ1), "null face outside"); ck.testFalse(HalfEdge.isNodeVisibleInSector(edge0, edgeQ0), "null face outside"); // edgeR1 is a 180 degree sector .... const edgeR0 = graph.addEdgeXY(-1, 3, 1, 3); const edgeR1 = graph.addEdgeXY(1, 3, 3, 3); HalfEdge.pinch(edgeR0.faceSuccessor, edgeR1); ck.testFalse(HalfEdge.isNodeVisibleInSector(edge0, edgeR1), "back side of line"); ck.testTrue(HalfEdge.isNodeVisibleInSector(edge0, edgeR1.vertexSuccessor), "front side side of line"); // these edges have origins on the extended graph edges ... only the one beyond R1 is considered in ... const edgeS0 = graph.addEdgeXY(-3, 3, 0, 5); const edgeS1 = graph.addEdgeXY(5, 3, 0, 5); ck.testFalse(HalfEdge.isNodeVisibleInSector(edgeS0, edgeR1), "on line before"); ck.testTrue(HalfEdge.isNodeVisibleInSector(edgeS1, edgeR1), "on line after"); const otherSide = edgeR1.vertexSuccessor; ck.testFalse(HalfEdge.isNodeVisibleInSector(edgeS1, otherSide), "on line before"); ck.testTrue(HalfEdge.isNodeVisibleInSector(edgeS0, otherSide), "on line after"); edgeQ0.setMask(HalfEdgeMask.NULL_FACE); // this exercises an obscure branch ... ck.testTrue(HalfEdge.nodeToMaskString(edgeQ0) === "N"); ck.testUndefined(HalfEdge.horizontalScanFraction01(edgeQ0, 20.0), " No crossing of horizontal edge"); ck.testExactNumber(0.5, HalfEdge.horizontalScanFraction01(edge90, 0.5)!, "scan crossing on simple vertical edge"); expect(ck.getNumErrors()).equals(0); }); it("isMaskedAroundFace", () => { const ck = new Checker(); const graph = new HalfEdgeGraph(); const pointA0 = Point2d.create(1, 2); const pointA1 = Point2d.create(4, 3); const edgeA = graph.addEdgeXY(pointA0.x, pointA0.y, pointA1.x, pointA1.y); const edgeB = graph.addEdgeXY(pointA0.x, pointA0.y, 3, 4); ck.testFalse(edgeA.findAroundFace(edgeB)); const pointB0 = edgeA.getPoint2d(); const pointB1 = edgeA.faceSuccessor.getPoint2d(); ck.testPoint2d(pointA0, pointB0); ck.testPoint2d(pointA1, pointB1); const vectorB01 = edgeA.getVector3dAlongEdge(); const vectorA01 = Vector3d.createStartEnd(pointA0, pointA1); ck.testVector3d(vectorA01, vectorB01); HalfEdge.pinch(edgeA, edgeB); ck.testTrue(edgeA.findAroundFace(edgeB.faceSuccessor)); // There are 4 edges around the face. ck.testFalse(edgeA.isMaskedAroundFace(HalfEdgeMask.BOUNDARY_EDGE, true)); ck.testTrue(edgeA.isMaskedAroundFace(HalfEdgeMask.BOUNDARY_EDGE, false)); edgeA.setMask(HalfEdgeMask.BOUNDARY_EDGE); ck.testFalse(edgeA.isMaskedAroundFace(HalfEdgeMask.BOUNDARY_EDGE, true)); ck.testFalse(edgeA.isMaskedAroundFace(HalfEdgeMask.BOUNDARY_EDGE, false)); edgeA.setMaskAroundFace(HalfEdgeMask.BOUNDARY_EDGE); ck.testTrue(edgeA.isMaskedAroundFace(HalfEdgeMask.BOUNDARY_EDGE, true)); ck.testFalse(edgeA.isMaskedAroundFace(HalfEdgeMask.BOUNDARY_EDGE, false)); let numNodes = 0; graph.announceNodes( (_g: HalfEdgeGraph, _node: HalfEdge) => { numNodes++; return true; } ); ck.testExactNumber(4, numNodes); // coverage for early exit from full-graph node, face, and vertex loops numNodes = 0; numNodes = 0; graph.announceNodes((_g: HalfEdgeGraph, node: HalfEdge) => { if (node === edgeA) return false; numNodes++; return true; }); ck.testLT (numNodes, 4); numNodes = 0; graph.announceVertexLoops( (_g: HalfEdgeGraph, node: HalfEdge) => { return !node.findAroundVertex(edgeB); } ); ck.testLT (numNodes, 3); numNodes = 0; graph.announceFaceLoops( (_g: HalfEdgeGraph, node: HalfEdge) => { return !node.findAroundFace(edgeB); } ); ck.testExactNumber (numNodes, 0, "Graph's only face contains all nodes"); expect(ck.getNumErrors()).equals(0); }); it("NodeXYZUV", () => { const ck = new Checker(); const graph = new HalfEdgeGraph(); const pointA0 = Point3d.create(1, 2); const pointA1 = Point3d.create(4, 3); const edgeA = graph.addEdgeXY(pointA0.x, pointA0.y, pointA1.x, pointA1.y); const _edgeB = graph.addEdgeXY(pointA0.x, pointA0.y, 3, 4); const pointQ = Point3d.create(10, 20, 30); const pointU0 = Point2d.create(5, 12); const markupA = NodeXYZUV.create(edgeA, 10, 20, 30, pointU0.x, pointU0.y); const pointR = markupA.getXYZAsPoint3d(); ck.testPoint3d(pointQ, pointR); const pointU1 = markupA.getUVAsPoint2d(); ck.testTrue(pointU0.isAlmostEqual(pointU1)); ck.testPoint3d(pointQ, pointR); ck.testExactNumber(0, markupA.classifyU(pointU0.x, 0)); ck.testExactNumber(1, markupA.classifyU(pointU0.x-3, 0)); ck.testExactNumber(-1, markupA.classifyU(pointU0.x + 2, 0)); const tol = 1.0e-5; const epsilon = 0.9 * tol; ck.testExactNumber(0, markupA.classifyU(pointU0.x + epsilon, tol)); ck.testExactNumber(0, markupA.classifyU(pointU0.x - epsilon, tol)); ck.testExactNumber(1, markupA.classifyU(pointU0.x-3 * epsilon, tol)); ck.testExactNumber(-1, markupA.classifyU(pointU0.x + 2 * epsilon, tol)); expect(ck.getNumErrors()).equals(0); }); it("MovingPosition", () => { const ck = new Checker(); const outputManager = new OutputManager(); const graph = new HalfEdgeGraph(); // 5 A D // 4 Q // 3 P // 2 B C // 1 2 3 4 5 6 7 8 const pointA = Point3d.create(1, 5); const pointB = Point3d.create(1, 2); const pointC = Point3d.create(4, 2); const pointD = Point3d.create(8, 5); const pointP = Point3d.create(2, 3); const pointQ = Point3d.create(4, 4); const edgeA = graph.addEdgeXY(pointA.x, pointA.y, pointB.x, pointB.y); const edgeB = graph.addEdgeXY(pointB.x, pointB.y, pointC.x, pointC.y); const edgeC = graph.addEdgeXY(pointC.x, pointC.y, pointA.x, pointA.y); const edgeCD = graph.addEdgeXY(pointC.x, pointC.y, pointD.x, pointD.y); const edgeDA = graph.addEdgeXY(pointD.x, pointD.y, pointA.x, pointA.y); HalfEdge.pinch(edgeA.faceSuccessor, edgeB); HalfEdge.pinch(edgeB.faceSuccessor, edgeC); HalfEdge.pinch(edgeC.faceSuccessor, edgeA); HalfEdge.pinch(edgeCD, edgeC.vertexPredecessor); HalfEdge.pinch(edgeDA.faceSuccessor, edgeA.vertexSuccessor); HalfEdge.pinch(edgeCD.faceSuccessor, edgeDA); outputManager.z0 = -0.001; outputManager.drawGraph(graph); outputManager.z0 = 0.0; ck.testExactNumber(3, graph.countFaceLoops()); ck.testExactNumber(4, graph.countVertexLoops()); const walker = HalfEdgePositionDetail.createEdgeAtFraction(edgeA, 0.4); const context = InsertAndRetriangulateContext.create(graph); markPosition(outputManager, walker); ck.testTrue(walker.isEdge, "start on edge"); moveAndMark(ck, outputManager, context, walker, pointP, HalfEdgeTopo.Face); moveAndMark(ck, outputManager, context, walker, pointQ, HalfEdgeTopo.Face); moveAndMark(ck, outputManager, context, walker, pointA, HalfEdgeTopo.Vertex); { // move sideways along an edge ... const pointE1 = pointA.interpolate(0.4, pointC); const pointE2 = pointA.interpolate(0.6, pointC); moveAndMark(ck, outputManager, context, walker, pointE1, HalfEdgeTopo.Edge); moveAndMark(ck, outputManager, context, walker, pointE2, HalfEdgeTopo.Edge); moveAndMark(ck, outputManager, context, walker, pointA, HalfEdgeTopo.Vertex); moveAndMark(ck, outputManager, context, walker, pointE2, HalfEdgeTopo.Edge); moveAndMark(ck, outputManager, context, walker, pointC, HalfEdgeTopo.Vertex); moveAndMark(ck, outputManager, context, walker, pointE2, HalfEdgeTopo.Edge); const pointAC2 = pointA.interpolate(2.0, pointC); moveAndMark(ck, outputManager, context, walker, pointAC2, HalfEdgeTopo.Vertex); moveAndMark(ck, outputManager, context, walker, pointE2, HalfEdgeTopo.Edge); const pointACNeg = pointA.interpolate(-1.0, pointC); moveAndMark(ck, outputManager, context, walker, pointACNeg, HalfEdgeTopo.Vertex); } moveAndMark(ck, outputManager, context, walker, pointA.interpolate (0.5, pointB), HalfEdgeTopo.Edge); // Exterior !!!! // moveTo does not identify this clearly. const pointZ1 = Point3d.create(5, 0, 0); moveAndMark(ck, outputManager, context, walker, pointZ1, undefined); const pointZ2 = Point3d.create(0.5, 0, 0); moveAndMark(ck, outputManager, context, walker, pointZ2, undefined); outputManager.saveToFile("Graph", "MovingPosition"); expect(ck.getNumErrors()).equals(0); }); }); const markerSize = 0.04; function markPosition(out: OutputManager, p: HalfEdgePositionDetail | undefined) { if (p) { if (p.isFace) out.drawPlus(p.clonePoint(), markerSize); else if (p.isEdge) { const nodeA = p.node!; const edgeVector = nodeA.getVector3dAlongEdge(); const perpVector = edgeVector.unitPerpendicularXY(); const edgePoint = p.clonePoint(); out.drawLines([edgePoint, edgePoint.plusXYZ(markerSize * perpVector.x, markerSize * perpVector.y)]); } else if (p.isVertex) { const nodeA = p.node!; const xyz = p.clonePoint(); const edgeVectorA = nodeA.getVector3dAlongEdge(); const edgeVectorB = nodeA.facePredecessor.getVector3dAlongEdge(); edgeVectorA.normalizeInPlace(); edgeVectorB.normalizeInPlace(); const xyz1 = xyz.plus2Scaled(edgeVectorA, markerSize, edgeVectorB, -markerSize); out.drawLines([xyz, xyz1]); } } } function moveAndMark(ck: Checker, out: OutputManager, context: InsertAndRetriangulateContext, position: HalfEdgePositionDetail, targetPoint: Point3d, expectedTopo: HalfEdgeTopo | undefined) { const xyz0 = position.clonePoint(); context.moveToPoint(position, targetPoint); out.drawLines([xyz0, position.clonePoint()]); markPosition(out, position); if (expectedTopo !== undefined) { ck.testExactNumber(expectedTopo as number, position.getTopo()); } else { ck.testTrue(position.isExteriorTarget, "Expect exterior target setting"); } }
the_stack
"use strict"; export interface Image { url: string; height: Nullable<number>; width: Nullable<number>; } enum Capability { VIDEO_OUT = "video_out", AUDIO_OUT = "audio_out", VIDEO_IN = "video_in", AUDIO_IN = "audio_in", MULTIZONE_GROUP = "multizone_group" } enum ReceiverType { CAST = "cast", DIAL = "dial", HANGOUT = "hangout", CUSTOM = "custom" } export interface SenderApplication { packageId: Nullable<string>; platform: string; url: Nullable<string>; } enum VolumeControlType { ATTENUATION = "attenuation", FIXED = "fixed", MASTER = "master" } export interface Volume { controlType?: VolumeControlType; stepInterval?: number; level: Nullable<number>; muted: Nullable<boolean>; } // Media enum IdleReason { CANCELLED = "CANCELLED", INTERRUPTED = "INTERRUPTED", FINISHED = "FINISHED", ERROR = "ERROR" } enum HlsSegmentFormat { AAC = "aac", AC3 = "ac3", MP3 = "mp3", TS = "ts", TS_AAC = "ts_aac", E_AC3 = "e_ac3", FMP4 = "fmp4" } export enum HlsVideoSegmentFormat { MPEG2_TS = "mpeg2_ts", FMP4 = "fmp4" } enum MetadataType { GENERIC, MOVIE, TV_SHOW, MUSIC_TRACK, PHOTO, AUDIOBOOK_CHAPTER } enum PlayerState { IDLE = "IDLE", PLAYING = "PLAYING", PAUSED = "PAUSED", BUFFERING = "BUFFERING" } enum RepeatMode { OFF = "REPEAT_OFF", ALL = "REPEAT_ALL", SINGLE = "REPEAT_SINGLE", ALL_AND_SHUFFLE = "REPEAT_ALL_AND_SHUFFLE" } enum ResumeState { PLAYBACK_START = "PLAYBACK_START", PLAYBACK_PAUSE = "PLAYBACK_PAUSE" } enum StreamType { BUFFERED = "BUFFERED", LIVE = "LIVE", OTHER = "OTHER" } enum TrackType { TEXT = "TEXT", AUDIO = "AUDIO", VIDEO = "VIDEO" } export enum UserAction { LIKE = "LIKE", DISLIKE = "DISLIKE", FOLLOW = "FOLLOW", UNFOLLOW = "UNFOLLOW" } interface Break { breakClipIds: string[]; duration?: number; id: string; isEmbedded?: boolean; isWatched: boolean; position: number; } interface BreakClip { clickThroughUrl?: string; contentId?: string; contentType?: string; contentUrl?: string; customData?: {}; duration?: number; id: string; hlsSegmentFormat?: HlsSegmentFormat; posterUrl?: string; title?: string; vastAdsRequest?: VastAdsRequest; whenSkippable?: number; } interface TextTrackStyle { backgroundColor: Nullable<string>; customData: any; edgeColor: Nullable<string>; edgeType: Nullable<string>; fontFamily: Nullable<string>; fontGenericFamily: Nullable<string>; fontScale: Nullable<number>; fontStyle: Nullable<string>; foregroundColor: Nullable<string>; windowColor: Nullable<string>; windowRoundedCornerRadius: Nullable<number>; windowType: Nullable<string>; } interface Track { customData: any; language: Nullable<string>; name: Nullable<string>; subtype: Nullable<string>; trackContentId: Nullable<string>; trackContentType: Nullable<string>; trackId: string; type: TrackType; } interface UserActionState { customData: any; userAction: UserAction; } interface VastAdsRequest { adsResponse?: string; adTagUrl?: string; } type Metadata = | GenericMediaMetadata | MovieMediaMetadata | MusicTrackMediaMetadata | PhotoMediaMetadata | TvShowMediaMetadata; interface MediaInformation { atvEntity?: string; breakClips?: BreakClip[]; breaks?: Break[]; contentId: string; contentType: string; contentUrl?: string; customData: any; duration: Nullable<number>; entity?: string; hlsSegmentFormat?: HlsSegmentFormat; hlsVideoSegmentFormat?: HlsVideoSegmentFormat; metadata: Nullable<Metadata>; startAbsoluteTime?: number; streamType: StreamType; textTrackStyle: Nullable<TextTrackStyle>; tracks: Nullable<Track[]>; userActionStates?: UserActionState[]; vmapAdsRequest?: VastAdsRequest; } interface GenericMediaMetadata { images?: Image[]; metadataType: number; releaseDate?: string; releaseYear?: number; subtitle?: string; title?: string; type: MetadataType.GENERIC; } interface MovieMediaMetadata { images?: Image[]; metadataType: number; releaseDate?: string; releaseYear?: number; studio?: string; subtitle?: string; title?: string; type: MetadataType.MOVIE; } interface TvShowMediaMetadata { episode?: number; episodeNumber?: number; episodeTitle?: string; images?: Image[]; metadataType: number; originalAirdate?: string; releaseYear?: number; season?: number; seasonNumber?: number; seriesTitle?: string; title?: string; type: MetadataType.TV_SHOW; } interface MusicTrackMediaMetadata { albumArtist?: string; albumName?: string; artist?: string; artistName?: string; composer?: string; discNumber?: number; images?: Image[]; metadataType: number; releaseDate?: string; releaseYear?: number; songName?: string; title?: string; trackNumber?: number; type: MetadataType.MUSIC_TRACK; } interface PhotoMediaMetadata { artist?: string; creationDateTime?: string; height?: number; images?: Image[]; latitude?: number; location?: string; longitude?: number; metadataType: number; title?: string; type: MetadataType.PHOTO; width?: number; } interface QueueItem { activeTrackIds: Nullable<number[]>; autoplay: boolean; customData: any; itemId: Nullable<number>; media: MediaInformation; playbackDuration: Nullable<number>; preloadTime: number; startTime: number; } export interface MediaStatus { mediaSessionId: number; media?: MediaInformation; playbackRate: number; playerState: PlayerState; idleReason?: IdleReason; items?: QueueItem[]; currentTime: number; supportedMediaCommands: number; repeatMode: RepeatMode; volume: Volume; customData: unknown; } interface ReceiverDisplayStatus { showStop: Nullable<boolean>; statusText: string; appImages: Image[]; } export interface Receiver { displayStatus: Nullable<ReceiverDisplayStatus>; isActiveInput: Nullable<boolean>; receiverType: ReceiverType; label: string; friendlyName: string; capabilities: Capability[]; volume: Nullable<Volume>; } export interface ReceiverApplication { appId: string; appType: string; displayName: string; iconUrl: string; isIdleScreen: boolean; launchedFromCloud: boolean; namespaces: Array<{ name: string }>; sessionId: string; statusText: string; transportId: string; universalAppId: string; } export interface ReceiverStatus { applications?: ReceiverApplication[]; isActiveInput?: boolean; isStandBy?: boolean; volume: Volume; } interface ReqBase { requestId: number; } // NS: urn:x-cast:com.google.cast.receiver export type SenderMessage = | (ReqBase & { type: "LAUNCH"; appId: string }) | (ReqBase & { type: "STOP"; sessionId: string }) | (ReqBase & { type: "GET_STATUS" }) | (ReqBase & { type: "GET_APP_AVAILABILITY"; appId: string[] }) | (ReqBase & { type: "SET_VOLUME"; volume: Volume }); export type ReceiverMessage = | (ReqBase & { type: "RECEIVER_STATUS"; status: ReceiverStatus }) | (ReqBase & { type: "LAUNCH_ERROR"; reason: string }); interface MediaReqBase extends ReqBase { mediaSessionId: number; customData?: unknown; } // NS: urn:x-cast:com.google.cast.media export type SenderMediaMessage = | (MediaReqBase & { type: "PLAY" }) | (MediaReqBase & { type: "PAUSE" }) | (MediaReqBase & { type: "MEDIA_GET_STATUS" }) | (MediaReqBase & { type: "STOP" }) | (MediaReqBase & { type: "MEDIA_SET_VOLUME"; volume: Volume }) | (MediaReqBase & { type: "SET_PLAYBACK_RATE"; playbackRate: number }) | (ReqBase & { type: "LOAD"; activeTrackIds: Nullable<number[]>; atvCredentials?: string; atvCredentialsType?: string; autoplay: Nullable<boolean>; currentTime: Nullable<number>; customData?: unknown; media: MediaInformation; sessionId: Nullable<string>; }) | (MediaReqBase & { type: "SEEK"; resumeState: Nullable<ResumeState>; currentTime: Nullable<number>; }) | (MediaReqBase & { type: "EDIT_TRACKS_INFO"; activeTrackIds: Nullable<number[]>; textTrackStyle: Nullable<string>; }) // QueueLoadRequest | (MediaReqBase & { type: "QUEUE_LOAD"; items: QueueItem[]; startIndex: number; repeatMode: string; sessionId: Nullable<string>; }) // QueueInsertItemsRequest | (MediaReqBase & { type: "QUEUE_INSERT"; items: QueueItem[]; insertBefore: Nullable<number>; sessionId: Nullable<string>; }) // QueueUpdateItemsRequest | (MediaReqBase & { type: "QUEUE_UPDATE"; items: QueueItem[]; sessionId: Nullable<string>; }) // QueueJumpRequest | (MediaReqBase & { type: "QUEUE_UPDATE"; jump: Nullable<number>; currentItemId: Nullable<number>; sessionId: Nullable<string>; }) // QueueRemoveItemsRequest | (MediaReqBase & { type: "QUEUE_REMOVE"; itemIds: number[]; sessionId: Nullable<string>; }) // QueueReorderItemsRequest | (MediaReqBase & { type: "QUEUE_REORDER"; itemIds: number[]; insertBefore: Nullable<number>; sessionId: Nullable<string>; }) // QueueSetPropertiesRequest | (MediaReqBase & { type: "QUEUE_UPDATE"; repeatMode: Nullable<string>; sessionId: Nullable<string>; }); export type ReceiverMediaMessage = | (MediaReqBase & { type: "MEDIA_STATUS"; status: MediaStatus[] }) | (MediaReqBase & { type: "INVALID_PLAYER_STATE" }) | (MediaReqBase & { type: "LOAD_FAILED" }) | (MediaReqBase & { type: "LOAD_CANCELLED" }) | (MediaReqBase & { type: "INVALID_REQUEST" });
the_stack
// Ledger settings const imageName = "ghcr.io/hyperledger/cactus-fabric2-all-in-one"; const imageVersion = "2021-09-02--fix-876-supervisord-retries"; const fabricEnvVersion = "2.2.0"; const fabricEnvCAVersion = "1.4.9"; const ledgerUserName = "appUser"; const ledgerChannelName = "mychannel"; const ledgerContractName = "basic"; // Log settings const testLogLevel: LogLevelDesc = "info"; const sutLogLevel: LogLevelDesc = "info"; import { FabricTestLedgerV1, pruneDockerAllIfGithubAction, } from "@hyperledger/cactus-test-tooling"; import { LogLevelDesc, LoggerProvider, Logger, } from "@hyperledger/cactus-common"; import { SocketIOApiClient } from "@hyperledger/cactus-api-client"; import { enrollAdmin, enrollUser, getUserCryptoFromWallet, } from "./fabric-setup-helpers"; import fs from "fs"; import path from "path"; import os from "os"; import "jest-extended"; import { Server as HttpsServer } from "https"; // Logger setup const log: Logger = LoggerProvider.getOrCreate({ label: "fabric-socketio-connector.test", level: testLogLevel, }); // Path to sample CA used by the test - creating new EC certs for each run is to verbose for our purpose const sampleFabricCAPath = path.join( process.cwd(), "packages", "cactus-plugin-ledger-connector-fabric-socketio", "sample-config", "CA", ); const connectorCertPath = path.join(sampleFabricCAPath, "connector.crt"); const connectorPrivKeyPath = path.join(sampleFabricCAPath, "connector.priv"); /** * Main test suite */ describe("Fabric-SocketIO connector tests", () => { let ledger: FabricTestLedgerV1; let connectorCertValue: string; let connectorPrivKeyValue: string; let tmpWalletDir: string; let connectorServer: HttpsServer; let apiClient: SocketIOApiClient; ////////////////////////////////// // Environment Setup ////////////////////////////////// /** * @param connectionProfile - Fabric connection profile JSON * @param connectorCert - connector-fabric-socketio server certificate * @param connectorPrivKey - connector-fabric-socketio server private key * @param walletDir - connector-fabric-socketio internal wallet path * @param adminName - ledger admin username * @param adminSecret - ledger admin secret * @returns fabric-socketio conenctor config JSON */ function createFabricConnectorConfig( connectionProfile: Record<string, any>, connectorCert: string, connectorPrivKey: string, walletDir: string, adminName: string, adminSecret: string, ) { // Get Org CA const caId = connectionProfile.organizations.Org1.certificateAuthorities[0]; log.debug("Use CA:", caId); // Get Orderer ID const ordererId = connectionProfile.channels[ledgerChannelName].orderers[0]; log.debug("Use Orderer:", ordererId); const connectorConfig: any = { sslParam: { port: 0, // random port keyValue: connectorPrivKey, certValue: connectorCert, }, logLevel: sutLogLevel, fabric: { mspid: connectionProfile.organizations.Org1.mspid, keystore: walletDir, connUserName: ledgerUserName, contractName: ledgerContractName, peers: [], // will be filled below orderer: { name: connectionProfile.orderers[ordererId].grpcOptions[ "ssl-target-name-override" ], url: connectionProfile.orderers[ordererId].url, tlscaValue: connectionProfile.orderers[ordererId].tlsCACerts.pem, }, ca: { name: connectionProfile.certificateAuthorities[caId].caName, url: connectionProfile.certificateAuthorities[caId].url, }, submitter: { name: adminName, secret: adminSecret, }, channelName: ledgerChannelName, chaincodeId: ledgerContractName, }, }; // Add peers connectionProfile.organizations.Org1.peers.forEach((peerName: string) => { log.debug("Add Peer:", peerName); const peer = connectionProfile.peers[peerName]; connectorConfig.fabric.peers.push({ name: peer.grpcOptions["ssl-target-name-override"], requests: peer.url, tlscaValue: peer.tlsCACerts.pem, }); }); const configJson = JSON.stringify(connectorConfig); log.debug("Connector Config:", configJson); return configJson; } beforeAll(async () => { log.info("Prune Docker..."); await pruneDockerAllIfGithubAction({ logLevel: testLogLevel }); log.info("Start FabricTestLedgerV1..."); log.debug("Version:", fabricEnvVersion, "CA Version:", fabricEnvCAVersion); ledger = new FabricTestLedgerV1({ emitContainerLogs: false, publishAllPorts: true, logLevel: testLogLevel, imageName, imageVersion, envVars: new Map([ ["FABRIC_VERSION", fabricEnvVersion], ["CA_VERSION", fabricEnvCAVersion], ]), }); log.debug("Fabric image:", ledger.getContainerImageName()); await ledger.start(); // Get connection profile log.info("Get fabric connection profile for Org1..."); const connectionProfile = await ledger.getConnectionProfileOrg1(); expect(connectionProfile).toBeTruthy(); // Get admin credentials const [adminName, adminSecret] = ledger.adminCredentials; // Setup wallet log.info("Create temp dir for wallet - will be removed later..."); tmpWalletDir = fs.mkdtempSync(path.join(os.tmpdir(), "fabric-test-wallet")); expect(tmpWalletDir).toBeTruthy(); await enrollAdmin(connectionProfile, tmpWalletDir, adminName, adminSecret); await enrollUser( connectionProfile, tmpWalletDir, ledgerUserName, adminName, ); // Read connector private key and certificate connectorCertValue = fs.readFileSync(connectorCertPath, "ascii"); connectorPrivKeyValue = fs.readFileSync(connectorPrivKeyPath, "ascii"); // Get connector config log.info("Export connector config before loading the module..."); process.env["NODE_CONFIG"] = createFabricConnectorConfig( connectionProfile, connectorCertValue, connectorPrivKeyValue, tmpWalletDir, adminName, adminSecret, ); // Load connector module const connectorModule = await import("../../../main/typescript/index"); // Run the connector connectorServer = await connectorModule.startFabricSocketIOConnector(); expect(connectorServer).toBeTruthy(); const connectorAddress = connectorServer.address(); if (!connectorAddress || typeof connectorAddress === "string") { throw new Error("Unexpected fabric connector AddressInfo type"); } log.info( "Fabric-SocketIO Connector started on:", `${connectorAddress.address}:${connectorAddress.port}`, ); // Create ApiClient instance const apiConfigOptions = { validatorID: "fabric-socketio-test", validatorURL: `https://localhost:${connectorAddress.port}`, validatorKeyValue: connectorCertValue, logLevel: sutLogLevel, maxCounterRequestID: 1000, syncFunctionTimeoutMillisecond: 10000, socketOptions: { rejectUnauthorized: false, reconnection: false, timeout: 60000, }, }; log.debug("ApiClient config:", apiConfigOptions); apiClient = new SocketIOApiClient(apiConfigOptions); }); afterAll(async () => { log.info("FINISHING THE TESTS"); if (ledger) { log.info("Stop the fabric ledger..."); await ledger.stop(); await ledger.destroy(); } if (apiClient) { log.info("Close ApiClient connection..."); apiClient.close(); } if (connectorServer) { log.info("Stop the fabric connector..."); await new Promise<void>((resolve) => connectorServer.close(() => resolve()), ); } if (tmpWalletDir) { log.info("Remove tmp wallet dir", tmpWalletDir); fs.rmSync(tmpWalletDir, { recursive: true }); } log.info("Prune Docker..."); await pruneDockerAllIfGithubAction({ logLevel: testLogLevel }); }); ////////////////////////////////// // Test Helpers ////////////////////////////////// /** * Calls `GetAllAssets` from `basic` CC on the ledger using apiClient.sendSyncRequest * @returns List of assets */ async function getAllAssets() { const contract = { channelName: ledgerChannelName, contractName: ledgerContractName, }; const method = { type: "evaluateTransaction", command: "GetAllAssets", }; const args = { args: [] }; const results = await apiClient.sendSyncRequest(contract, method, args); expect(results).toBeTruthy(); expect(results.status).toBe(200); expect(results.data).toBeTruthy(); expect(results.data.length).toBeGreaterThanOrEqual(5); // we assume at least 5 assets in future tests return results.data as { ID: string }[]; } /** * Calls `GetAllAssets` from `basic` CC on the ledger using apiClient.sendSyncRequest * * @param assetID - Asset to read from the ledger. * @returns asset object */ async function readAsset(assetID: string) { const contract = { channelName: ledgerChannelName, contractName: ledgerContractName, }; const method = { type: "evaluateTransaction", command: "ReadAsset", }; const args = { args: [assetID] }; const results = await apiClient.sendSyncRequest(contract, method, args); expect(results).toBeTruthy(); expect(results.status).toBe(200); expect(results.data).toBeTruthy(); return results.data; } /** * Calls connector function `sendSignedProposal`, assert correct response, and returns signed proposal. * @param txProposal - Transaction data we want to send (CC function name, arguments, chancode ID, channel ID) * @returns Signed proposal that can be feed into `sendSignedProposal` */ async function getSignedProposal(txProposal: { fcn: string; args: string[]; chaincodeId: string; channelId: string; }) { const [certPem, privateKeyPem] = await getUserCryptoFromWallet( ledgerUserName, tmpWalletDir, ); const contract = { channelName: ledgerChannelName }; const method = { type: "function", command: "sendSignedProposal" }; const argsParam = { args: { transactionProposalReq: txProposal, certPem, privateKeyPem, }, }; const response = await apiClient.sendSyncRequest( contract, method, argsParam, ); expect(response).toBeTruthy(); expect(response.status).toBe(200); expect(response.data).toBeTruthy(); expect(response.data.signedCommitProposal).toBeTruthy(); expect(response.data.commitReq).toBeTruthy(); expect(response.data.txId).toBeTruthy(); const { signedCommitProposal, commitReq } = response.data; // signedCommitProposal must be Buffer signedCommitProposal.signature = Buffer.from( signedCommitProposal.signature, ); signedCommitProposal.proposal_bytes = Buffer.from( signedCommitProposal.proposal_bytes, ); return { signedCommitProposal, commitReq }; } ////////////////////////////////// // Tests ////////////////////////////////// /** * Read all assets, get single asset, comapre that they return the same asset value without any errors. */ test("Evaluate transaction returns correct data (GetAllAssets and ReadAsset)", async () => { const allAssets = await getAllAssets(); const firstAsset = allAssets.pop(); if (!firstAsset) { throw new Error("Unexpected missing firstAsset"); } const readSingleAsset = await readAsset(firstAsset.ID); expect(readSingleAsset).toEqual(firstAsset); }); /** * Send transaction proposal to be signed with keys attached to the request (managed by BLP), * and then send signed transaction to the ledger. */ test("Signining proposal and sending it to the ledger works", async () => { // Get asset data to be transfered const allAssets = await getAllAssets(); const assetId = allAssets[1].ID; const newOwnerName = "SignAndSendXXX"; // Prepare signed proposal const txProposal = { fcn: "TransferAsset", args: [assetId, newOwnerName], chaincodeId: ledgerContractName, channelId: ledgerChannelName, }; const signedProposal = await getSignedProposal(txProposal); // Send transaction const contract = { channelName: ledgerChannelName }; const method = { type: "sendSignedTransaction" }; const args = { args: [signedProposal] }; const response = await apiClient.sendSyncRequest(contract, method, args); expect(response).toBeTruthy(); expect(response.status).toBe(200); expect(response.data).toBeTruthy(); expect(response.data.status).toEqual("SUCCESS"); }); /** * Send transaction proposal to be signed with keys from connector wallet (managed by the connector). * Verify correct response from the call. */ test("Signining proposal with connector wallet keys work", async () => { // Get asset data to be transfered const allAssets = await getAllAssets(); const assetId = allAssets[2].ID; const newOwnerName = "SignWithConnectorXXX"; // Prepare signed proposal const contract = { channelName: ledgerChannelName }; const method = { type: "function", command: "sendSignedProposal" }; const argsParam = { args: { transactionProposalReq: { fcn: "TransferAsset", args: [assetId, newOwnerName], chaincodeId: ledgerContractName, channelId: ledgerChannelName, }, }, }; const response = await apiClient.sendSyncRequest( contract, method, argsParam, ); expect(response).toBeTruthy(); expect(response.status).toBe(200); expect(response.data).toBeTruthy(); expect(response.data.signedCommitProposal).toBeTruthy(); expect(response.data.commitReq).toBeTruthy(); expect(response.data.txId).toBeTruthy(); }); /** * Start monitoring for fabric events. * Send new transaction to the ledger (async) * Finish after receiving event for matching transaction function. * This function needs separate timeout, in case of error (no event was received). */ test( "Monitoring for transaction sending works", async () => { // Get asset data to be transfered const allAssets = await getAllAssets(); const assetId = allAssets[3].ID; const newOwnerName = "MonitorChangedXXX"; const txFunctionName = "TransferAsset"; // Start monitoring const monitorPromise = new Promise<void>((resolve, reject) => { apiClient.watchBlocksV1().subscribe({ next(event) { expect(event.status).toBe(200); const matchingEvents = event.blockData.filter( (e) => e.func === txFunctionName, ); if (matchingEvents.length > 0) { resolve(); } }, error(err) { log.error("watchBlocksV1() error:", err); reject(err); }, }); }); // Get signed proposal const signedProposal = await getSignedProposal({ fcn: txFunctionName, args: [assetId, newOwnerName], chaincodeId: ledgerContractName, channelId: ledgerChannelName, }); // Send transaction (async) const contract = { channelName: ledgerChannelName }; const method = { type: "sendSignedTransaction" }; const args = { args: [signedProposal] }; apiClient.sendAsyncRequest(contract, method, args); expect(monitorPromise).toResolve(); }, 60 * 1000, ); });
the_stack
'use strict'; /* tslint:disable:prefer-conditional-expression */ import { IErrorMessage, IIPCSendMessage, IPrintMessage, MessageType, ReceiveTypes, SendTypes } from 'wpilib-riolog'; import { checkResize, scrollImpl, sendMessage } from '../script/implscript'; let paused = false; export function onPause() { const pauseElement = document.getElementById('pause'); if (pauseElement === null) { return; } if (paused === true) { paused = false; pauseElement.innerHTML = 'Pause'; sendMessage({ message: false, type: ReceiveTypes.Pause, }); } else { paused = true; pauseElement.innerHTML = 'Paused: 0'; sendMessage({ message: true, type: ReceiveTypes.Pause, }); } } let discard = false; export function onDiscard() { const dButton = document.getElementById('discard'); if (dButton === null) { return; } if (discard === true) { discard = false; dButton.innerHTML = 'Discard'; sendMessage({ message: false, type: ReceiveTypes.Discard, }); } else { discard = true; dButton.innerHTML = 'Resume'; sendMessage({ message: true, type: ReceiveTypes.Discard, }); } } export function onClear() { const list = document.getElementById('list'); if (list === null) { return; } list.innerHTML = ''; } let showWarnings = true; export function onShowWarnings() { const warningsButton = document.getElementById('showwarnings'); if (warningsButton === null) { return; } if (showWarnings === true) { showWarnings = false; warningsButton.innerHTML = 'Show Warnings'; } else { showWarnings = true; warningsButton.innerHTML = 'Don\'t Show Warnings'; } const ul = document.getElementById('list'); if (ul === null) { return; } const items = ul.getElementsByTagName('li'); // tslint:disable-next-line:prefer-for-of for (let i = 0; i < items.length; ++i) { if (items[i].dataset.type === 'warning') { if (showWarnings === true) { items[i].style.display = 'inline'; } else { items[i].style.display = 'none'; } } } checkResize(); } let showPrints = true; export function onShowPrints() { const printButton = document.getElementById('showprints'); if (printButton === null) { return; } if (showPrints === true) { showPrints = false; printButton.innerHTML = 'Show Prints'; } else { showPrints = true; printButton.innerHTML = 'Don\'t Show Prints'; } const ul = document.getElementById('list'); if (ul === null) { return; } const items = ul.getElementsByTagName('li'); // tslint:disable-next-line:prefer-for-of for (let i = 0; i < items.length; ++i) { if (items[i].dataset.type === 'print') { if (showPrints === true) { items[i].style.display = 'inline'; } else { items[i].style.display = 'none'; } } } checkResize(); } let autoReconnect = true; export function onAutoReconnect() { if (autoReconnect === true) { autoReconnect = false; // send a disconnect sendMessage({ message: false, type: ReceiveTypes.Reconnect, }); } else { autoReconnect = true; sendMessage({ message: true, type: ReceiveTypes.Reconnect, }); } const arButton = document.getElementById('autoreconnect'); if (arButton === null) { return; } if (autoReconnect === true) { arButton.innerHTML = 'Reconnect'; } else { arButton.innerHTML = 'Disconnect'; } } let showTimestamps = false; export function onShowTimestamps() { const tsButton = document.getElementById('timestamps'); if (tsButton === null) { return; } if (showTimestamps === true) { showTimestamps = false; tsButton.innerHTML = 'Show Timestamps'; } else { showTimestamps = true; tsButton.innerHTML = 'Don\'t Show Timestamps'; } const ul = document.getElementById('list'); if (ul === null) { return; } const items = ul.getElementsByTagName('li'); // tslint:disable-next-line:prefer-for-of for (let i = 0; i < items.length; ++i) { const spans = items[i].getElementsByTagName('span'); if (spans === undefined) { continue; } // tslint:disable-next-line:prefer-for-of for (let j = 0; j < spans.length; j++) { const span = spans[j]; if (span.hasAttribute('data-timestamp')) { if (showTimestamps === true) { span.style.display = 'inline'; } else { span.style.display = 'none'; } } } } checkResize(); } export function onSaveLog() { const ul = document.getElementById('list'); if (ul === null) { return; } const items = ul.getElementsByTagName('li'); const logs: string[] = []; // tslint:disable-next-line:prefer-for-of for (let i = 0; i < items.length; ++i) { const m = items[i].dataset.message; if (m === undefined) { return; } logs.push(m); } sendMessage({ message: logs, type: ReceiveTypes.Save, }); } export function onConnect() { const button = document.getElementById('autoreconnect'); if (button === null) { return; } button.style.backgroundColor = 'Green'; } export function onDisconnect() { const button = document.getElementById('autoreconnect'); if (button === null) { return; } button.style.backgroundColor = 'Red'; } function insertMessage(ts: number, line: string, li: HTMLLIElement, color?: string) { const div = document.createElement('div'); const tsSpan = document.createElement('span'); tsSpan.appendChild(document.createTextNode(ts.toFixed(3) + ': ')); tsSpan.dataset.timestamp = 'true'; if (showTimestamps === true) { tsSpan.style.display = 'inline'; } else { tsSpan.style.display = 'none'; } div.appendChild(tsSpan); const span = document.createElement('span'); const split = line.split('\n'); let first = true; for (const item of split) { if (item.trim() === '') { continue; } if (first === false) { span.appendChild(document.createElement('br')); } first = false; const tNode = document.createTextNode(item); span.appendChild(tNode); } if (color !== undefined) { span.style.color = color; } div.appendChild(span); li.appendChild(div); } function insertStackTrace(st: string, li: HTMLLIElement, color?: string) { const div = document.createElement('div'); const split = st.split('\n'); let first = true; for (const item of split) { if (item.trim() === '') { continue; } if (first === false) { div.appendChild(document.createElement('br')); } first = false; const tNode = document.createTextNode('\u00a0\u00a0\u00a0\u00a0 at: ' + item); div.appendChild(tNode); } if (color !== undefined) { div.style.color = color; } li.appendChild(div); } function insertLocation(loc: string, li: HTMLLIElement, color?: string) { const div = document.createElement('div'); const split = loc.split('\n'); let first = true; for (const item of split) { if (item.trim() === '') { continue; } if (first === false) { li.appendChild(document.createElement('br')); } first = false; const tNode = document.createTextNode('\u00a0\u00a0 from: ' + item); li.appendChild(tNode); } if (color !== undefined) { div.style.color = color; } li.appendChild(div); } export function addMessage(message: IPrintMessage | IErrorMessage) { if (message.messageType === MessageType.Print) { addPrint(message as IPrintMessage); } else { addError(message as IErrorMessage); } } function limitList() { const ul = document.getElementById('list') as HTMLUListElement; if (ul === null) { return; } if (ul.childElementCount > 1000 && ul.firstChild !== null) { ul.removeChild(ul.firstChild); } } export function addPrint(message: IPrintMessage) { limitList(); const ul = document.getElementById('list') as HTMLUListElement; if (ul === null) { return; } const li = document.createElement('li'); li.style.fontFamily = 'Consolas, "Courier New", monospace'; insertMessage(message.timestamp, message.line, li); const str = JSON.stringify(message); li.dataset.message = str; li.dataset.type = 'print'; if (showPrints === true) { li.style.display = 'inline'; } else { li.style.display = 'none'; } ul.appendChild(li); } export function expandError(message: IErrorMessage, li: HTMLLIElement, color?: string) { // First append the message insertMessage(message.timestamp, message.details, li, color); // Then append location, tabbed in once insertLocation(message.location, li); // Then append stack trace, tabbed in twice insertStackTrace(message.callStack, li); li.appendChild(document.createElement('br')); } export function addError(message: IErrorMessage) { limitList(); const ul = document.getElementById('list'); if (ul === null) { return; } const li = document.createElement('li'); li.style.fontFamily = 'Consolas, "Courier New", monospace'; const str = JSON.stringify(message); li.dataset.expanded = 'false'; li.dataset.message = str; if (message.messageType === MessageType.Warning) { li.dataset.type = 'warning'; insertMessage(message.timestamp, message.details, li, 'Yellow'); if (showWarnings === true) { li.style.display = 'inline'; } else { li.style.display = 'none'; } } else { li.dataset.type = 'error'; insertMessage(message.timestamp, message.details, li, 'Red'); } li.onclick = () => { if (li.dataset.expanded === 'true') { // shrink li.dataset.expanded = 'false'; if (li.dataset.message === undefined) { return; } const parsed = JSON.parse(li.dataset.message) as IPrintMessage | IErrorMessage; li.innerHTML = ''; if (li.dataset.type === 'warning') { insertMessage(parsed.timestamp, (parsed as IErrorMessage).details, li, 'Yellow'); } else { insertMessage(parsed.timestamp, (parsed as IErrorMessage).details, li, 'Red'); } } else { // expand li.dataset.expanded = 'true'; if (li.dataset.message === undefined) { return; } const parsed = JSON.parse(li.dataset.message); li.innerHTML = ''; if (li.dataset.type === 'warning') { expandError(parsed as IErrorMessage, li, 'Yellow'); } else { expandError(parsed as IErrorMessage, li, 'Red'); } } checkResize(); }; ul.appendChild(li); } window.addEventListener('resize', () => { checkResize(); }); // tslint:disable-next-line:no-any function handleFileSelect(evt: any) { // tslint:disable-next-line:no-unsafe-any const files: FileList = evt.target.files; // filelist const firstFile = files[0]; const reader = new FileReader(); reader.onload = (loaded: Event) => { const target: FileReader = loaded.target as FileReader; const parsed = JSON.parse(target.result as string) as (IPrintMessage | IErrorMessage)[]; for (const p of parsed) { addMessage(p); } checkResize(); }; reader.readAsText(firstFile); } let currentScreenHeight = 100; export function checkResizeImpl(element: HTMLElement) { const allowedHeight = element.clientHeight - currentScreenHeight; const ul = document.getElementById('list'); if (ul === null) { return; } const listHeight = ul.clientHeight; if (listHeight < allowedHeight) { ul.style.position = 'fixed'; ul.style.bottom = currentScreenHeight + 'px'; } else { ul.style.position = 'static'; ul.style.bottom = 'auto'; } } export function handleMessage(data: IIPCSendMessage): void { switch (data.type) { case SendTypes.New: addMessage(data.message as IPrintMessage | IErrorMessage); scrollImpl(); break; case SendTypes.Batch: for (const message of data.message as (IPrintMessage | IErrorMessage)[]) { addMessage(message); } scrollImpl(); break; case SendTypes.PauseUpdate: const pause = document.getElementById('pause'); if (pause !== null) { pause.innerHTML = 'Paused: ' + (data.message as number); } break; case SendTypes.ConnectionChanged: const bMessage: boolean = data.message as boolean; if (bMessage === true) { onConnect(); } else { onDisconnect(); } break; default: break; } checkResize(); } function createSplitUl(left: boolean): HTMLUListElement { const splitDiv = document.createElement('ul'); splitDiv.style.position = 'fixed'; splitDiv.style.bottom = '0px'; if (left) { splitDiv.style.left = '0px'; } else { splitDiv.style.right = '0px'; } splitDiv.style.listStyleType = 'none'; splitDiv.style.padding = '0'; splitDiv.style.width = '49.8%'; splitDiv.style.marginBottom = '1px'; return splitDiv; } function createButton(id: string, text: string, callback: () => void): HTMLLIElement { const li = document.createElement('li'); const button = document.createElement('button'); button.id = id; button.style.width = '100%'; button.appendChild(document.createTextNode(text)); button.addEventListener('click', callback); li.appendChild(button); return li; } function onChangeTeamNumber() { const newNumber = document.getElementById('teamNumber'); console.log('finding team number'); if (newNumber === null) { return; } console.log('sending message'); sendMessage({ message: parseInt((newNumber as HTMLInputElement).value, 10), type: ReceiveTypes.ChangeNumber, }); console.log('sent message'); } function setLivePage() { const mdv = document.getElementById('mainDiv'); if (mdv === undefined) { return; } const mainDiv: HTMLDivElement = mdv as HTMLDivElement; currentScreenHeight = 100; mainDiv.innerHTML = ''; const ul = document.createElement('ul'); ul.id = 'list'; ul.style.listStyleType = 'none'; ul.style.padding = '0'; mainDiv.appendChild(ul); const splitDiv = document.createElement('div'); splitDiv.style.height = '100px'; mainDiv.appendChild(splitDiv); const leftList = createSplitUl(true); leftList.appendChild(createButton('pause', 'Pause', onPause)); leftList.appendChild(createButton('discard', 'Discard', onDiscard)); leftList.appendChild(createButton('clear', 'Clear', onClear)); leftList.appendChild(createButton('showprints', 'Don\'t Show Prints', onShowPrints)); leftList.appendChild(createButton('switchPage', 'Switch to Viewer', () => { setViewerPage(); })); mainDiv.appendChild(leftList); const rightList = createSplitUl(false); rightList.appendChild(createButton('showwarnings', 'Don\'t Show Warnings', onShowWarnings)); rightList.appendChild(createButton('autoreconnect', 'Disconnect', onAutoReconnect)); rightList.appendChild(createButton('timestamps', 'Show Timestamps', onShowTimestamps)); rightList.appendChild(createButton('savelot', 'Save Log', onSaveLog)); const teamNumberUl = document.createElement('li'); const teamNumberI = document.createElement('input'); teamNumberI.id = 'teamNumber'; teamNumberI.type = 'number'; teamNumberI.style.width = '50%'; const teamNumberB = document.createElement('button'); teamNumberB.id = 'changeTeamNumber'; teamNumberB.style.width = '24.9%'; teamNumberB.style.right = '0'; teamNumberB.style.position = 'fixed'; teamNumberB.addEventListener('click', onChangeTeamNumber); teamNumberB.appendChild(document.createTextNode('Set Team Number')); teamNumberUl.appendChild(teamNumberI); teamNumberUl.appendChild(teamNumberB); rightList.appendChild(teamNumberUl); mainDiv.appendChild(rightList); if (autoReconnect !== true) { onAutoReconnect(); } } export function setViewerPage() { const mdv = document.getElementById('mainDiv'); if (mdv === undefined) { return; } if (autoReconnect === true) { onAutoReconnect(); } const mainDiv: HTMLDivElement = mdv as HTMLDivElement; currentScreenHeight = 60; mainDiv.innerHTML = ''; const ul = document.createElement('ul'); ul.id = 'list'; ul.style.listStyleType = 'none'; ul.style.padding = '0'; mainDiv.appendChild(ul); const splitDiv = document.createElement('div'); splitDiv.style.height = '60px'; mainDiv.appendChild(splitDiv); const leftList = createSplitUl(true); const fileInput = document.createElement('input'); fileInput.type = 'file'; fileInput.id = 'openFile'; fileInput.name = 'files[]'; fileInput.style.width = '100%'; fileInput.addEventListener('change', handleFileSelect, false); leftList.appendChild(fileInput); leftList.appendChild(createButton('showprints', 'Don\'t Show Prints', onShowPrints)); leftList.appendChild(createButton('switchPage', 'Switch to Live', () => { setLivePage(); })); mainDiv.appendChild(leftList); const rightList = createSplitUl(false); rightList.appendChild(createButton('showwarnings', 'Don\'t Show Warnings', onShowWarnings)); rightList.appendChild(createButton('timestamps', 'Show Timestamps', onShowTimestamps)); mainDiv.appendChild(rightList); } window.addEventListener('load', (_: Event) => { setLivePage(); });
the_stack
import { DecodedTile } from "@here/harp-datasource-protocol"; import { mercatorProjection, OrientedBox3, TileKey, webMercatorTilingScheme } from "@here/harp-geoutils"; import { silenceLoggingAroundFunction } from "@here/harp-test-utils"; import { TaskQueue } from "@here/harp-utils"; import { assert, expect } from "chai"; import * as sinon from "sinon"; import * as THREE from "three"; import { DataSource } from "../lib/DataSource"; import { TileGeometryLoader } from "../lib/geometry/TileGeometryLoader"; import { ITileLoader, TileLoaderState } from "../lib/ITileLoader"; import { MapView, TileTaskGroups } from "../lib/MapView"; import { TextElement } from "../lib/text/TextElement"; import { Tile } from "../lib/Tile"; class FakeTileLoader implements ITileLoader { state: TileLoaderState = TileLoaderState.Ready; isFinished: boolean = false; priority: number = 0; loadAndDecode(): Promise<TileLoaderState> { return new Promise(() => this.state); } waitSettled(): Promise<TileLoaderState> { return new Promise(() => this.state); } cancel(): void { // do nothing. } } class TileTestStubDataSource extends DataSource { /** @override */ getTile(tileKey: TileKey): Tile { const tile = new Tile(this, tileKey); tile.tileLoader = new FakeTileLoader(); return tile; } /** @override */ getTilingScheme() { return webMercatorTilingScheme; } } function createFakeTextElement(): TextElement { const priority = 0; return new TextElement("fake", new THREE.Vector3(), {}, {}, priority); } describe("Tile", function () { const tileKey = TileKey.fromRowColumnLevel(0, 0, 0); let stubDataSource: any; let mapView: any; let sandbox: any; before(function () { sandbox = sinon.createSandbox(); }); beforeEach(function () { stubDataSource = new TileTestStubDataSource({ name: "test-data-source" }); mapView = { taskQueue: new TaskQueue({ groups: [TileTaskGroups.CREATE, TileTaskGroups.FETCH_AND_DECODE] }), projection: mercatorProjection, frameNumber: 1, visibleTileSet: { disposeTile: () => {} } as any } as MapView; stubDataSource.attach(mapView); }); afterEach(function () { sandbox.restore(); }); it("set empty decoded tile forces hasGeometry to be true", function () { const tile = new Tile(stubDataSource, tileKey); const decodedTile: DecodedTile = { techniques: [], geometries: [] }; tile.decodedTile = decodedTile; assert(tile.hasGeometry); expect(tile.decodedTile).to.be.equal(decodedTile); }); it("set decoded tile with text only forces hasGeometry to be true", function () { const tile = new Tile(stubDataSource, tileKey); const decodedTile: DecodedTile = { techniques: [], geometries: [], textGeometries: [ { positions: { name: "positions", buffer: new Float32Array(), type: "float", itemCount: 1000 }, texts: new Array<number>(1000), stringCatalog: new Array<undefined>(1000) } ] }; tile.decodedTile = decodedTile; assert(tile.hasGeometry); expect(tile.decodedTile).to.be.equal(decodedTile); }); describe("Text elements", function () { it("addTextElement to changed tile does not recreate text group", function () { const tile = new Tile(stubDataSource, tileKey); tile.addTextElement(createFakeTextElement()); const oldGroup = tile.textElementGroups.groups.values().next().value; expect(oldGroup.elements).to.have.lengthOf(1); tile.addTextElement(createFakeTextElement()); const newGroup = tile.textElementGroups.groups.values().next().value; expect(newGroup.elements).to.have.lengthOf(2); expect(newGroup).to.equal(oldGroup); }); it("addTextElement to unchanged tile recreates text group", function () { const tile = new Tile(stubDataSource, tileKey); tile.addTextElement(createFakeTextElement()); tile.textElementsChanged = false; const oldGroup = tile.textElementGroups.groups.values().next().value; expect(oldGroup.elements).to.have.lengthOf(1); tile.addTextElement(createFakeTextElement()); const newGroup = tile.textElementGroups.groups.values().next().value; expect(newGroup.elements).to.have.lengthOf(2); expect(newGroup).to.not.equal(oldGroup); assert.isTrue(tile.textElementsChanged); }); it("removeTextElement from changed tile does not recreate text group", function () { const tile = new Tile(stubDataSource, tileKey); tile.addTextElement(createFakeTextElement()); const textElement = createFakeTextElement(); tile.addTextElement(textElement); const oldGroup = tile.textElementGroups.groups.values().next().value; expect(oldGroup.elements).to.have.lengthOf(2); const result = tile.removeTextElement(textElement); assert.isTrue(result); const newGroup = tile.textElementGroups.groups.values().next().value; expect(newGroup.elements).to.have.lengthOf(1); expect(newGroup).to.equal(oldGroup); }); it("removeTextElement from unchanged tile recreates text group", function () { const tile = new Tile(stubDataSource, tileKey); tile.addTextElement(createFakeTextElement()); const textElement = createFakeTextElement(); tile.addTextElement(textElement); tile.textElementsChanged = false; const oldGroup = tile.textElementGroups.groups.values().next().value; const result = tile.removeTextElement(textElement); assert.isTrue(result); const newGroup = tile.textElementGroups.groups.values().next().value; expect(newGroup.elements).to.have.lengthOf(1); expect(newGroup).to.not.equal(oldGroup); assert.isTrue(tile.textElementsChanged); }); it("clearTextElements from empty tile does nothing", function () { const tile = new Tile(stubDataSource, tileKey); assert.isFalse(tile.textElementsChanged); tile.clearTextElements(); assert.isFalse(tile.textElementsChanged); const textElement = createFakeTextElement(); tile.addTextElement(textElement); tile.removeTextElement(textElement); tile.clearTextElements(); assert.isTrue(tile.textElementsChanged); }); it("clearTextElements from non-empty tile marks it as changed", function () { const tile = new Tile(stubDataSource, tileKey); tile.addTextElement(createFakeTextElement()); expect(tile.textElementGroups.count()).to.equal(1); tile.textElementsChanged = false; tile.clearTextElements(); expect(tile.textElementGroups.count()).to.equal(0); assert.isTrue(tile.textElementsChanged); }); it("dispose diposes of text elements", function () { const tile = new Tile(stubDataSource, tileKey); const textElement = createFakeTextElement(); const disposeStub = sinon.stub(textElement, "dispose"); tile.addTextElement(textElement); expect(tile.textElementGroups.count()).to.equal(1); tile.dispose(); disposeStub.called; expect(tile.textElementGroups.count()).to.equal(0); }); }); it("setting skipping will cause willRender to return false", function () { const tile = new Tile(stubDataSource, tileKey); tile.skipRendering = true; expect(tile.willRender(0)).is.false; tile.skipRendering = false; expect(tile.willRender(0)).is.true; }); describe("Elevation", function () { it("default tile min/max elevation and max geometry height are 0", function () { const tile = new Tile(stubDataSource, tileKey); const oldGeoBox = tile.geoBox.clone(); const oldBBox = tile.boundingBox.clone(); tile.decodedTile = { techniques: [], geometries: [] }; expect(tile.geoBox).deep.equals(oldGeoBox); expect(tile.boundingBox).deep.equals(oldBBox); }); it("elevationRange setter does not elevate bbox if maxGeometryHeight is not set", function () { const tile = new Tile(stubDataSource, tileKey); const oldBBox = tile.boundingBox.clone(); tile.elevationRange = { minElevation: 5, maxElevation: 10 }; expect(tile.geoBox.minAltitude).equals(tile.elevationRange.minElevation); expect(tile.geoBox.maxAltitude).equals(tile.elevationRange.maxElevation); expect(tile.boundingBox).deep.equals(oldBBox); tile.decodedTile = { techniques: [], geometries: [], boundingBox: new OrientedBox3() }; tile.elevationRange = { minElevation: 100, maxElevation: 500 }; expect(tile.boundingBox).deep.equals(tile.decodedTile.boundingBox); }); it("elevationRange setter elevates bbox if maxGeometryHeight is set", function () { const tile = new Tile(stubDataSource, tileKey); const minElevation = 30; const maxElevation = 50; const maxGeometryHeight = 100; const expectedGeoBox = tile.geoBox.clone(); expectedGeoBox.southWest.altitude = minElevation; expectedGeoBox.northEast.altitude = maxElevation + maxGeometryHeight; const expectedBBox = new OrientedBox3(); stubDataSource.mapView.projection.projectBox(expectedGeoBox, expectedBBox); tile.decodedTile = { techniques: [], geometries: [], maxGeometryHeight }; tile.elevationRange = { minElevation, maxElevation }; expect(tile.geoBox).deep.equals(expectedGeoBox); expect(tile.boundingBox).deep.equals(expectedBBox); }); it("elevationRange setter elevates bbox if minGeometryHeight is set", function () { const tile = new Tile(stubDataSource, tileKey); const minElevation = 30; const maxElevation = 50; const minGeometryHeight = -100; const expectedGeoBox = tile.geoBox.clone(); expectedGeoBox.southWest.altitude = minElevation + minGeometryHeight; expectedGeoBox.northEast.altitude = maxElevation; const expectedBBox = new OrientedBox3(); stubDataSource.mapView.projection.projectBox(expectedGeoBox, expectedBBox); tile.decodedTile = { techniques: [], geometries: [], minGeometryHeight }; tile.elevationRange = { minElevation, maxElevation }; expect(tile.geoBox).deep.equals(expectedGeoBox); expect(tile.boundingBox).deep.equals(expectedBBox); }); it("decodedTile setter sets decoded tile bbox if defined but does not elevate it", function () { const key = new TileKey(5, 5, 5); const tile = new Tile(stubDataSource, key); const expectedGeoBox = tile.dataSource.getTilingScheme().getGeoBox(key); expectedGeoBox.southWest.altitude = 500; expectedGeoBox.northEast.altitude = 1000; const expectedBBox = new OrientedBox3( new THREE.Vector3(1, 2, 3), new THREE.Matrix4(), new THREE.Vector3(1, 1, 1) ); tile.elevationRange = { minElevation: 500, maxElevation: 1000 }; tile.decodedTile = { techniques: [], geometries: [], boundingBox: expectedBBox, maxGeometryHeight: 10 }; expect(tile.geoBox).deep.equals(expectedGeoBox); expect(tile.boundingBox).deep.equals(expectedBBox); }); it("decodedTile setter elevates bbox with decoded maxGeometryHeight if defined", function () { const tile = new Tile(stubDataSource, tileKey); const minElevation = 500; const maxElevation = 1000; const maxGeometryHeight = 10; const expectedGeoBox = tile.geoBox.clone(); expectedGeoBox.southWest.altitude = minElevation; expectedGeoBox.northEast.altitude = maxElevation + maxGeometryHeight; const expectedBBox = new OrientedBox3(); stubDataSource.mapView.projection.projectBox(expectedGeoBox, expectedBBox); tile.elevationRange = { minElevation, maxElevation }; tile.decodedTile = { techniques: [], geometries: [], maxGeometryHeight }; expect(tile.geoBox).deep.equals(expectedGeoBox); expect(tile.boundingBox).deep.equals(expectedBBox); }); }); describe("isVisible", function () { it("doesn't throw on isVisible if not attached to a MapView", function () { const tile = new Tile(stubDataSource, tileKey); mapView.frameNumber = 2; tile.frameNumLastRequested = 2; expect(tile.isVisible).not.throw; expect(tile.isVisible).is.true; stubDataSource.detach(mapView as MapView); silenceLoggingAroundFunction("Tile", () => { expect(tile.isVisible).not.throw; expect(tile.isVisible).is.false; }); }); it("cancels geometry loader if tile is made invisible", function () { stubDataSource.useGeometryLoader = true; const tile = stubDataSource.getTile(tileKey); const geometryLoader = (tile as any).m_tileGeometryLoader; const cancelSpy: sinon.SinonSpy = sandbox.spy(geometryLoader, "cancel"); tile.isVisible = false; expect(cancelSpy.called).be.true; }); it("does not cancel geometry loader if tile is made visible", function () { stubDataSource.useGeometryLoader = true; const tile = stubDataSource.getTile(tileKey); const geometryLoader = (tile as any).m_tileGeometryLoader; const cancelSpy: sinon.SinonSpy = sandbox.spy(geometryLoader, "cancel"); tile.isVisible = true; expect(cancelSpy.called).be.false; }); }); describe("updateGeometry", function () { it("returns false immediately if tile does not use geometry loader", function () { stubDataSource.useGeometryLoader = false; const tile = stubDataSource.getTile(tileKey); expect(tile.updateGeometry()).be.false; }); it("does not update geometry loader if tile loader is not done", function () { stubDataSource.useGeometryLoader = true; const tile = stubDataSource.getTile(tileKey); const geometryLoader = (tile as any).m_tileGeometryLoader; (tile.tileLoader as FakeTileLoader).isFinished = false; const updateSpy: sinon.SinonSpy = sandbox.spy(geometryLoader, "update"); expect(tile.updateGeometry()).be.true; expect(updateSpy.called).be.false; }); it("finishes geometry loader if decoded tile is empty", function () { stubDataSource.useGeometryLoader = true; const tile = stubDataSource.getTile(tileKey); const geometryLoader: TileGeometryLoader = (tile as any).m_tileGeometryLoader; (tile.tileLoader as FakeTileLoader).isFinished = true; const updateSpy: sinon.SinonSpy = sandbox.spy(geometryLoader, "update"); expect(tile.updateGeometry()).be.true; expect(updateSpy.called).be.false; expect(geometryLoader.isFinished).be.true; }); it("does not update geometry loader if it's canceled", function () { stubDataSource.useGeometryLoader = true; const tile = stubDataSource.getTile(tileKey); const geometryLoader: TileGeometryLoader = (tile as any).m_tileGeometryLoader; geometryLoader.cancel(); (tile.tileLoader as FakeTileLoader).isFinished = true; tile.decodedTile = { techniques: [], geometries: [] }; const updateSpy: sinon.SinonSpy = sandbox.spy(geometryLoader, "update"); expect(tile.updateGeometry()).be.true; expect(updateSpy.called).be.false; }); it("cancels geometry loader if data source is detached from map view", function () { stubDataSource.useGeometryLoader = true; const tile = stubDataSource.getTile(tileKey); const geometryLoader: TileGeometryLoader = (tile as any).m_tileGeometryLoader; (tile.tileLoader as FakeTileLoader).isFinished = true; tile.decodedTile = { techniques: [], geometries: [] }; stubDataSource.detach(mapView); const updateSpy: sinon.SinonSpy = sandbox.spy(geometryLoader, "update"); const cancelSpy: sinon.SinonSpy = sandbox.spy(geometryLoader, "cancel"); expect(tile.updateGeometry()).be.true; expect(updateSpy.called).be.false; expect(cancelSpy.called).be.true; }); it("does not update geometry loader for disposed tile", function () { stubDataSource.useGeometryLoader = true; const tile = stubDataSource.getTile(tileKey); const geometryLoader = (tile as any).m_tileGeometryLoader; (tile.tileLoader as FakeTileLoader).isFinished = true; tile.dispose(); const updateSpy: sinon.SinonSpy = sandbox.spy(geometryLoader, "update"); expect(tile.updateGeometry()).be.true; expect(updateSpy.called).be.false; }); }); });
the_stack
import React, {MouseEvent} from "react"; import {Button, Row, Col, Card, CardBody} from "helpers/reactstrap"; import Tour from "helpers/tourHelper"; import {Typing} from "react-typing"; import "./style.scss"; import Grid from "./GridDom"; import DamageOverlay from "../helpers/DamageOverlay"; import SensorScans from "./SensorScans"; import { useSensorsSubscription, TargetingRangeDocument, useSensorsSetPingModeMutation, useSensorsSendPingMutation, useSetCalculatedTargetMutation, Simulator, SensorContact, Station, Ping_Modes, Sensors as SensorsI, useSensorsRemoveProcessedDataMutation, SensorsPingSubDocument, } from "generated/graphql"; import {useApolloClient} from "@apollo/client"; import useDimensions from "helpers/hooks/useDimensions"; import {Duration} from "luxon"; import {capitalCase} from "change-case"; import useInterval from "helpers/hooks/useInterval"; import {FaBan} from "react-icons/fa"; const trainingSteps = [ { selector: ".nothing", content: "Sensors allow you to get information about what is going on around your ship.", }, { selector: "#sensorGrid", content: "This is your sensor grid. Your ship is located at the center of the grid, where the lines converge. The top segment is directly in front of your ship, as if you were looking down on your ship from above it. You can see the relative location of objects around your ship on this grid.", }, /*{ selector: ".ping-controls", content: "Some sensor systems allow you to control how often the sensor grid 'pings', or detects objects around the ship. You can control the rate of pings with these controls. Whenever your sensors pings, it sends out a faint signal which can be detected by other ships. Turning down the rate of sensor pings can keep your ship's position masked." },*/ { selector: ".contact-info", content: "When you move your mouse over a contact, the contact's identification will show up in this box.", }, { selector: ".processedData", content: "Text will sometimes appear in this box. Your sensors will passively scan and when it finds useful information it will inform you here. Whenever it does, you want to read it out loud so the Captain can know about what is going on around your ship.", }, { selector: ".scanEntry", content: "If you want to know specific information about a contact around your ship, you can scan it directly. Just type what you want to know, such as the weapons on a ship, the population, size, distance, or anything else you want to know about. Click the scan button to initiate your scan. The results will appear in the box below.", }, ]; export function usePing(sensorsId?: string) { const [pinging, setPinging] = React.useState({}); const [pinged, setPinged] = React.useState(false); const mountedRef = React.useRef(false); const client = useApolloClient(); React.useEffect(() => { function doPing() { setPinged(false); setPinging({}); } if (!sensorsId) return; const subscription = client .subscribe({ query: SensorsPingSubDocument, variables: { sensorsId, }, }) .subscribe({ next() { doPing(); }, error(err) { console.error("err", err); }, }); return () => subscription.unsubscribe(); }, [sensorsId, client]); React.useEffect(() => { if (mountedRef.current) { setPinged(true); const timeout = setTimeout(() => { setPinged(false); }, 1000 * 6.5); return () => clearTimeout(timeout); } mountedRef.current = true; }, [pinging]); return pinged; } function calculateTime(milliseconds: number) { if (milliseconds < 1000) return "Just now"; return ( Object.entries( Duration.fromObject({ months: 0, weeks: 0, days: 0, hours: 0, minutes: 0, seconds: 0, milliseconds, }) .normalize() .toObject(), ) .filter(t => t[1] !== 0) .map(t => `${t[1]} ${capitalCase(t[0])}`)[0] + " ago" ); } const TimeCounter: React.FC<{time: Date}> = ({time}) => { const milliseconds = Date.now() - Number(time); return <>{calculateTime(milliseconds)}</>; }; export const ProcessedData: React.FC<{sensors: SensorsI; core?: boolean}> = ({ sensors, core, }) => { const [key, setKey] = React.useState(0); const [removeProcessedData] = useSensorsRemoveProcessedDataMutation(); useInterval(() => { setKey(Math.random()); }, 1000); return ( <> <Col className="col-sm-12"> <label>Processed Data</label> </Col> <Col className="col-sm-12"> <Card className="processedData"> <CardBody> {sensors.processedData ?.concat() .sort((a, b) => { const dateA = new Date(a.time); const dateB = new Date(b.time); if (dateA > dateB) return -1; if (dateB > dateA) return 1; return 0; }) .map((p, i, arr) => ( <React.Fragment key={p.time}> <pre> {core && ( <FaBan className="text-danger" onClick={() => removeProcessedData({ variables: {id: sensors.id, time: p.time}, }) } /> )} <Typing keyDelay={20} key={p.time}> {p.value} </Typing> <div> <small> <TimeCounter key={key} time={new Date(p.time)} /> </small> </div> </pre> {i < arr.length - 1 && <hr />} </React.Fragment> ))} </CardBody> </Card> </Col> </> ); }; interface HoverContact { name: string; picture: string; } interface SensorsProps { simulator: Simulator; station: Station; widget: boolean; viewscreen: boolean; } const Sensors: React.FC<SensorsProps> = ({ simulator, widget, station, viewscreen, }) => { const [hoverContact, setHoverContact] = React.useState<HoverContact>({ name: "", picture: "", }); const [weaponsRange, setWeaponsRange] = React.useState<number | null>(null); const [measureRef, dimensions] = useDimensions(); const client = useApolloClient(); const [setCalculatedTarget] = useSetCalculatedTargetMutation(); const {loading, data} = useSensorsSubscription({ variables: {simulatorId: simulator.id, domain: "external"}, }); const pinged = usePing(data?.sensorsUpdate?.[0].id); const gridMouseDown = React.useCallback(() => { // setCalculatedTarget setCalculatedTarget({ variables: { simulatorId: simulator.id, coordinates: {x: 0, y: 0, z: 0}, contactId: null, }, }); }, [setCalculatedTarget, simulator.id]); const includeTypes = React.useMemo( () => ["contact", "planet", "border", "ping", "projectile"], [], ); const clickContact = React.useCallback( ( e: MouseEvent, contact: SensorContact, selectContact: (contact: SensorContact | string) => void, ) => { e.preventDefault(); e.stopPropagation(); selectContact(contact); if (!contact.location) return; const {x, y, z} = contact.location; setCalculatedTarget({ variables: { simulatorId: simulator.id, coordinates: { x: Math.abs(x || 0), y: Math.abs(y || 0), z: Math.abs(z || 0), }, contactId: contact.id, }, }); }, [setCalculatedTarget, simulator.id], ); if (loading || !data) return <p>Loading...</p>; const sensors = data.sensorsUpdate?.[0]; if (!sensors) return <p>No sensors system.</p>; const showWeaponsRange = async () => { const {data} = await client.query({ query: TargetingRangeDocument, variables: {id: simulator.id}, }); const target = data?.targeting[0]; if (!target) return; setWeaponsRange(target.range); setTimeout(() => { setWeaponsRange(null); }, 1000); }; const needScans = !widget && !station?.cards?.find(c => c?.component === "SensorScans"); const {pingMode, pings} = sensors; return ( <div className="cardSensors"> <div> <Row> {needScans && ( <Col sm={3}> {!viewscreen && ( <> <DamageOverlay message="External Sensors Offline" system={sensors} /> <SensorScans sensors={sensors} client={client} /> <Button onClick={showWeaponsRange} block> Show Weapons Range </Button> {/*<Row> <Col className="col-sm-12"> <h4>Contact Coordinates</h4> </Col> <Col className="col-sm-12"> <Card> <p>X:</p> <p>Y:</p> <p>Z:</p> </Card> </Col> </Row> */} </> )} </Col> )} <Col sm={{size: 6, offset: !needScans ? 1 : 0}} className="arrayContainer" > <div className="spacer" /> <div id="threeSensors" className="array" ref={measureRef}> {dimensions?.width && ( <Grid dimensions={dimensions} sensor={sensors.id} damaged={sensors.damage?.damaged} hoverContact={setHoverContact} movement={sensors.movement} ping={pinged} pings={pings} simulatorId={simulator.id} segments={sensors.segments} interference={sensors.interference} mouseDown={clickContact} gridMouseDown={gridMouseDown} includeTypes={includeTypes} range={ weaponsRange && { size: weaponsRange, color: "rgba(255, 0, 0, 0.5)", } } /> )} </div> <DamageOverlay message="External Sensors Offline" system={sensors} /> </Col> <Col sm={{size: 3, offset: !needScans ? 1 : 0}} className="data"> {!viewscreen && ( <RightSensorsSidebar needScans={needScans} pingMode={pingMode || undefined} ping={pinged} pings={Boolean(pings)} sensors={sensors} hoverContact={hoverContact} showWeaponsRange={showWeaponsRange} /> )} </Col> </Row> </div> <Tour steps={trainingSteps} /> </div> ); }; const RightSensorsSidebar: React.FC<{ needScans: boolean; pingMode?: Ping_Modes; ping: boolean; pings?: boolean; sensors: SensorsI; hoverContact: HoverContact; showWeaponsRange: () => void; }> = ({ pings, needScans, pingMode, ping, sensors, hoverContact, showWeaponsRange, }) => { const [whichControl, setWhichControl] = React.useState<"info" | "options">( "info", ); return ( <> {pings && ( <div className="sensor-control-buttons"> <Button active={whichControl === "info"} onClick={() => setWhichControl("info")} > Contacts </Button> <Button active={whichControl === "options"} onClick={() => setWhichControl("options")} > Options </Button> </div> )} {whichControl === "options" && pings && pingMode && ( <PingControl sensorsId={sensors.id} pingMode={pingMode} ping={ping} /> )} {(whichControl === "info" || !pings) && ( <Row className="contact-info"> <Col className="col-sm-12"> <label>Contact Information</label> </Col> <Col className="col-sm-12"> <div className="card contactPictureContainer"> {hoverContact.picture && ( <div className="contactPicture" style={{ backgroundSize: "contain", backgroundPosition: "center", backgroundRepeat: "no-repeat", backgroundColor: "black", backgroundImage: `url('/assets${hoverContact.picture}')`, }} /> )} </div> </Col> <Col className="col-sm-12 contactNameContainer"> <div className="card contactName">{hoverContact.name}</div> </Col> </Row> )} <Row> <ProcessedData sensors={sensors} /> </Row> {!needScans && ( <Button onClick={showWeaponsRange} block> Show Weapons Range </Button> )} </> ); }; const PingControl: React.FC<{ pingMode: Ping_Modes; ping: boolean; sensorsId: string; }> = ({sensorsId, pingMode, ping}) => { const [setPingMode] = useSensorsSetPingModeMutation(); const selectPing = (which: Ping_Modes) => { setPingMode({ variables: { id: sensorsId, mode: which, }, }); }; const [sendPing] = useSensorsSendPingMutation(); const triggerPing = () => { sendPing({variables: {id: sensorsId}}); }; return ( <Row className="ping-control"> <Col sm="12"> <label>Sensor Options:</label> </Col> <Col sm={12} className="ping-controls"> <Card> <li onClick={() => selectPing(Ping_Modes.Active)} className={`list-group-item ${ pingMode === Ping_Modes.Active ? "selected" : "" }`} > Active Scan </li> <li onClick={() => selectPing(Ping_Modes.Passive)} className={`list-group-item ${ pingMode === Ping_Modes.Passive ? "selected" : "" }`} > Passive Scan </li> <li onClick={() => selectPing(Ping_Modes.Manual)} className={`list-group-item ${ pingMode === Ping_Modes.Manual ? "selected" : "" }`} > Manual Scan </li> </Card> <Button block disabled={ping} className="pingButton" style={{ opacity: pingMode === "manual" ? 1 : 0, pointerEvents: pingMode === "manual" ? "auto" : "none", }} onClick={triggerPing} > Ping </Button> </Col> </Row> ); }; export default Sensors;
the_stack
import {expect} from 'chai'; import * as fetch from 'isomorphic-fetch'; // tslint:disable:no-string-literal import {config, Record, Store} from '../../src'; import mockApi from '../utils/api'; import {Event, Image, Organiser, Photo, TestStore, User} from '../utils/setup'; const baseStoreFetch = config.storeFetch; describe('updates', () => { beforeEach(() => { config.fetchReference = fetch; config.baseUrl = 'http://example.com/'; }); describe('adding record', () => { it('should add a record', async () => { const store = new Store(); const record = new Record({ title: 'Example title', }, 'event'); store.add(record); mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'POST', name: 'event-1', url: 'event', }); const data = record.toJsonApi(); expect(record['title']).to.equal('Example title'); expect(data.id).to.be.an('undefined'); expect(data.type).to.equal('event'); expect(data.attributes.id).to.be.an('undefined'); expect(data.attributes.type).to.be.an('undefined'); const updated = await record.save(); expect(updated['title']).to.equal('Test 1'); expect(updated).to.equal(record); }); it('should add a record if not in store', async () => { const record = new Record({ title: 'Example title', }, 'event'); mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'POST', name: 'event-1', url: 'event', }); const data = record.toJsonApi(); expect(record['title']).to.equal('Example title'); expect(data.id).to.be.an('undefined'); expect(data.type).to.equal('event'); expect(data.attributes.id).to.be.an('undefined'); expect(data.attributes.type).to.be.an('undefined'); const updated = await record.save(); expect(updated['title']).to.equal('Test 1'); expect(updated).to.equal(record); }); it('should add a referenced record', async () => { class Foo extends Record { public static type = 'event'; } // tslint:disable-next-line:max-classes-per-file class Bar extends Record { public static type = 'bar'; public static refs = { foo: 'event', }; public foo: Foo; public fooId: number|string; } // tslint:disable-next-line:max-classes-per-file class Test extends Store { public static types = [Foo, Bar]; } const store = new Test(); const foo = new Foo({ title: 'Example title', }); store.add(foo); const bar = store.add<Bar>({foo}, 'bar'); const baz = store.add<Record>({}, 'baz'); expect(bar.foo).to.equal(foo); expect(bar.fooId).to.equal(foo.getRecordId()); baz.assignRef('foo', foo); expect(baz['foo']).to.equal(foo); expect(baz['fooId']).to.equal(foo.getRecordId()); mockApi({ data: JSON.stringify({ data: foo.toJsonApi(), }), method: 'POST', name: 'event-1', url: 'event', }); const data = foo.toJsonApi(); expect(foo['title']).to.equal('Example title'); expect(data.id).to.be.an('undefined'); expect(data.type).to.equal('event'); expect(data.attributes.id).to.be.an('undefined'); expect(data.attributes.type).to.be.an('undefined'); const updated = await foo.save(); expect(updated['title']).to.equal('Test 1'); expect(updated).to.equal(foo); expect(foo.getRecordId()).to.equal(12345); expect(bar.foo).to.equal(foo); expect(bar.fooId).to.equal(foo.getRecordId()); expect(baz['foo']).to.equal(foo); expect(baz['fooId']).to.equal(foo.getRecordId()); }); it('should add a record with queue (202)', async () => { const store = new Store(); const record = new Record({ title: 'Example title', }, 'event'); store.add(record); mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'POST', name: 'queue-1', status: 202, url: 'event', }); const data = record.toJsonApi(); expect(record['title']).to.equal('Example title'); expect(data.id).to.be.an('undefined'); expect(data.type).to.equal('event'); expect(data.attributes.id).to.be.an('undefined'); expect(data.attributes.type).to.be.an('undefined'); const queue = await record.save(); expect(queue.getRecordType()).to.equal('queue'); mockApi({ name: 'queue-1', url: 'events/queue-jobs/123', }); const queue2 = await queue.fetchLink('self', null, true); const queueRecord = queue2.data as Record; expect(queueRecord.getRecordType()).to.equal('queue'); mockApi({ name: 'event-1', url: 'events/queue-jobs/123', }); const updatedRes = await queue.fetchLink('self', null, true); const updated = updatedRes.data as Record; expect(updated.getRecordType()).to.equal('event'); expect(updated['title']).to.equal('Test 1'); expect(updated.getRecordId()).to.equal(12345); expect(updated).to.equal(record); }); it('should add a record with queue (202) if not in store', async () => { const record = new Record({ title: 'Example title', }, 'event'); mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'POST', name: 'queue-1', status: 202, url: 'event', }); const data = record.toJsonApi(); expect(record['title']).to.equal('Example title'); expect(data.id).to.be.an('undefined'); expect(data.type).to.equal('event'); expect(data.attributes.id).to.be.an('undefined'); expect(data.attributes.type).to.be.an('undefined'); const queue = await record.save(); expect(queue.getRecordType()).to.equal('queue'); mockApi({ name: 'queue-1', url: 'events/queue-jobs/123', }); const queue2 = await queue.fetchLink('self', null, true); const queueRecord = queue2.data as Record; expect(queueRecord.getRecordType()).to.equal('queue'); mockApi({ name: 'event-1', url: 'events/queue-jobs/123', }); const updatedRes = await queue.fetchLink('self', null, true); const updated = updatedRes.data as Record; expect(updated.getRecordType()).to.equal('event'); expect(updated['title']).to.equal('Test 1'); expect(updated.getRecordId()).to.equal(12345); expect(updated).to.equal(record); }); it('should add a record with response 204', async () => { const store = new Store(); const record = new Record({ title: 'Example title', }, {id: 123, type: 'event'}); store.add(record); mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'POST', responseFn: () => null, status: 204, url: 'event', }); const data = record.toJsonApi(); expect(record['title']).to.equal('Example title'); expect(data.type).to.equal('event'); expect(data.attributes.id).to.be.an('undefined'); expect(data.attributes.type).to.be.an('undefined'); const updated = await record.save(); expect(updated['title']).to.equal('Example title'); expect(updated).to.equal(record); }); it('should add a record with response 204 if not in store', async () => { const record = new Record({ title: 'Example title', }, {id: 123, type: 'event'}); mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'POST', responseFn: () => null, status: 204, url: 'event', }); const data = record.toJsonApi(); expect(record['title']).to.equal('Example title'); expect(data.type).to.equal('event'); expect(data.attributes.id).to.be.an('undefined'); expect(data.attributes.type).to.be.an('undefined'); const updated = await record.save(); expect(updated['title']).to.equal('Example title'); expect(updated).to.equal(record); }); it('should add a record with client-generated id', async () => { const store = new Store(); // tslint:disable-next-line:max-classes-per-file class GenRecord extends Record { public static useAutogeneratedIds = true; public static autoIdFunction = () => '110ec58a-a0f2-4ac4-8393-c866d813b8d1'; } const record = new GenRecord({ title: 'Example title', }, 'event'); store.add(record); mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'POST', name: 'event-1c', url: 'event', }); const data = record.toJsonApi(); expect(record['title']).to.equal('Example title'); expect(data.id).to.be.an('string'); expect(data.id).to.have.length(36); expect(data.type).to.equal('event'); expect(data.attributes.id).to.be.an('undefined'); expect(data.attributes.type).to.be.an('undefined'); const updated = await record.save(); expect(updated['title']).to.equal('Test 1'); expect(updated).to.equal(record); }); it('should add a record with client-generated id if not in store', async () => { // tslint:disable-next-line:max-classes-per-file class GenRecord extends Record { public static useAutogeneratedIds = true; public static autoIdFunction = () => '110ec58a-a0f2-4ac4-8393-c866d813b8d1'; } const record = new GenRecord({ title: 'Example title', }, 'event'); mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'POST', name: 'event-1c', url: 'event', }); const data = record.toJsonApi(); expect(record['title']).to.equal('Example title'); expect(data.id).to.be.an('string'); expect(data.id).to.have.length(36); expect(data.type).to.equal('event'); expect(data.attributes.id).to.be.an('undefined'); expect(data.attributes.type).to.be.an('undefined'); const updated = await record.save(); expect(updated['title']).to.equal('Test 1'); expect(updated).to.equal(record); }); }); describe('updating record', () => { it('should update a record', async () => { mockApi({ name: 'event-1', url: 'event/12345', }); const store = new Store(); const events = await store.fetch('event', 12345); const record = events.data as Record; mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'PATCH', name: 'event-1', url: 'event/12345', }); const updated = await record.save(); expect(updated['title']).to.equal('Test 1'); expect(updated).to.equal(record); }); it('should update a record if not in store', async () => { mockApi({ name: 'event-1', url: 'event/12345', }); const store = new Store(); const events = await store.fetch('event', 12345); const record = events.data as Record; store.remove(record.getRecordType(), record.getRecordId()); mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'PATCH', name: 'event-1', url: 'event/12345', }); const updated = await record.save(); expect(updated['title']).to.equal('Test 1'); expect(updated).to.equal(record); }); it('should update a record with self link', async () => { mockApi({ name: 'event-1b', url: 'event/12345', }); const store = new Store(); const events = await store.fetch('event', 12345); const record = events.data as Record; mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'PATCH', name: 'event-1b', url: 'event/1234', }); const updated = await record.save(); expect(updated['title']).to.equal('Test 1'); expect(updated).to.equal(record); }); it('should update a record with self link if not in store', async () => { mockApi({ name: 'event-1b', url: 'event/12345', }); const store = new Store(); const events = await store.fetch('event', 12345); const record = events.data as Record; store.remove(record.getRecordType(), record.getRecordId()); mockApi({ data: JSON.stringify({ data: record.toJsonApi(), }), method: 'PATCH', name: 'event-1b', url: 'event/1234', }); const updated = await record.save(); expect(updated['title']).to.equal('Test 1'); expect(updated).to.equal(record); }); it('should support updating relationships', async () => { mockApi({ name: 'events-1', url: 'event', }); const store = new Store(); const events = await store.fetchAll('event'); const event = events.data[0] as Record; event['imageId'] = [event['imageId'], '2']; mockApi({ data: { data: [{ id: '1', type: 'image', }, { id: '2', type: 'image', }], }, method: 'PATCH', name: 'event-1d', url: 'images/1', }); const event2 = await event.saveRelationship('image') as Record; expect(event2.getRecordId()).to.equal(12345); expect(event2.getRecordType()).to.equal('event'); expect(event2['imageId'][0]).to.equal('1'); expect(event['imageId'][0]).to.equal('1'); expect(event).to.equal(event2); }); it('should support updating relationships if not in store', async () => { mockApi({ name: 'events-1', url: 'event', }); const store = new Store(); const events = await store.fetchAll('event'); const event = events.data[0] as Record; store.remove(event.getRecordType(), event.getRecordId()); event['imageId'] = [event['imageId'], '2']; mockApi({ data: { data: [{ id: '1', type: 'image', }, { id: '2', type: 'image', }], }, method: 'PATCH', name: 'event-1d', url: 'images/1', }); const event2 = await event.saveRelationship('image') as Record; expect(event2.getRecordId()).to.equal(12345); expect(event2.getRecordType()).to.equal('event'); expect(event2['imageId'][0]).to.equal('1'); expect(event['imageId'][0]).to.equal('1'); expect(event).to.equal(event2); }); }); describe('removing record', () => { it('should remove a record', async () => { mockApi({ name: 'event-1', url: 'event/12345', }); const store = new Store(); const events = await store.fetch('event', 12345); const record = events.data as Record; mockApi({ method: 'DELETE', name: 'event-1', url: 'event/12345', }); expect(store.findAll('event').length).to.equal(1); const updated = await record.remove(); expect(updated).to.equal(true); expect(store.findAll('event').length).to.equal(0); }); it('should remove a record if not in store', async () => { mockApi({ name: 'event-1', url: 'event/12345', }); const store = new Store(); const events = await store.fetch('event', 12345); const record = events.data as Record; expect(store.findAll('event').length).to.equal(1); store.remove(record.getRecordType(), record.getRecordId()); expect(store.findAll('event').length).to.equal(0); mockApi({ method: 'DELETE', name: 'event-1', url: 'event/12345', }); const updated = await record.remove(); expect(updated).to.equal(true); expect(store.findAll('event').length).to.equal(0); }); it('should remove a local record without api calls', async () => { const store = new Store(); const record = new Record({ title: 'Example title', }, 'event'); store.add(record); expect(record['title']).to.equal('Example title'); expect(store.findAll('event').length).to.equal(1); const updated = await record.remove(); expect(updated).to.equal(true); expect(store.findAll('event').length).to.equal(0); }); it('should remove a record from the store', async () => { mockApi({ name: 'event-1', url: 'event/12345', }); const store = new Store(); const events = await store.fetch('event', 12345); const record = events.data as Record; mockApi({ method: 'DELETE', name: 'event-1', url: 'event/12345', }); expect(store.findAll('event').length).to.equal(1); const updated = await store.destroy(record.getRecordType() as string, record.getRecordId()); expect(updated).to.equal(true); expect(store.findAll('event').length).to.equal(0); }); it('should remove a local record from store without api calls', async () => { const store = new Store(); const record = new Record({ title: 'Example title', }, 'event'); store.add(record); expect(record['title']).to.equal('Example title'); expect(store.findAll('event').length).to.equal(1); const updated = await store.destroy(record.getRecordType() as string, record.getRecordId()); expect(updated).to.equal(true); expect(store.findAll('event').length).to.equal(0); }); it('should silently remove an unexisting record', async () => { const store = new Store(); expect(store.findAll('event').length).to.equal(0); const updated = await store.destroy('event', 1); expect(updated).to.equal(true); expect(store.findAll('event').length).to.equal(0); }); }); });
the_stack
import { defer, delay, difference, each, endsWith, filter, find, intersection, pull, some, take } from 'lodash'; import { findCandidates, Candidate, DriverState, Runtime } from 'omnisharp-client'; import * as path from 'path'; import { AsyncSubject, BehaviorSubject, Observable, Scheduler, Subject } from 'rxjs'; import { CompositeDisposable, Disposable, IDisposable, RefCountDisposable } from 'ts-disposables'; import { GenericSelectListView } from '../views/generic-list-view'; import { AtomProjectTracker } from './atom-projects'; import { SolutionAggregateObserver, SolutionObserver } from './composite-solution'; import { isOmnisharpTextEditor, IOmnisharpTextEditor, OmnisharpEditorContext } from './omnisharp-text-editor'; import { Solution } from './solution'; type REPOSITORY = { getWorkingDirectory(): string; }; const SOLUTION_LOAD_TIME = 30000; let openSelectList: GenericSelectListView; class SolutionInstanceManager { /* tslint:disable:variable-name */ public _unitTestMode_ = false; public _kick_in_the_pants_ = false; private get logger() { if (this._unitTestMode_ || this._kick_in_the_pants_) { return { log: () => {/* */ }, error: () => {/* */ } }; } return console; } /* tslint:enable:variable-name */ private _disposable: CompositeDisposable; private _solutionDisposable: CompositeDisposable; private _atomProjects: AtomProjectTracker; private _configurations = new Set<(solution: Solution) => void>(); private _solutions = new Map<string, Solution>(); private _solutionProjects = new Map<string, Solution>(); private _temporarySolutions = new WeakMap<Solution, RefCountDisposable>(); private _disposableSolutionMap = new WeakMap<Solution, IDisposable>(); private _findSolutionCache = new Map<string, Observable<Solution>>(); private _candidateFinderCache = new Set<string>(); private _activated = false; private _nextIndex = 0; private _activeSearch: Promise<any>; // These extensions only support server per folder, unlike normal cs files. private _specialCaseExtensions = ['.csx', /*".cake"*/]; public get __specialCaseExtensions() { return this._specialCaseExtensions; } private _activeSolutions: Solution[] = []; public get activeSolutions() { return this._activeSolutions; } // this solution can be used to observe behavior across all solution. private _observation = new SolutionObserver(); public get solutionObserver() { return this._observation; } // this solution can be used to aggregate behavior across all solutions private _combination = new SolutionAggregateObserver(); public get solutionAggregateObserver() { return this._combination; } private _activeSolution = new BehaviorSubject<Solution>(null); private _activeSolutionObserable = this._activeSolution.distinctUntilChanged().filter(z => !!z).publishReplay(1).refCount(); public get activeSolution() { return this._activeSolutionObserable; } private _activatedSubject = new Subject<boolean>(); private get activatedSubject() { return this._activatedSubject; } public activate(activeEditor: Observable<IOmnisharpTextEditor>) { if (this._activated) return; this._disposable = new CompositeDisposable(); this._solutionDisposable = new CompositeDisposable(); this._atomProjects = new AtomProjectTracker(); this._disposable.add(this._atomProjects); this._activeSearch = Promise.resolve(undefined); // monitor atom project paths this._subscribeToAtomProjectTracker(); // We use the active editor on omnisharpAtom to // create another observable that chnages when we get a new solution. this._disposable.add(activeEditor .filter(z => !!z) .flatMap(z => this.getSolutionForEditor(z)) .subscribe(x => this._activeSolution.next(x))); this._atomProjects.activate(); this._activated = true; this.activatedSubject.next(true); this._disposable.add(this._solutionDisposable); } public connect() { this._solutions.forEach(solution => solution.connect()); } public disconnect() { this._solutions.forEach(solution => solution.dispose()); } public deactivate() { this._activated = false; this._disposable.dispose(); this.disconnect(); this._solutions.clear(); this._solutionProjects.clear(); this._findSolutionCache.clear(); } public get connected() { const iterator = this._solutions.values(); const result = iterator.next(); while (!result.done) if (result.value.currentState === DriverState.Connected) return true; return false; } private _subscribeToAtomProjectTracker() { this._disposable.add(this._atomProjects.removed .filter(z => this._solutions.has(z)) .subscribe(project => this._removeSolution(project))); this._disposable.add(this._atomProjects.added .filter(project => !this._solutionProjects.has(project)) .map(project => { return this._candidateFinder(project) .flatMap(candidates => { return Observable.from(candidates) .flatMap(x => this._findRepositoryForPath(x.path), (candidate, repo) => ({ candidate, repo })) .toArray() .toPromise() .then(repos => { const newCandidates = difference(candidates.map(z => z.path), fromIterator(this._solutions.keys())).map(z => find(candidates, { path: z })) .map(({ path, isProject, originalFile }) => { const found = find(repos, x => x.candidate.path === path); const repo = found && found.repo; return { path, isProject, repo, originalFile }; }); return addCandidatesInOrder(newCandidates, (candidate, repo, isProject, originalFile) => this._addSolution(candidate, repo, isProject, { originalFile, project })); }); }).toPromise(); }) .subscribe(candidateObservable => { this._activeSearch = this._activeSearch.then(() => candidateObservable); })); } private _findRepositoryForPath(workingPath: string) { return Observable.from<REPOSITORY>(atom.project.getRepositories() || []) .filter(x => !!x) .map(repo => ({ repo, directory: repo.getWorkingDirectory() })) .filter(({directory}) => path.normalize(directory) === path.normalize(workingPath)) .take(1) .map(x => x.repo); } private _addSolution(candidate: string, repo: REPOSITORY, isProject: boolean, {temporary = false, project, originalFile}: { delay?: number; temporary?: boolean; project?: string; originalFile?: string; }) { const projectPath = candidate; if (endsWith(candidate, '.sln')) { candidate = path.dirname(candidate); } let solution: Solution; if (this._solutions.has(candidate)) { solution = this._solutions.get(candidate); } else if (project && this._solutionProjects.has(project)) { solution = this._solutionProjects.get(project); } if (solution && !solution.isDisposed) { return Observable.of(solution); } else if (solution && solution.isDisposed) { const disposer = this._disposableSolutionMap.get(solution); disposer.dispose(); } solution = new Solution({ projectPath, index: ++this._nextIndex, temporary, repository: <any>repo, runtime: endsWith(originalFile, '.csx') ? Runtime.ClrOrMono : Runtime.ClrOrMono }); if (!isProject) { solution.isFolderPerFile = true; } const cd = new CompositeDisposable(); this._solutionDisposable.add(solution); solution.disposable.add(cd); this._disposableSolutionMap.set(solution, cd); solution.disposable.add(Disposable.create(() => { solution.connect = () => this._addSolution(candidate, repo, isProject, { temporary, project }); })); cd.add(Disposable.create(() => { this._solutionDisposable.remove(cd); pull(this._activeSolutions, solution); this._solutions.delete(candidate); if (this._temporarySolutions.has(solution)) { this._temporarySolutions.delete(solution); } if (this._activeSolution.getValue() === solution) { this._activeSolution.next(this._activeSolutions.length ? this._activeSolutions[0] : null); } })); this._configurations.forEach(config => config(solution)); this._solutions.set(candidate, solution); // keep track of the active solutions cd.add(this._observation.add(solution)); cd.add(this._combination.add(solution)); if (temporary) { const tempD = Disposable.create(() => { /* */ }); tempD.dispose(); this._temporarySolutions.set(solution, new RefCountDisposable(tempD)); } this._activeSolutions.push(solution); if (this._activeSolutions.length === 1) this._activeSolution.next(solution); const result = this._addSolutionSubscriptions(solution, cd); solution.connect(); return <Observable<Solution>><any>result; } private _addSolutionSubscriptions(solution: Solution, cd: CompositeDisposable) { const result = new AsyncSubject<Solution>(); const errorResult = solution.state .filter(z => z === DriverState.Error) .delay(100) .take(1); cd.add(errorResult.subscribe(() => result.complete())); // If this solution errors move on to the next cd.add(solution.model.observe.projectAdded.subscribe(project => this._solutionProjects.set(project.path, solution))); cd.add(solution.model.observe.projectRemoved.subscribe(project => this._solutionProjects.delete(project.path))); // Wait for the projects to return from the solution cd.add(solution.model.observe.projects .debounceTime(100) .take(1) .map(() => solution) .timeout(SOLUTION_LOAD_TIME, Scheduler.queue) // Wait 30 seconds for the project to load. .onErrorResumeNext() .subscribe(() => { // We loaded successfully return the solution result.next(solution); result.complete(); }, () => { // Move along. result.complete(); })); return result; } private _removeSolution(candidate: string) { if (endsWith(candidate, '.sln')) { candidate = path.dirname(candidate); } const solution = this._solutions.get(candidate); const refCountDisposable = solution && this._temporarySolutions.has(solution) && this._temporarySolutions.get(solution); if (refCountDisposable) { refCountDisposable.dispose(); if (!refCountDisposable.isDisposed) { return; } } // keep track of the removed solutions if (solution) { solution.dispose(); const disposable = this._disposableSolutionMap.get(solution); if (disposable) disposable.dispose(); } } public getSolutionForPath(path: string) { if (!path) // No text editor found return Observable.empty<Solution>(); const isFolderPerFile = some(this.__specialCaseExtensions, ext => endsWith(path, ext)); const location = path; if (!location) { // Text editor not saved yet? return Observable.empty<Solution>(); } const solutionValue = this._getSolutionForUnderlyingPath(location, isFolderPerFile); if (solutionValue) return Observable.of(solutionValue); return this._findSolutionForUnderlyingPath(location, isFolderPerFile); } public getSolutionForEditor(editor: Atom.TextEditor) { return this._getSolutionForEditor(editor).filter(() => !editor.isDestroyed()); } private _setupEditorWithContext(editor: Atom.TextEditor, solution: Solution) { const context = new OmnisharpEditorContext(editor, solution); const result: IOmnisharpTextEditor = <any>editor; this._disposable.add(context); if (solution && !context.temp && this._temporarySolutions.has(solution)) { const refCountDisposable = this._temporarySolutions.get(solution); const disposable = refCountDisposable.getDisposable(); context.temp = true; context.solution.disposable.add(editor.onDidDestroy(() => { disposable.dispose(); this._removeSolution(solution.path); })); } return result; } private _getSolutionForEditor(editor: Atom.TextEditor) { if (!editor) { // No text editor found return Observable.empty<Solution>(); } const location = editor.getPath(); if (!location) { // Text editor not saved yet? return Observable.empty<Solution>(); } if (isOmnisharpTextEditor(editor)) { if (editor.omnisharp.metadata) { // client / server doesn"t work currently for metadata documents. return Observable.empty<Solution>(); } const solution = editor.omnisharp.solution; // If the solution has disconnected, reconnect it if (solution.currentState === DriverState.Disconnected && atom.config.get('omnisharp-atom.autoStartOnCompatibleFile')) solution.connect(); // Client is in an invalid state if (solution.currentState === DriverState.Error) { return Observable.empty<Solution>(); } return Observable.of(solution); } const isFolderPerFile = some(this.__specialCaseExtensions, ext => endsWith(editor.getPath(), ext)); const solution = this._getSolutionForUnderlyingPath(location, isFolderPerFile); if (solution) { this._setupEditorWithContext(editor, solution); return Observable.of(solution); } return this._findSolutionForUnderlyingPath(location, isFolderPerFile) .do(sln => this._setupEditorWithContext(editor, sln)); } private _isPartOfAnyActiveSolution<T>(location: string, cb: (intersect: string, solution: Solution) => T) { for (const solution of this._activeSolutions) { // We don"t check for folder based solutions if (solution.isFolderPerFile) continue; const paths = solution.model.projects.map(z => z.path); const intersect = this._intersectPathMethod(location, paths); if (intersect) { return cb(intersect, solution); } } } private _getSolutionForUnderlyingPath(location: string, isFolderPerFile: boolean): Solution { if (location === undefined) { return null; } if (isFolderPerFile) { // CSX are special, and need a solution per directory. const directory = path.dirname(location); if (this._solutions.has(directory)) return this._solutions.get(directory); return null; } else { const intersect = this._intersectPath(location); if (intersect) { return this._solutions.get(intersect); } } if (!isFolderPerFile) { // Attempt to see if this file is part a solution return this._isPartOfAnyActiveSolution(location, (intersect, solution) => solution); } return null; } private _findSolutionForUnderlyingPath(location: string, isFolderPerFile: boolean): Observable<Solution> { const directory = path.dirname(location); if (!this._activated) { return this.activatedSubject.take(1) .flatMap(() => this._findSolutionForUnderlyingPath(location, isFolderPerFile)); } const segments = location.split(path.sep); const mappedLocations = segments.map((loc, index) => { return take(segments, index + 1).join(path.sep); }); for (const l of mappedLocations) { if (this._findSolutionCache.has(l)) { return this._findSolutionCache.get(l); } } const subject = new AsyncSubject<Solution>(); each(mappedLocations, l => { this._findSolutionCache.set(l, <Observable<Solution>><any>subject); subject.subscribe({ complete: () => this._findSolutionCache.delete(l) }); }); const project = this._intersectAtomProjectPath(directory); const cb = (candidates: Candidate[]) => { // We only want to search for solutions after the main solutions have been processed. // We can get into this race condition if the user has windows that were opened previously. if (!this._activated) { delay(cb, SOLUTION_LOAD_TIME); return; } if (!isFolderPerFile) { // Attempt to see if this file is part a solution const r = this._isPartOfAnyActiveSolution(location, (intersect, solution) => { subject.next(solution); subject.complete(); return true; }); if (r) return; } this._activeSearch.then(() => Observable.from(candidates) .flatMap(x => this._findRepositoryForPath(x.path), (candidate, repo) => ({ candidate, repo })) .toArray() .toPromise() .then(repos => { const newCandidates = difference(candidates.map(z => z.path), fromIterator(this._solutions.keys())).map(z => find(candidates, { path: z })) .map(({ path, isProject, originalFile }) => { const found = find(repos, x => x.candidate.path === path); const repo = found && found.repo; return { path, isProject, repo, originalFile }; }); addCandidatesInOrder(newCandidates, (candidate, repo, isProject, originalFile) => this._addSolution(candidate, repo, isProject, { temporary: !project, originalFile })) .then(() => { if (!isFolderPerFile) { // Attempt to see if this file is part a solution const r = this._isPartOfAnyActiveSolution(location, (intersect, solution) => { subject.next(solution); subject.complete(); return; }); if (r) { return; } } const intersect = this._intersectPath(location) || this._intersectAtomProjectPath(location); if (intersect) { if (this._solutions.has(intersect)) { subject.next(this._solutions.get(intersect)); // The boolean means this solution is temporary. } } else { atom.notifications.addInfo(`Could not find a solution for "${location}"`); } subject.complete(); }); })); }; this._candidateFinder(directory).subscribe(cb); return <Observable<Solution>><any>subject; } private _candidateFinder(directory: string) { return findCandidates.withCandidates(directory, this.logger, { independentSourceFilesToSearch: this.__specialCaseExtensions.map(z => '*' + z) }) .flatMap(candidates => { const slns = filter(candidates, x => endsWith(x.path, '.sln')); if (slns.length > 1) { const items = difference(candidates, slns); const asyncResult = new AsyncSubject<typeof candidates>(); asyncResult.next(items); // handle multiple solutions. const listView = new GenericSelectListView('', slns.map(x => ({ displayName: x.path, name: x.path })), (result: any) => { items.unshift(...slns.filter(x => x.path === result)); each(candidates, x => { this._candidateFinderCache.add(x.path); }); asyncResult.complete(); }, () => { asyncResult.complete(); } ); listView.message.text('Please select a solution to load.'); // Show the view if (openSelectList) { openSelectList.onClosed.subscribe(() => { if (!some(slns, x => this._candidateFinderCache.has(x.path))) { defer(() => listView.toggle()); } else { asyncResult.complete(); } }); } else { defer(() => listView.toggle()); } asyncResult.do({ complete: () => { openSelectList = null; } }); openSelectList = listView; return <Observable<typeof candidates>><any>asyncResult; } else { return Observable.of(candidates); } }); } public registerConfiguration(callback: (solution: Solution) => void) { this._configurations.add(callback); this._solutions.forEach(solution => callback(solution)); } private _intersectPathMethod(location: string, paths?: string[]) { const validSolutionPaths = paths; const segments = location.split(path.sep); const mappedLocations = segments.map((loc, index) => { return take(segments, index + 1).join(path.sep); }); // Look for the closest match first. mappedLocations.reverse(); const intersect: string = intersection(mappedLocations, validSolutionPaths)[0]; if (intersect) { return intersect; } } private _intersectPath(location: string) { return this._intersectPathMethod(location, fromIterator(this._solutions.entries()) .filter(z => !z[1].isFolderPerFile).map(z => z[0])); } private _intersectAtomProjectPath(location: string) { return this._intersectPathMethod(location, this._atomProjects.paths); } } function addCandidatesInOrder(candidates: { path: string; repo: REPOSITORY; isProject: boolean; originalFile: string; }[], cb: (candidate: string, repo: REPOSITORY, isProject: boolean, originalFile: string) => Observable<Solution>) { const asyncSubject = new AsyncSubject(); if (!candidates.length) { asyncSubject.next(candidates); asyncSubject.complete(); return asyncSubject.toPromise(); } const cds = candidates.slice(); const candidate = cds.shift(); const handleCandidate = (cand: { path: string; repo: REPOSITORY; isProject: boolean; originalFile: string; }) => { cb(cand.path, cand.repo, cand.isProject, cand.originalFile) .subscribe({ complete: () => { if (cds.length) { cand = cds.shift(); handleCandidate(cand); } else { asyncSubject.next(candidates); asyncSubject.complete(); } } }); }; handleCandidate(candidate); return asyncSubject.toPromise(); } function fromIterator<T>(iterator: IterableIterator<T>) { const items: T[] = []; let result = iterator.next(); while (!result.done) { items.push(result.value); result = iterator.next(); } return items; } /* tslint:disable:variable-name */ export const SolutionManager = new SolutionInstanceManager(); /* tslint:enable:variable-name */
the_stack
import { IonButton, IonCard, IonCardContent, IonCol, IonGrid, IonInput, IonItem, IonLabel, IonList, IonProgressBar, IonRow, IonSegment, IonSegmentButton, IonSelect, IonSelectOption, } from '@ionic/react'; import { V1PodList } from '@kubernetes/client-node'; import React, { useContext, useState } from 'react'; import { IContext } from '../../../declarations'; import { kubernetesRequest, pluginRequest } from '../../../utils/api'; import { IS_INCLUSTER } from '../../../utils/constants'; import { AppContext } from '../../../utils/context'; import ChartTraces from './ChartTraces'; import { ITrace } from './Trace'; import TraceModal from './TraceModal'; interface IResponse { data: ITrace[]; } export interface IRequest { end: string; limit: string; lookback: string; maxDuration: string; minDuration: string; operation: string; service: string; start: string; tags: string; } interface ITracesProps { request: IRequest; services: string[]; operations: string[]; // eslint-disable-next-line @typescript-eslint/no-explicit-any handleRequest: (event: any) => void; // eslint-disable-next-line @typescript-eslint/no-explicit-any handleRequestService: (event: any) => void; } const Traces: React.FunctionComponent<ITracesProps> = ({ request, services, operations, handleRequest, handleRequestService, }: ITracesProps) => { const context = useContext<IContext>(AppContext); const [activeSegment, setActiveSegment] = useState<string>('service'); // eslint-disable-next-line @typescript-eslint/no-explicit-any const [traces, setTraces] = useState<ITrace[]>([]); const [error, setError] = useState<string>(''); const [isFetching, setIsFetching] = useState<boolean>(false); const runQuery = async () => { try { setError(''); setIsFetching(true); let portforwardingPath = ''; if (!IS_INCLUSTER) { const podList: V1PodList = await kubernetesRequest( 'GET', `/api/v1/namespaces/${context.settings.jaegerNamespace}/pods?labelSelector=${context.settings.jaegerSelector}`, '', context.settings, await context.kubernetesAuthWrapper(''), ); if (podList.items.length > 0 && podList.items[0].metadata) { portforwardingPath = `/api/v1/namespaces/${podList.items[0].metadata.namespace}/pods/${podList.items[0].metadata.name}/portforward`; } else { throw new Error( `Could not find Pod in Namespace "${context.settings.jaegerNamespace}" with selector "${context.settings.jaegerSelector}".`, ); } } let st = ''; let et = ''; if (request.lookback === 'custom') { st = `${Date.parse(request.start)}000`; et = `${Date.parse(request.end)}000`; } const result: IResponse = await pluginRequest( 'jaeger', context.settings.jaegerPort, context.settings.jaegerAddress, { type: 'traces', end: et, limit: request.limit, lookback: request.lookback, maxDuration: request.maxDuration, minDuration: request.minDuration, operation: request.operation, service: request.service, start: st, tags: request.tags, username: context.settings.jaegerUsername, password: context.settings.jaegerPassword, queryBasePath: context.settings.jaegerQueryBasePath, }, portforwardingPath, context.settings, await context.kubernetesAuthWrapper(''), ); setTraces(result.data); setIsFetching(false); } catch (err) { setIsFetching(false); setTraces([]); setError(err.message); } }; return ( <React.Fragment> {isFetching ? <IonProgressBar slot="fixed" type="indeterminate" color="primary" /> : null} <IonGrid> <IonRow> <IonCol> <IonCard> <IonCardContent> <IonSegment value={activeSegment} onIonChange={(e) => setActiveSegment(e.detail.value as string)}> <IonSegmentButton value="service"> <IonLabel>Service</IonLabel> </IonSegmentButton> <IonSegmentButton value="options"> <IonLabel>Options</IonLabel> </IonSegmentButton> </IonSegment> {activeSegment === 'service' ? ( <IonGrid> <IonRow> <IonCol sizeXs="12" sizeSm="12" sizeMd="12" sizeLg="10" sizeXl="10"> {services.length > 0 ? ( <IonItem> <IonLabel>Service</IonLabel> <IonSelect name="service" value={request.service} onIonChange={handleRequestService} interface="popover" > {services.map((service, index) => ( <IonSelectOption key={index} value={service}> {service} </IonSelectOption> ))} </IonSelect> </IonItem> ) : ( <IonItem> <IonInput type="text" required={true} placeholder="Service" name="service" value={request.service} onIonChange={handleRequest} /> </IonItem> )} </IonCol> <IonCol sizeXs="12" sizeSm="12" sizeMd="12" sizeLg="2" sizeXl="2"> <IonButton expand="block" onClick={() => runQuery()}> Search </IonButton> </IonCol> </IonRow> </IonGrid> ) : null} {activeSegment === 'options' ? ( <IonGrid> <IonRow> <IonCol sizeXs="12" sizeSm="12" sizeMd="12" sizeLg="6" sizeXl="6"> <IonItem> <IonLabel position="stacked">Operation</IonLabel> <IonSelect name="operation" value={request.operation} onIonChange={handleRequest} interface="popover" > <IonSelectOption value="">all</IonSelectOption> {operations.map((operation, index) => ( <IonSelectOption key={index} value={operation}> {operation} </IonSelectOption> ))} </IonSelect> </IonItem> </IonCol> <IonCol sizeXs="12" sizeSm="12" sizeMd="12" sizeLg="6" sizeXl="6"> <IonItem> <IonLabel position="stacked">Tags</IonLabel> <IonInput type="text" required={true} placeholder="http.status_code=200 error=true" name="tags" value={request.tags} onIonChange={handleRequest} /> </IonItem> </IonCol> </IonRow> <IonRow> <IonCol sizeXs="12" sizeSm="12" sizeMd="4" sizeLg="4" sizeXl="4"> <IonItem> <IonLabel position="stacked">Lookback</IonLabel> <IonSelect name="lookback" value={request.lookback} onIonChange={handleRequest} interface="popover" > <IonSelectOption value="1h">Last Hour</IonSelectOption> <IonSelectOption value="2h">Last 2 Hours</IonSelectOption> <IonSelectOption value="3h">Last 3 Hours</IonSelectOption> <IonSelectOption value="6h">Last 6 Hours</IonSelectOption> <IonSelectOption value="12h">Last 12 Hours</IonSelectOption> <IonSelectOption value="24h">Last 24 Hours</IonSelectOption> <IonSelectOption value="48h">Last 2 Days</IonSelectOption> <IonSelectOption value="custom">Custom</IonSelectOption> </IonSelect> </IonItem> </IonCol> {request.lookback === 'custom' ? ( <IonCol sizeXs="12" sizeSm="12" sizeMd="4" sizeLg="4" sizeXl="4"> <IonItem> <IonLabel position="stacked">Start Time</IonLabel> <IonInput type="text" required={true} placeholder="2020-12-24T15:00:00Z" name="start" value={request.start} onIonChange={handleRequest} /> </IonItem> </IonCol> ) : null} {request.lookback === 'custom' ? ( <IonCol sizeXs="12" sizeSm="12" sizeMd="4" sizeLg="4" sizeXl="4"> <IonItem> <IonLabel position="stacked">End Time</IonLabel> <IonInput type="text" required={true} placeholder="2020-12-24T16:00:00Z" name="end" value={request.end} onIonChange={handleRequest} /> </IonItem> </IonCol> ) : null} </IonRow> <IonRow> <IonCol sizeXs="12" sizeSm="12" sizeMd="4" sizeLg="4" sizeXl="4"> <IonItem> <IonLabel position="stacked">Min Duration</IonLabel> <IonInput type="text" required={true} placeholder="100ms" name="minDuration" value={request.minDuration} onIonChange={handleRequest} /> </IonItem> </IonCol> <IonCol sizeXs="12" sizeSm="12" sizeMd="4" sizeLg="4" sizeXl="4"> <IonItem> <IonLabel position="stacked">Max Duration</IonLabel> <IonInput type="text" required={true} placeholder="100ms" name="maxDuration" value={request.maxDuration} onIonChange={handleRequest} /> </IonItem> </IonCol> <IonCol sizeXs="12" sizeSm="12" sizeMd="4" sizeLg="4" sizeXl="4"> <IonItem> <IonLabel position="stacked">Limit</IonLabel> <IonInput type="text" required={true} name="limit" value={request.limit} onIonChange={handleRequest} /> </IonItem> </IonCol> </IonRow> </IonGrid> ) : null} </IonCardContent> </IonCard> </IonCol> </IonRow> {traces.length > 0 ? ( <IonRow> <IonCol> <IonCard> <IonCardContent> <ChartTraces traces={traces} /> </IonCardContent> </IonCard> </IonCol> </IonRow> ) : null} {error || traces.length > 0 ? ( <IonRow> <IonCol> <IonCard> <IonCardContent> {error ? ( error ) : ( <IonList> {traces.map((trace, index) => ( <TraceModal key={index} trace={trace} /> ))} </IonList> )} </IonCardContent> </IonCard> </IonCol> </IonRow> ) : null} </IonGrid> </React.Fragment> ); }; export default Traces;
the_stack
import { Application, Color, CoreTypes, Font, ImageSource, Utils, getTransformedText } from '@nativescript/core'; import { TabContentItem } from '../tab-content-item'; import { getIconSpecSize, itemsProperty, selectedIndexProperty, tabStripProperty } from '../tab-navigation-base'; import { TabStrip } from '../tab-strip'; import { TabStripItem } from '../tab-strip-item'; import { TabNavigationBase, TabsPosition, offscreenTabLimitProperty, swipeEnabledProperty } from './index-common'; export * from './index-common'; export { TabContentItem, TabStrip, TabStripItem }; const ACCENT_COLOR = 'colorAccent'; export const PRIMARY_COLOR = 'colorPrimary'; const DEFAULT_ELEVATION = 4; const TABID = '_tabId'; const INDEX = '_index'; class IconInfo { drawable: android.graphics.drawable.BitmapDrawable; height: number; } type PagerAdapter = new (owner: WeakRef<TabNavigation>, fragmentActivity: androidx.fragment.app.FragmentActivity) => androidx.viewpager2.adapter.FragmentStateAdapter; type PageChangeCallback = new (owner: WeakRef<TabNavigation>) => androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback; // eslint-disable-next-line no-redeclare let PagerAdapter: PagerAdapter; // eslint-disable-next-line no-redeclare let PageChangeCallback: PageChangeCallback; let appResources: android.content.res.Resources; function getTabById(id: number): TabNavigation { const ref = tabs.find((ref) => { const tab = ref.get(); return tab && tab._domId === id; }); return ref && ref.get(); } export interface PositionChanger { onSelectedPositionChange(position: number, prevPosition: number); } function initializeNativeClasses() { if (PagerAdapter) { return; } @NativeClass class PageChangeCallbackImpl extends androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback { private readonly owner: WeakRef<TabNavigation>; constructor(owner: WeakRef<TabNavigation>) { super(); this.owner = owner; return global.__native(this); } onPageSelected(position: number) { const owner = this.owner && this.owner.get(); if (owner) { owner.selectedIndex = position; const tabItems = owner.items; const newTabItem = tabItems ? tabItems[position] : null; if (newTabItem) { owner._loadUnloadTabItems(owner.selectedIndex); } } } } @NativeClass class TabFragmentImplementation extends org.nativescript.widgets.FragmentBase { private owner: TabNavigation; private index: number; // private backgroundBitmap: android.graphics.Bitmap = null; constructor() { super(); return global.__native(this); } static newInstance(tabId: number, index: number): TabFragmentImplementation { const args = new android.os.Bundle(); args.putInt(TABID, tabId); args.putInt(INDEX, index); const fragment = new TabFragmentImplementation(); fragment.setArguments(args); return fragment; } public onCreate(savedInstanceState: android.os.Bundle): void { super.onCreate(savedInstanceState); const args = this.getArguments(); this.owner = getTabById(args.getInt(TABID)); this.index = args.getInt(INDEX); if (!this.owner) { throw new Error('Cannot find TabView'); } } public onCreateView(inflater: android.view.LayoutInflater, container: android.view.ViewGroup, savedInstanceState: android.os.Bundle): android.view.View { const tabItem = this.owner.items[this.index]; tabItem.canBeLoaded = true; // ensure item is loaded tabItem.loadView(tabItem.content); return tabItem.nativeViewProtected; } public onDestroyView() { super.onDestroyView(); const tabItem = this.owner.items[this.index]; tabItem.canBeLoaded = false; tabItem.unloadView(tabItem.content); } } @NativeClass class FragmentPagerAdapter extends androidx.viewpager2.adapter.FragmentStateAdapter { constructor(public owner: WeakRef<TabNavigation>, fragmentActivity: androidx.fragment.app.FragmentActivity) { super(fragmentActivity); return global.__native(this); } getItemCount() { const owner = this.owner?.get(); if (!owner) { return 0; } return owner.items.length; } createFragment(position: number): androidx.fragment.app.Fragment { const owner = this.owner?.get(); if (!owner) { return null; } const fragment: androidx.fragment.app.Fragment = TabFragmentImplementation.newInstance(owner._domId, position); return fragment; } } PagerAdapter = FragmentPagerAdapter; PageChangeCallback = PageChangeCallbackImpl; appResources = Application.android.context.getResources(); } let defaultAccentColor: number; export function getDefaultAccentColor(context: android.content.Context): number { if (defaultAccentColor === undefined) { //Fallback color: https://developer.android.com/samples/SlidingTabsColors/src/com.example.android.common/view/SlidingTabStrip.html defaultAccentColor = Utils.android.resources.getPaletteColor(ACCENT_COLOR, context) || 0xff33b5e5; } return defaultAccentColor; } function setElevation(grid: org.nativescript.widgets.GridLayout, tabsBar: android.view.View, tabsPosition: string) { const compat = androidx.core.view.ViewCompat as any; if (compat.setElevation) { const val = DEFAULT_ELEVATION * Utils.layout.getDisplayDensity(); if (grid && tabsPosition === 'top') { compat.setElevation(grid, val); } if (tabsBar) { compat.setElevation(tabsBar, val); } } } export const tabs = new Array<WeakRef<TabNavigation>>(); //TODO: move to abstract export abstract class TabNavigation<T extends android.view.ViewGroup = any> extends TabNavigationBase { nativeViewProtected: org.nativescript.widgets.GridLayout; protected mTabsBar: T; protected mViewPager: androidx.viewpager2.widget.ViewPager2; protected mPageListener: androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback; protected mPagerAdapter: androidx.viewpager2.adapter.FragmentStateAdapter; protected mAndroidViewId = -1; // value from N core!!! public _originalBackground: any; protected mTextTransform: CoreTypes.TextTransformType = 'none'; protected mSelectedItemColor: Color; protected mUnSelectedItemColor: Color; fragments: androidx.fragment.app.Fragment[] = []; protected tabBarLayoutParams: org.nativescript.widgets.CommonLayoutParams; constructor() { super(); tabs.push(new WeakRef(this)); } get _hasFragments(): boolean { return true; } public onItemsChanged(oldItems: TabContentItem[], newItems: TabContentItem[]): void { super.onItemsChanged(oldItems, newItems); if (oldItems) { oldItems.forEach((item: TabContentItem, i, arr) => { (item as any).index = 0; (item as any).tabItemSpec = null; item.setNativeView(null); }); } } public createNativeView() { initializeNativeClasses(); const context: android.content.Context = this._context; const nativeView = new org.nativescript.widgets.GridLayout(context); const viewPager = new androidx.viewpager2.widget.ViewPager2(context); const lp = new org.nativescript.widgets.CommonLayoutParams(); lp.row = 1; if (this.tabsPosition === 'top') { nativeView.addRow(new org.nativescript.widgets.ItemSpec(1, org.nativescript.widgets.GridUnitType.auto)); nativeView.addRow(new org.nativescript.widgets.ItemSpec(1, org.nativescript.widgets.GridUnitType.star)); viewPager.setLayoutParams(lp); } else { nativeView.addRow(new org.nativescript.widgets.ItemSpec(1, org.nativescript.widgets.GridUnitType.star)); nativeView.addRow(new org.nativescript.widgets.ItemSpec(1, org.nativescript.widgets.GridUnitType.auto)); this.tabBarLayoutParams = lp; } nativeView.addView(viewPager); (nativeView as any).viewPager = viewPager; const adapter = (this.mPagerAdapter = new PagerAdapter(new WeakRef(this), this._context)); viewPager.setAdapter(adapter); (viewPager as any).adapter = adapter; this.mViewPager = viewPager; setElevation(nativeView, null, this.tabsPosition); if (this.tabStrip) { this.handleTabStripChanged(nativeView, null, this.tabStrip); } return nativeView; } protected abstract createNativeTabBar(context: android.content.Context): T; protected abstract setTabBarItems(tabItems: com.nativescript.material.core.TabItemSpec[]); protected abstract getTabBarItemView(index: number); protected abstract getTabBarItemTextView(index: number); protected abstract selectTabBar(oldIndex: number, newIndex: number); private handleTabStripChanged(nativeView: org.nativescript.widgets.GridLayout, oldTabStrip: TabStrip, newTabStrip: TabStrip) { if (this.mTabsBar) { nativeView.removeView(this.mTabsBar); nativeView['tabsBar'] = null; this.mTabsBar = null; } if (newTabStrip) { initializeNativeClasses(); const context = this._context; const tabsBar = (this.mTabsBar = this.createNativeTabBar(context)); setElevation(null, tabsBar, this.tabsPosition); if (this.tabsPosition !== TabsPosition.Top) { tabsBar.setLayoutParams(this.tabBarLayoutParams); } nativeView.addView(tabsBar); nativeView['tabsBar'] = tabsBar; this.setTabStripItems(newTabStrip?.items || null); } } public onTabStripChanged(oldTabStrip: TabStrip, newTabStrip: TabStrip) { super.onTabStripChanged(oldTabStrip, newTabStrip); const nativeView = this.nativeViewProtected; if (!nativeView) { return; } this.handleTabStripChanged(nativeView, oldTabStrip, newTabStrip); } onSelectedIndexChanged(oldIndex: number, newIndex: number) { if (this.mTabsBar) { this.selectTabBar(oldIndex, newIndex); } super.onSelectedIndexChanged(oldIndex, newIndex); } public initNativeView(): void { super.initNativeView(); if (this.mAndroidViewId < 0) { this.mAndroidViewId = android.view.View.generateViewId(); } this.mPageListener = new PageChangeCallback(new WeakRef(this)); this.mViewPager.setId(this.mAndroidViewId); this.mViewPager.registerOnPageChangeCallback(this.mPageListener); } public disposeNativeView() { if (this.mTabsBar) { this.setTabBarItems(null); } // setAdapter(null) will destroy fragments this.mViewPager.setAdapter(null); this.mViewPager.unregisterOnPageChangeCallback(this.mPageListener); this.mPagerAdapter = null; super.disposeNativeView(); } public onLoaded(): void { super.onLoaded(); // if (this._originalBackground) { // console.log('setting original background', this._originalBackground); // this.backgroundColor = null; // this.backgroundColor = this._originalBackground; // this._originalBackground = null; // } // this.setItems(this.items as any); if (this.tabStrip) { this.setTabStripItems(this.tabStrip.items); } } public onUnloaded(): void { super.onUnloaded(); // this.setItems(null); // this.setTabStripItems(null); // TODO: needed ? // this.items.forEach((item, i) => { // item.unloadView(item.content); // }); } private shouldUpdateAdapter(items: TabContentItem[]) { if (!this.mPagerAdapter) { return false; } const currentPagerAdapterItems = (this.mPagerAdapter as any).items; // if both values are null, should not update if (!items && !currentPagerAdapterItems) { return false; } // if one value is null, should update if (!items || !currentPagerAdapterItems) { return true; } // if both are Arrays but length doesn't match, should update if (items.length !== currentPagerAdapterItems.length) { return true; } const matchingItems = currentPagerAdapterItems.filter((currentItem) => !!items.filter((item) => item._domId === currentItem._domId)[0]); // if both are Arrays and length matches, but not all items are the same, should update if (matchingItems.length !== items.length) { return true; } // if both are Arrays and length matches and all items are the same, should not update return false; } private setItems(items: TabContentItem[]) { if (items && items.length) { items.forEach((item: TabContentItem, i) => { item.index = i; }); } this._loadUnloadTabItems(this.selectedIndex); if (this.shouldUpdateAdapter(items)) { this.mPagerAdapter.notifyDataSetChanged(); } } protected setTabStripItems(items: TabStripItem[]) { const length = items ? items.length : 0; if (length === 0) { if (this.mTabsBar) { this.setTabBarItems(null); } return; } const tabItems = new Array<com.nativescript.material.core.TabItemSpec>(); items.forEach((tabStripItem: TabStripItem, i, arr) => { tabStripItem.index = i; const tabItemSpec = this.createTabItemSpec(tabStripItem); (tabStripItem as any).tabItemSpec = tabItemSpec; tabItems.push(tabItemSpec); }); const tabsBar = this.mTabsBar; this.setTabBarItems(tabItems); this.tabStrip.setNativeView(tabsBar); items.forEach((item, i, arr) => { const tv = this.getTabBarItemTextView(i); item.setNativeView(tv); this._setItemColor(item); }); } protected createTabItemSpec(tabStripItem: TabStripItem): com.nativescript.material.core.TabItemSpec { const tabItemSpec = new com.nativescript.material.core.TabItemSpec(); if (tabStripItem.isLoaded) { const nestedLabel = tabStripItem.label; let title = nestedLabel.text; // TEXT-TRANSFORM const textTransform = this.getItemLabelTextTransform(tabStripItem); title = getTransformedText(title, textTransform); tabItemSpec.title = title; // BACKGROUND-COLOR const backgroundColor = tabStripItem.style.backgroundColor; tabItemSpec.backgroundColor = backgroundColor ? backgroundColor.android : this.getTabBarBackgroundArgbColor(); // COLOR const itemColor = this.selectedIndex === tabStripItem.index ? this.mSelectedItemColor : this.mUnSelectedItemColor; const color = itemColor || nestedLabel.style.color; tabItemSpec.color = color && color.android; // FONT const fontInternal = nestedLabel.style.fontInternal; if (fontInternal) { tabItemSpec.fontSize = fontInternal.fontSize; tabItemSpec.typeFace = fontInternal.getAndroidTypeface(); } // ICON const iconSource = tabStripItem.image && tabStripItem.image.src; if (iconSource) { const iconInfo = this.getIconInfo(tabStripItem, itemColor); if (iconInfo) { // TODO: Make this native call that accepts string so that we don't load Bitmap in JS. // tslint:disable-next-line:deprecation tabItemSpec.iconDrawable = iconInfo.drawable; tabItemSpec.imageHeight = iconInfo.height; } else { // TODO: // traceMissingIcon(iconSource); } } } return tabItemSpec; } private getOriginalIcon(tabStripItem: TabStripItem, color?: Color): android.graphics.Bitmap { const iconSource = tabStripItem.image && tabStripItem.image.src; if (!iconSource) { return null; } let is: ImageSource; if (Utils.isFontIconURI(iconSource)) { const fontIconCode = iconSource.split('//')[1]; const target = tabStripItem.image ? tabStripItem.image : tabStripItem; const font = target.style.fontInternal; if (!color) { color = target.style.color; } is = ImageSource.fromFontIconCodeSync(fontIconCode, font, color); } else { is = ImageSource.fromFileOrResourceSync(iconSource); } return is && is.android; } private getDrawableInfo(image: android.graphics.Bitmap): IconInfo { if (image) { if (this.tabStrip && this.tabStrip.isIconSizeFixed) { image = this.getFixedSizeIcon(image); } const imageDrawable = new android.graphics.drawable.BitmapDrawable(appResources, image); return { drawable: imageDrawable, height: image.getHeight() }; } return new IconInfo(); } private getIconInfo(tabStripItem: TabStripItem, color?: Color): IconInfo { const originalIcon = this.getOriginalIcon(tabStripItem, color); return this.getDrawableInfo(originalIcon); } private getFixedSizeIcon(image: android.graphics.Bitmap): android.graphics.Bitmap { const inWidth = image.getWidth(); const inHeight = image.getHeight(); const iconSpecSize = getIconSpecSize({ width: inWidth, height: inHeight }); const widthPixels = iconSpecSize.width * Utils.layout.getDisplayDensity(); const heightPixels = iconSpecSize.height * Utils.layout.getDisplayDensity(); const scaledImage = android.graphics.Bitmap.createScaledBitmap(image, widthPixels, heightPixels, true); return scaledImage; } protected abstract updateTabsBarItemAt(index: number, spec: com.nativescript.material.core.TabItemSpec); protected abstract setTabsBarSelectedIndicatorColors(colors: number[]); public updateAndroidItemAt(index: number, spec: com.nativescript.material.core.TabItemSpec) { // that try catch is fix for an android NPE error on css change which navigated in (not the current fragment) try { if (this.mTabsBar) { this.updateTabsBarItemAt(index, spec); } } catch (err) {} } public getTabBarBackgroundColor(): android.graphics.drawable.Drawable { return this.mTabsBar.getBackground(); } public setTabBarBackgroundColor(value: android.graphics.drawable.Drawable | Color): void { if (value instanceof Color) { this.mTabsBar.setBackgroundColor(value.android); } else { this.mTabsBar.setBackground(tryCloneDrawable(value, this.nativeViewProtected.getResources())); } } public getTabBarHighlightColor(): number { return getDefaultAccentColor(this._context); } public setTabBarHighlightColor(value: number | Color) { const color = value instanceof Color ? value.android : value; this.setTabsBarSelectedIndicatorColors([color]); } public getTabBarSelectedItemColor(): Color { return this.mSelectedItemColor; } public setTabBarSelectedItemColor(value: Color) { this.mSelectedItemColor = value; } public getTabBarUnSelectedItemColor(): Color { return this.mUnSelectedItemColor; } public setTabBarUnSelectedItemColor(value: Color) { this.mUnSelectedItemColor = value; } private updateItem(tabStripItem: TabStripItem): void { // TODO: Should figure out a way to do it directly with the the nativeView const tabStripItemIndex = this.tabStrip.items.indexOf(tabStripItem); const tabItemSpec = this.createTabItemSpec(tabStripItem); this.updateAndroidItemAt(tabStripItemIndex, tabItemSpec); } public setTabBarItemTitle(tabStripItem: TabStripItem, value: string): void { this.updateItem(tabStripItem); } public setTabBarItemBackgroundColor(tabStripItem: TabStripItem, value: android.graphics.drawable.Drawable | Color): void { this.updateItem(tabStripItem); } public _setItemColor(tabStripItem: TabStripItem) { if (!tabStripItem.nativeViewProtected) { return; } const itemColor = tabStripItem.index === this.selectedIndex ? this.mSelectedItemColor : tabStripItem.style.color || this.mUnSelectedItemColor; // set label color if (itemColor) { tabStripItem.nativeViewProtected.setTextColor(itemColor.android || null); } // set icon color this.setIconColor(tabStripItem, itemColor); } protected setIconColor(tabStripItem: TabStripItem, color?: Color) { if (!tabStripItem.nativeViewProtected) { return; } const tabBarItem = this.getTabBarItemView(tabStripItem.index); const drawableInfo = this.getIconInfo(tabStripItem, color); const imgView = tabBarItem.getChildAt(0) as android.widget.ImageView; imgView.setImageDrawable(drawableInfo.drawable); imgView.setColorFilter(color?.android || null); } public setTabBarItemColor(tabStripItem: TabStripItem, value: number | Color): void { const itemColor = tabStripItem.index === this.selectedIndex ? this.mSelectedItemColor : this.mUnSelectedItemColor; if (itemColor) { // the itemColor is set through the selectedItemColor and unSelectedItemColor properties // so it does not respect the css color return; } const androidColor = value instanceof Color ? value.android : value; tabStripItem.nativeViewProtected.setTextColor(androidColor); } public setTabBarIconColor(tabStripItem: TabStripItem, value: number | Color): void { const itemColor = tabStripItem.index === this.selectedIndex ? this.mSelectedItemColor : this.mUnSelectedItemColor; if (itemColor) { // the itemColor is set through the selectedItemColor and unSelectedItemColor properties // so it does not respect the css color return; } this.setIconColor(tabStripItem); } public setTabBarIconSource(tabStripItem: TabStripItem, value: number | Color): void { this.updateItem(tabStripItem); } public setTabBarItemFontInternal(tabStripItem: TabStripItem, value: Font): void { if (value.fontSize) { tabStripItem.nativeViewProtected.setTextSize(value.fontSize); } tabStripItem.nativeViewProtected.setTypeface(value.getAndroidTypeface()); } public setTabBarItemTextTransform(tabStripItem: TabStripItem, value: CoreTypes.TextTransformType): void { const nestedLabel = tabStripItem.label; const title = getTransformedText(nestedLabel.text, value); tabStripItem.nativeViewProtected.setText(title); } public setTabBarTextTransform(value: CoreTypes.TextTransformType): void { const items = this.tabStrip && this.tabStrip.items; if (items) { items.forEach((tabStripItem) => { if (tabStripItem.label && tabStripItem.nativeViewProtected) { const nestedLabel = tabStripItem.label; const title = getTransformedText(nestedLabel.text, value); tabStripItem.nativeViewProtected.setText(title); } }); } this.mTextTransform = value; } public onTabsBarSelectedPositionChange(position: number, prevPosition: number): void { this.mViewPager.setCurrentItem(position, this.animationEnabled); const tabStripItems = this.tabStrip?.items; if (position >= 0 && tabStripItems && tabStripItems[position]) { tabStripItems[position]._emit(TabStripItem.selectEvent); this._setItemColor(tabStripItems[position]); } if (prevPosition >= 0 && tabStripItems && tabStripItems[prevPosition]) { tabStripItems[prevPosition]._emit(TabStripItem.unselectEvent); this._setItemColor(tabStripItems[prevPosition]); } } public onTabsBarTap(position: number): boolean { const tabStrip = this.tabStrip; const tabStripItems = tabStrip && tabStrip.items; if (position >= 0 && tabStripItems[position]) { tabStripItems[position]._emit(TabStripItem.tapEvent); tabStrip.notify({ eventName: TabStrip.itemTapEvent, object: tabStrip, index: position }); } if (!this.items[position]) { return false; } return true; } [selectedIndexProperty.setNative](value: number) { const current = this.mViewPager.getCurrentItem(); if (current !== value) { this.mViewPager.setCurrentItem(value, this.animationEnabled); } } [itemsProperty.getDefault](): TabContentItem[] { return null; } [itemsProperty.setNative](value: TabContentItem[]) { this.setItems(value); selectedIndexProperty.coerce(this as any); } [tabStripProperty.getDefault](): TabStrip { return null; } [tabStripProperty.setNative](value: TabStrip) { this.setTabStripItems(value?.items || null); } [swipeEnabledProperty.getDefault](): boolean { return true; } [swipeEnabledProperty.setNative](value: boolean) { this.mViewPager.setUserInputEnabled(value); } [offscreenTabLimitProperty.getDefault](): number { return this.mViewPager.getOffscreenPageLimit(); } [offscreenTabLimitProperty.setNative](value: number) { this.mViewPager.setOffscreenPageLimit(value); } } function tryCloneDrawable(value: android.graphics.drawable.Drawable, resources: android.content.res.Resources): android.graphics.drawable.Drawable { if (value) { const constantState = value.getConstantState(); if (constantState) { return constantState.newDrawable(resources); } } return value; }
the_stack
import { dlog } from "./util" import { EventEmitter } from "./event" import * as monaco from "../monaco/monaco" import { EditorState } from "./editor" import { UIInput } from "./ui-input" import { UIInputResponseMsg } from "../common/messages" export type ViewZoneID = string const kViewZoneDOMObserver = Symbol("kViewZoneDOMObserver") type DomMountQueue = { el :HTMLElement, callback():void }[] function registerDOMMountCallback(editor :EditorState, el :HTMLElement, callback :()=>void) { if (document.body.contains(el)) { callback() } var ent = editor[kViewZoneDOMObserver] as [DomMountQueue, MutationObserver]|null if (ent) { ent[0].push({el, callback}) return } let queue :DomMountQueue = [ {el, callback} ] let changecount = 0 var observer = new MutationObserver((mutationsList, observer) => { for (let i = 0; i < queue.length; ) { let e = queue[i] if (document.body.contains(e.el)) { e.callback() queue.splice(i, 1) continue } i++ } if (queue.length == 0) { observer.disconnect() editor[kViewZoneDOMObserver] = null } }) let viewZonesEl = editor.editor.getDomNode().querySelector(".view-zones") observer.observe(viewZonesEl, { childList: true, subtree: true, }) ent = [queue, observer] editor[kViewZoneDOMObserver] = ent } export enum ViewZoneType { GENERIC = 0, PRINT = 1, INPUT = 2, } const kViewZoneType = Symbol("kViewZoneType") interface ViewZoneEvents { "add" :EditorState "remove" :undefined } export class ViewZone extends EventEmitter<ViewZoneEvents> implements monaco.editor.IViewZone { readonly id :ViewZoneID = "" readonly containerEl :HTMLDivElement // element containing contentEl and buttonsEl readonly contentEl :HTMLDivElement readonly buttonsEl :HTMLDivElement readonly editor :EditorState|null = null // non-null when in editor readonly sourceLine :number = -1 // current effective line number in the editor readonly sourceLineLen :number = 1 // length of source line // IViewZone interface domNode :HTMLElement suppressMouseDown :boolean = false afterLineNumber :number // Note: Use sourceLine instead when reading the value. heightInPx :number // afterColumn? :number // heightInLines? :number // minWidthInPx? :number // marginDomNode? :HTMLElement | null constructor(afterLineNumber :number, className? :string) { super() this.sourceLine = this.afterLineNumber = afterLineNumber || 0 let domNode = this.domNode = document.createElement('div') domNode.className = "inlineWidget" if (className) { domNode.className += " " + className } // let heightInLines = message.split("\n").length // if (heightInLines < 2) { // if (message.length > 40) { // // make room for wrapping text // heightInLines = 2 // } else { // domNode.className += " small" // } // } // container let containerEl = this.containerEl = document.createElement('div') domNode.appendChild(containerEl) // content this.contentEl = document.createElement('div') this.contentEl.className = "content" containerEl.appendChild(this.contentEl) // buttons this.buttonsEl = document.createElement('div') this.buttonsEl.className = "buttons" containerEl.appendChild(this.buttonsEl) let closeButtonEl = document.createElement('div') closeButtonEl.innerText = "✗" closeButtonEl.title = "Dismiss" closeButtonEl.className = "button closeButton sansSerif" closeButtonEl.addEventListener('click', ev => { ev.preventDefault() ev.stopPropagation() this.removeFromEditor() }, {passive:false, capture:true}) this.buttonsEl.appendChild(closeButtonEl) } // removeFromEditor removes this viewZone from the editor it is attached to. // removeFromEditor() { if (this.editor) { let editor = this.editor // must ref to access after call to delete editor.viewZones.delete(this.id) editor.editor.focus() } } moveToLine(line :number) { if (line == this.afterLineNumber) { return } this.afterLineNumber = line ;(this as any).sourceLine = line } // prepareForLayout is called when a view zone is about layout in response to a change // to for instance uiScale. This doesn't happen often (normally never.) // prepareForLayout() { this.afterLineNumber = this.sourceLine // copy; conceptually same value let tmpNode = this.domNode.cloneNode(true) as HTMLElement tmpNode.style.height = "auto" let size = this.editor.measureHTMLElement(tmpNode) this.heightInPx = Math.max(16, size.height) } onWillAddToEditor(editor :EditorState) { ;(this as any).editor = editor ;(this as any).sourceLine = this.afterLineNumber // copy; conceptually same value let size = this.editor.measureHTMLElement(this.domNode) this.heightInPx = Math.max(16, size.height) this.onWillMount() } onDidAddToEditor(id :ViewZoneID, replacedClassName :string) { ;(this as any).id = id // if (DEBUG) { // this.contentEl.appendChild(document.createTextNode(` #${id}`)) // } this._updateSourceLineLen() this.triggerEvent("add", this.editor) if (replacedClassName == this.constructor.name) { this.domNode.classList.add("updated") // const domNode = this.domNode // requestAnimationFrame(() => { // if (domNode.ownerDocument) { // domNode.classList.add("updated") // } // }) } } onWillRemoveFromEditor() { this.onWillUnmount() } onDidRemoveFromEditor() { ;(this as any).id = "" ;(this as any).editor = null ;(this as any).sourceLine = -1 this.triggerEvent("remove") this.onDidUnmount() // remove all listeners since this object is now dead this.removeAllListeners() } onMovedSourceLine(sourceLine :number) { let oldSourceLine = this.sourceLine ;(this as any).sourceLine = sourceLine this._updateSourceLineLen() // dlog(`ViewZone.onMovedSourceLine ${oldSourceLine} -> ${sourceLine}`) } _updateSourceLineLen() { try { ;(this as any).sourceLineLen = this.editor.currentModel.getLineLength(this.sourceLine) } catch(e) { console.warn( `[scripter/ViewZone._updateSourceLineLen] `+ `Model.getLineLength(${this.sourceLine}): ${e.stack||e}` ) ;(this as any).sourceLineLen = 1 } } // Callback which gives the relative top of the view zone as it appears // (taking scrolling into account). // onDomNodeTop(top :number) { // dlog("onDomNodeTop", top) // } // onComputedHeight is part of the IViewZone interface; a Monaco callback which gives // the height in pixels of the view zone. // We use this to get a callback for when the element was actually added to the DOM. // Note: Since we set height explicitly, we can ignore the height value. onComputedHeight(_height :number) { registerDOMMountCallback(this.editor, this.domNode, () => { this.domNode.style.width = null this.onDidMount() }) } // high-level DOM callbacks, replaceable by subclasses. // onWillMount is called before the ViewZone is introduced in the DOM. // .heightInPx is set as well as .editor and .sourceLine onWillMount() {} // onDidMount is called just after the ViewZone was introduced in the DOM. onDidMount() {} // onWillUnmount is called just before the ViewZone is removed from the DOM. onWillUnmount() {} // onDidUnmount is called just after the ViewZone was removed from the DOM. onDidUnmount() {} } // ----------------------------------------------------------------------------------------------- interface PrintViewZoneOptions { isError? :bool } export class PrintViewZone extends ViewZone { readonly pos :SourcePos readonly messageHtml :string readonly messageJs :string constructor(pos :SourcePos, messageHtml :string, messageJs :string, opt :PrintViewZoneOptions) { super(pos.line, "printWidget" + (opt.isError ? " error" : "")) this.pos = pos this.messageHtml = messageHtml this.messageJs = messageJs this.contentEl.className += " message monospace" this.contentEl.innerHTML = messageHtml if (messageHtml != "") { let inlineButtonEl = document.createElement('div') inlineButtonEl.innerText = "+" inlineButtonEl.title = "Add to script as code" inlineButtonEl.className = "button inlineButton sansSerif" inlineButtonEl.addEventListener('click', ev => { ev.stopPropagation() ev.preventDefault() this.addAsCode() }, {passive:false, capture:true}) this.buttonsEl.appendChild(inlineButtonEl) } } addAsCode() { if (!this.editor) { return } let editor = this.editor // must ref since removeFromEditor clears this.editor let lineNumber = this.sourceLine this.removeFromEditor() let insertMessage = "\n" + this.messageJs let spaces = " " if (this.pos.column > 1) { insertMessage = insertMessage.replace(/\n/g, "\n" + spaces.substr(0, this.pos.column)) } let newSelection = new monaco.Selection( lineNumber + 1, this.pos.column + 1, lineNumber + insertMessage.split("\n").length - 1, 9999 ) let sel = editor.currentModel.pushEditOperations( // beforeCursorState: Selection[], // [new monaco.Selection(lineNumber, this.pos.column, lineNumber, this.pos.column)], editor.editor.getSelections(), [{ // editOperations: IIdentifiedSingleEditOperation[], range: new monaco.Range(lineNumber,999,lineNumber,999), text: insertMessage, // This indicates that this operation has "insert" semantics: forceMoveMarkers: true }], // A callback that can compute the resulting cursors state after some edit // operations have been executed. (inverseEditOperations: monaco.editor.IIdentifiedSingleEditOperation[]) => { // let sel = editor.editor.getSelection() // if (!sel.isEmpty()) { // // don't change selection that is not empty // return null // } return [newSelection] }, // cursorStateComputer: ICursorStateComputer ) setTimeout(() => { editor.editor.setSelection(newSelection) },1) } } // ----------------------------------------------------------------------------------------------- export class InputViewZone extends ViewZone { readonly input :UIInput value :any sendTimer :any = null lastSentValue :any = undefined done :boolean = false nextResolver :InputResolver|null = null constructor(afterLineNumber :number, input :UIInput) { super(afterLineNumber, "inputWidget") this.input = input this.contentEl.appendChild(input.el) this.value = this.input.value } onDidMount() { this.input.on("change", this.onInputChange) // triggered only when changes to an input commit this.input.on("input", this.onInputInput) // triggered continously as the input changes this.input.onMountDOM() } onDidUnmount() { this.input.onUnmountDOM() this.input.removeListener("change", this.onInputChange) this.input.removeListener("input", this.onInputInput) this.done = true this.sendValue() } onInputInput = (value :any) => { this.value = value if (this.sendTimer === null) { this.sendValue() this.sendTimer = setTimeout(() => this.sendValue(), 1000/30) } } onInputChange = (value :any) => { this.value = value this.sendValue() } sendValue() { clearTimeout(this.sendTimer) ; this.sendTimer = null // dequeue next resolver if (this.done || (this.nextResolver && this.value !== this.lastSentValue)) { this.lastSentValue = this.value if (this.nextResolver) { this.nextResolver({ value: this.lastSentValue, done: this.done }) this.nextResolver = null } } } enqueueResolver(resolver :InputResolver) { if (this.nextResolver) { console.warn("[scripter] enqueueResolver while this.nextResolver != null") // let prevResolver = this.nextResolver // let nextResolver = resolver // resolver = (msg:Omit<UIInputResponseMsg,"id"|"type">) => { // prevResolver(msg) // nextResolver(msg) // } this.nextResolver({ value: this.lastSentValue, done: this.done }) } this.nextResolver = resolver } } export type InputResolver = (msg:Omit<UIInputResponseMsg,"id"|"type">)=>void
the_stack
import {ColorFormat} from '@react-types/color'; import fc from 'fast-check'; import {getDeltaE00} from 'delta-e'; import {parseColor} from '../src/Color'; import space from 'color-space'; describe('Color', function () { describe('hex', function () { it('should parse a short hex color', function () { let color = parseColor('#abc'); expect(color.getChannelValue('red')).toBe(170); expect(color.getChannelValue('green')).toBe(187); expect(color.getChannelValue('blue')).toBe(204); expect(color.getChannelValue('alpha')).toBe(1); expect(color.toString('hex')).toBe('#AABBCC'); expect(color.toString('rgb')).toBe('rgb(170, 187, 204)'); expect(color.toString('rgba')).toBe('rgba(170, 187, 204, 1)'); expect(color.toString('css')).toBe('rgba(170, 187, 204, 1)'); }); it('should parse a long hex color', function () { let color = parseColor('#abcdef'); expect(color.getChannelValue('red')).toBe(171); expect(color.getChannelValue('green')).toBe(205); expect(color.getChannelValue('blue')).toBe(239); expect(color.getChannelValue('alpha')).toBe(1); expect(color.toString('hex')).toBe('#ABCDEF'); expect(color.toString('rgb')).toBe('rgb(171, 205, 239)'); expect(color.toString('rgba')).toBe('rgba(171, 205, 239, 1)'); expect(color.toString('css')).toBe('rgba(171, 205, 239, 1)'); }); it('should throw on invalid hex value', function () { expect(() => parseColor('#ggg')).toThrow('Invalid color value: #ggg'); }); }); it('should convert a color to its equivalent hex value in decimal format', function () { const color = parseColor('#abcdef'); expect(color.toHexInt()).toBe(0xABCDEF); }); describe('rgb', function () { it('should parse a rgb color', function () { let color = parseColor('rgb(128, 128, 0)'); expect(color.getChannelValue('red')).toBe(128); expect(color.getChannelValue('green')).toBe(128); expect(color.getChannelValue('blue')).toBe(0); expect(color.getChannelValue('alpha')).toBe(1); expect(color.toString('rgb')).toBe('rgb(128, 128, 0)'); expect(color.toString('rgba')).toBe('rgba(128, 128, 0, 1)'); expect(color.toString('css')).toBe('rgba(128, 128, 0, 1)'); }); it('should parse a rgba color', function () { let color = parseColor('rgba(128, 128, 0, 0.5)'); expect(color.getChannelValue('red')).toBe(128); expect(color.getChannelValue('green')).toBe(128); expect(color.getChannelValue('blue')).toBe(0); expect(color.getChannelValue('alpha')).toBe(0.5); expect(color.toString('rgb')).toBe('rgb(128, 128, 0)'); expect(color.toString('rgba')).toBe('rgba(128, 128, 0, 0.5)'); expect(color.toString('css')).toBe('rgba(128, 128, 0, 0.5)'); }); it('normalizes rgba value by clamping', function () { let color = parseColor('rgba(300, -10, 0, 4)'); expect(color.getChannelValue('red')).toBe(255); expect(color.getChannelValue('green')).toBe(0); expect(color.getChannelValue('blue')).toBe(0); expect(color.getChannelValue('alpha')).toBe(1); expect(color.toString('rgba')).toBe('rgba(255, 0, 0, 1)'); }); }); describe('hsl', function () { it('should parse a hsl color', function () { let color = parseColor('hsl(120, 100%, 50%)'); expect(color.getChannelValue('hue')).toBe(120); expect(color.getChannelValue('saturation')).toBe(100); expect(color.getChannelValue('lightness')).toBe(50); expect(color.getChannelValue('alpha')).toBe(1); expect(color.toString('hsl')).toBe('hsl(120, 100%, 50%)'); expect(color.toString('hsla')).toBe('hsla(120, 100%, 50%, 1)'); expect(color.toString('css')).toBe('hsla(120, 100%, 50%, 1)'); }); it('should parse a hsla color', function () { let color = parseColor('hsla(120, 100%, 50%, 0.5)'); expect(color.getChannelValue('hue')).toBe(120); expect(color.getChannelValue('saturation')).toBe(100); expect(color.getChannelValue('lightness')).toBe(50); expect(color.getChannelValue('alpha')).toBe(0.5); expect(color.toString('hsl')).toBe('hsl(120, 100%, 50%)'); expect(color.toString('hsla')).toBe('hsla(120, 100%, 50%, 0.5)'); expect(color.toString('css')).toBe('hsla(120, 100%, 50%, 0.5)'); }); it('normalizes hsla value by clamping', function () { let color = parseColor('hsla(-400, 120%, -4%, -1)'); expect(color.getChannelValue('hue')).toBe(320); expect(color.getChannelValue('saturation')).toBe(100); expect(color.getChannelValue('lightness')).toBe(0); expect(color.getChannelValue('alpha')).toBe(0); expect(color.toString('hsla')).toBe('hsla(320, 100%, 0%, 0)'); }); }); it('withChannelValue', () => { let color = parseColor('hsl(120, 100%, 50%)'); let newColor = color.withChannelValue('hue', 200); expect(newColor.getChannelValue('hue')).toBe(200); expect(newColor.getChannelValue('saturation')).toBe(color.getChannelValue('saturation')); expect(newColor.getChannelValue('lightness')).toBe(color.getChannelValue('lightness')); expect(newColor.getChannelValue('alpha')).toBe(color.getChannelValue('alpha')); }); describe('hsb', function () { it('should parse a hsb color', function () { let color = parseColor('hsb(120, 100%, 50%)'); expect(color.getChannelValue('hue')).toBe(120); expect(color.getChannelValue('saturation')).toBe(100); expect(color.getChannelValue('brightness')).toBe(50); expect(color.getChannelValue('alpha')).toBe(1); expect(color.toString('hsb')).toBe('hsb(120, 100%, 50%)'); expect(color.toString('hsba')).toBe('hsba(120, 100%, 50%, 1)'); }); it('should parse a hsba color', function () { let color = parseColor('hsba(120, 100%, 50%, 0.5)'); expect(color.getChannelValue('hue')).toBe(120); expect(color.getChannelValue('saturation')).toBe(100); expect(color.getChannelValue('brightness')).toBe(50); expect(color.getChannelValue('alpha')).toBe(0.5); expect(color.toString('hsb')).toBe('hsb(120, 100%, 50%)'); expect(color.toString('hsba')).toBe('hsba(120, 100%, 50%, 0.5)'); }); it('normalizes hsba value by clamping', function () { let color = parseColor('hsba(-400, 120%, -4%, -1)'); expect(color.getChannelValue('hue')).toBe(320); expect(color.getChannelValue('saturation')).toBe(100); expect(color.getChannelValue('brightness')).toBe(0); expect(color.getChannelValue('alpha')).toBe(0); expect(color.toString('hsba')).toBe('hsba(320, 100%, 0%, 0)'); }); }); describe('conversions', () => { // Since color spaces can represent unique values that don't exist in other spaces we can't test round trips easily. // For example: hsl 0, 1%, 0 -> rgb is 0, 0, 0 -> hsl 0, 0%, 0% // In order to test round trips, we can use delta-e, a way of telling the difference/distance between two colors. // We can use a conversion to LAB as the common ground to get the delta-e. let rgb = fc.tuple(fc.integer({min: 0, max: 255}), fc.integer({min: 0, max: 255}), fc.integer({min: 0, max: 255})) .map(([r, g, b]) => (['rgb', `rgb(${r}, ${g}, ${b})`, [r, g, b]])); let hsl = fc.tuple(fc.integer({min: 0, max: 360}), fc.integer({min: 0, max: 100}), fc.integer({min: 0, max: 100})) .map(([h, s, l]) => (['hsl', `hsl(${h}, ${s}%, ${l}%)`, [h, s, l]])); let hsb = fc.tuple(fc.integer({min: 0, max: 360}), fc.integer({min: 0, max: 100}), fc.integer({min: 0, max: 100})) .map(([h, s, b]) => (['hsb', `hsb(${h}, ${s}%, ${b}%)`, [h, s, b]])); let options = fc.record({ colorSpace: fc.oneof(fc.constant('rgb'), fc.constant('hsl'), fc.constant('hsb')), color: fc.oneof(rgb, hsl, hsb) }); let parse = { rgb: (rgbString) => { let rgbRegex = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/; return rgbString.match(rgbRegex).slice(1).map(Number); }, hsl: (hslString) => { let hslRegex = /^hsl\(([\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)$/; return hslString.match(hslRegex).slice(1).map(Number); }, hsb: (hsbString) => { let hsbRegex = /^hsb\(([\d.]+),\s*([\d.]+)%,\s*([\d.]+)%\)$/; return hsbString.match(hsbRegex).slice(1).map(Number); } }; let positionMap = {0: 'L', 1: 'A', 2: 'B'}; let arrayToLab = (acc, item, index) => { acc[positionMap[index]] = item; return acc; }; it('can perform round trips', () => { fc.assert(fc.property(options, ({colorSpace, color}: {colorSpace: ColorFormat, color: [string, string, number[]]}) => { let testColor = parseColor(color[1]); let convertedColor = testColor.toString(colorSpace); let convertedColorObj = parse[colorSpace](convertedColor); let labConvertedResult = space[colorSpace === 'hsb' ? 'hsv' : colorSpace].lab(convertedColorObj).reduce(arrayToLab, {}); let labConvertedStart = space[color[0] === 'hsb' ? 'hsv' : color[0]].lab(color[2]).reduce(arrayToLab, {}); // 1.5 chosen because that's about the limit of what humans can detect and 1.1 was the largest I found when running 100k runs of this // gives us a little over 30% tolerance to changes expect(getDeltaE00(labConvertedStart, labConvertedResult)).toBeLessThan(1.5); })); }); // check a bare minimum that it won't blow up it('hsl to rgb', () => { expect(parseColor('hsl(0, 0%, 0%)').toString('rgb')).toBe('rgb(0, 0, 0)'); expect(parseColor('hsl(0, 1%, 0%)').toString('rgb')).toBe('rgb(0, 0, 0)'); expect(parseColor('hsl(0, 0%, 100%)').toString('rgb')).toBe('rgb(255, 255, 255)'); }); it('hsb to rgb', () => { expect(parseColor('hsb(0, 0%, 0%)').toString('rgb')).toBe('rgb(0, 0, 0)'); expect(parseColor('hsb(0, 1%, 0%)').toString('rgb')).toBe('rgb(0, 0, 0)'); expect(parseColor('hsb(0, 0%, 100%)').toString('rgb')).toBe('rgb(255, 255, 255)'); }); it('rgb to hsl', () => { expect(parseColor('rgb(0, 0, 0)').toString('hsl')).toBe('hsl(0, 0%, 0%)'); expect(parseColor('rgb(0, 1, 0)').toString('hsl')).toBe('hsl(120, 100%, 0.2%)'); expect(parseColor('rgb(20, 40, 60)').toString('hsl')).toBe('hsl(210, 50%, 15.69%)'); }); it('rgb to hsb', () => { expect(parseColor('rgb(0, 0, 0)').toString('hsb')).toBe('hsb(0, 0%, 0%)'); expect(parseColor('rgb(0, 1, 0)').toString('hsb')).toBe('hsb(120, 100%, 0.39%)'); expect(parseColor('rgb(20, 40, 60)').toString('hsb')).toBe('hsb(210, 66.67%, 23.53%)'); }); it('hsl to hsb', () => { expect(parseColor('hsl(0, 0%, 0%)').toString('hsb')).toBe('hsb(0, 0%, 0%)'); expect(parseColor('hsl(0, 1%, 0%)').toString('hsb')).toBe('hsb(0, 0%, 0%)'); }); it('hsb to hsl', () => { expect(parseColor('hsb(0, 0%, 0%)').toString('hsl')).toBe('hsl(0, 0%, 0%)'); expect(parseColor('hsb(0, 1%, 0%)').toString('hsl')).toBe('hsl(0, 0%, 0%)'); }); }); });
the_stack
import angular, {ICompileService, IRootScopeService, ITimeoutService} from 'angular' import 'angular-mocks' import jQuery from 'jquery' import moment from 'moment' import { expect } from 'chai' describe('Gantt', function () { // Load the module with MainController beforeEach(angular.mock.module('gantt')) let Gantt let $rootScope: IRootScopeService let $compile: ICompileService let $timeout: ITimeoutService let mockData = [ { name: 'Milestones', height: '3em', sortable: false, drawTask: false, classes: 'gantt-row-milestone', color: '#45607D', tasks: [ // Dates can be specified as string, timestamp or javascript date object. The data attribute can be used to attach a custom object { name: 'Kickoff', color: '#93C47D', from: '2013-10-07T09:00:00', to: '2013-10-07T10:00:00', data: 'Can contain any custom data or object' }, { name: 'Concept approval', color: '#93C47D', from: new Date(2013, 9, 18, 18, 0, 0), to: new Date(2013, 9, 18, 18, 0, 0), est: new Date(2013, 9, 16, 7, 0, 0), lct: new Date(2013, 9, 19, 0, 0, 0) }, { name: 'Development finished', color: '#93C47D', from: new Date(2013, 10, 15, 18, 0, 0), to: new Date(2013, 10, 15, 18, 0, 0) }, { name: 'Shop is running', color: '#93C47D', from: new Date(2013, 10, 22, 12, 0, 0), to: new Date(2013, 10, 22, 12, 0, 0) }, { name: 'Go-live', color: '#93C47D', from: new Date(2013, 10, 29, 16, 0, 0), to: new Date(2013, 10, 29, 16, 0, 0) } ], data: 'Can contain any custom data or object' }, { name: 'Status meetings', tasks: [ {name: 'Demo #1', color: '#9FC5F8', from: new Date(2013, 9, 25, 15, 0, 0), to: new Date(2013, 9, 25, 18, 30, 0)}, {name: 'Demo #2', color: '#9FC5F8', from: new Date(2013, 10, 1, 15, 0, 0), to: new Date(2013, 10, 1, 18, 0, 0)}, {name: 'Demo #3', color: '#9FC5F8', from: new Date(2013, 10, 8, 15, 0, 0), to: new Date(2013, 10, 8, 18, 0, 0)}, {name: 'Demo #4', color: '#9FC5F8', from: new Date(2013, 10, 15, 15, 0, 0), to: new Date(2013, 10, 15, 18, 0, 0)}, {name: 'Demo #5', color: '#9FC5F8', from: new Date(2013, 10, 24, 9, 0, 0), to: new Date(2013, 10, 24, 10, 0, 0)} ] }, { name: 'Kickoff', movable: {allowResizing: false}, tasks: [ { name: 'Day 1', color: '#9FC5F8', from: new Date(2013, 9, 7, 9, 0, 0), to: new Date(2013, 9, 7, 17, 0, 0), progress: {percent: 100, color: '#3C8CF8'}, movable: false }, { name: 'Day 2', color: '#9FC5F8', from: new Date(2013, 9, 8, 9, 0, 0), to: new Date(2013, 9, 8, 17, 0, 0), progress: {percent: 100, color: '#3C8CF8'} }, { name: 'Day 3', color: '#9FC5F8', from: new Date(2013, 9, 9, 8, 30, 0), to: new Date(2013, 9, 9, 12, 0, 0), progress: {percent: 100, color: '#3C8CF8'} } ] }, { name: 'Create concept', tasks: [ { name: 'Create concept', content: '<i class="fa fa-cog"></i>{{task.model.name}}', color: '#F1C232', from: new Date(2013, 9, 10, 8, 0, 0), to: new Date(2013, 9, 16, 18, 0, 0), est: new Date(2013, 9, 8, 8, 0, 0), lct: new Date(2013, 9, 18, 20, 0, 0), progress: 100 } ] }, { name: 'Finalize concept', tasks: [ { name: 'Finalize concept', color: '#F1C232', from: new Date(2013, 9, 17, 8, 0, 0), to: new Date(2013, 9, 18, 18, 0, 0), progress: 100 } ] }, { name: 'Development', children: ['Sprint 1', 'Sprint 2', 'Sprint 3', 'Sprint 4'], content: '<i class="fa fa-file-code-o"></i> {{row.model.name}}' }, { name: 'Sprint 1', tooltips: false, tasks: [ { name: 'Product list view', color: '#F1C232', from: new Date(2013, 9, 21, 8, 0, 0), to: new Date(2013, 9, 25, 15, 0, 0), progress: 25 } ] }, { name: 'Sprint 2', tasks: [ { name: 'Order basket', color: '#F1C232', from: new Date(2013, 9, 28, 8, 0, 0), to: new Date(2013, 10, 1, 15, 0, 0) } ] }, { name: 'Sprint 3', tasks: [ {name: 'Checkout', color: '#F1C232', from: new Date(2013, 10, 4, 8, 0, 0), to: new Date(2013, 10, 8, 15, 0, 0)} ] }, { name: 'Sprint 4', tasks: [ { name: 'Login & Signup & Admin Views', color: '#F1C232', from: new Date(2013, 10, 11, 8, 0, 0), to: new Date(2013, 10, 15, 15, 0, 0) } ] }, {name: 'Hosting', content: '<i class="fa fa-server"></i> {{row.model.name}}'}, { name: 'Setup', tasks: [ {name: 'HW', color: '#F1C232', from: new Date(2013, 10, 18, 8, 0, 0), to: new Date(2013, 10, 18, 12, 0, 0)} ] }, { name: 'Config', tasks: [ { name: 'SW / DNS/ Backups', color: '#F1C232', from: new Date(2013, 10, 18, 12, 0, 0), to: new Date(2013, 10, 21, 18, 0, 0) } ] }, {name: 'Server', parent: 'Hosting', children: ['Setup', 'Config']}, { name: 'Deployment', parent: 'Hosting', tasks: [ { name: 'Depl. & Final testing', color: '#F1C232', from: new Date(2013, 10, 21, 8, 0, 0), to: new Date(2013, 10, 22, 12, 0, 0), 'classes': 'gantt-task-deployment' } ] }, { name: 'Workshop', tasks: [ { name: 'On-side education', color: '#F1C232', from: new Date(2013, 10, 24, 9, 0, 0), to: new Date(2013, 10, 25, 15, 0, 0) } ] }, { name: 'Content', tasks: [ { name: 'Supervise content creation', color: '#F1C232', from: new Date(2013, 10, 26, 9, 0, 0), to: new Date(2013, 10, 29, 16, 0, 0) } ] }, { name: 'Documentation', tasks: [ { name: 'Technical/User documentation', color: '#F1C232', from: new Date(2013, 10, 26, 8, 0, 0), to: new Date(2013, 10, 28, 18, 0, 0) } ] } ] let checkData = function (data, ganttElement) { let tasks = [] angular.forEach(data, function (row) { if (row.tasks) { tasks = tasks.concat(row.tasks) } }) let rowElements = jQuery(ganttElement).find('div.gantt-body-rows div.gantt-row') let taskElements = jQuery(ganttElement).find('div.gantt-task') expect(rowElements.length).to.be.eq(data.length) expect(taskElements.length).to.be.eq(tasks.length) for (let i = 0; i < rowElements.length; i++) { let rowElement = jQuery(rowElements[i]) let rowTaskElements = rowElement.find('div.gantt-task, div.gantt-task-milestone') let rowModel = data[i] for (let j = 0; j < rowTaskElements.length; j++) { let rowTaskElement = jQuery(rowTaskElements[j]) let taskModel = rowModel.tasks[j] let taskText = rowTaskElement.find('.gantt-task-content').text() expect(taskText).to.be.eq(taskModel.name) if (taskModel.classes) { let taskClasses = taskModel.classes if (!angular.isArray(taskClasses)) { taskClasses = [taskClasses] } angular.forEach(taskClasses, function (taskClass) { expect(rowTaskElement.hasClass(taskClass)).to.be.ok }) } } } } beforeEach(inject(['$rootScope', '$compile', '$timeout', 'Gantt', function ($tRootScope: IRootScopeService, $tCompile: ICompileService, $tTimeout: ITimeoutService, tGantt) { Gantt = tGantt $rootScope = $tRootScope $compile = $tCompile $timeout = $tTimeout }])) it('should register API and call api.on.ready event', function () { let $scope = $rootScope.$new() let ganttApi let ready = false $scope.api = function (api) { ganttApi = api ganttApi.core.on.ready($scope, function () { ready = true }) } $compile('<div gantt api="api"></div>')($scope) $scope.$digest() $timeout.flush() expect(ganttApi).to.be.not.undefined expect(ready).to.be.ok ganttApi = undefined ready = false $compile('<div gantt api="api"></div>')($scope) $scope.$digest() $timeout.flush() expect(ganttApi).to.be.not.undefined expect(ready).to.be.ok } ) it('should load with no data', function () { let $scope = $rootScope.$new() let ganttElement = $compile('<div gantt></div>')($scope) $scope.$digest() $timeout.flush() checkData([], ganttElement) }) it('should load and modify data from $scope.data', function () { let $scope = $rootScope.$new() $scope.data = angular.copy(mockData) let ganttElement = $compile('<div gantt data="data"></div>')($scope) $scope.$digest() $timeout.flush() checkData($scope.data, ganttElement) $scope.data = [] $scope.$digest() checkData($scope.data, ganttElement) $scope.data = angular.copy(mockData) $scope.$digest() checkData($scope.data, ganttElement) $scope.data[2].name = 'Modified' // Change row name $scope.$digest() checkData($scope.data, ganttElement) $scope.data[2].tasks.splice(1, 0) // Remove a task $scope.$digest() checkData($scope.data, ganttElement) $scope.data[2].tasks = undefined // Removes all row task $scope.$digest() checkData($scope.data, ganttElement) $scope.data[2].tasks = [] // Set task array back $scope.$digest() checkData($scope.data, ganttElement) $scope.data[2].tasks.push(angular.copy((mockData[2] as any).tasks[1])) // Add a task $scope.$digest() checkData($scope.data, ganttElement) $scope.data[2].tasks[0].name = 'Modified' $scope.$digest() checkData($scope.data, ganttElement) $scope.data[2].tasks[0].classes = ['other-custom-class'] $scope.$digest() checkData($scope.data, ganttElement) } ) it('should load data from API', function () { let $scope = $rootScope.$new() let data = angular.copy(mockData) let ganttApi let ready = false $scope.api = function (api) { ganttApi = api ganttApi.core.on.ready($scope, function () { ready = true ganttApi.data.load(data) }) } let ganttElement = $compile('<div gantt api="api" data="data"></div>')($scope) $scope.$digest() $timeout.flush() expect($scope.data).to.be.eq(data) checkData(data, ganttElement) } ) it('should destroy scope properly', function () { let $scope = $rootScope.$new() $scope.data = angular.copy(mockData) $compile('<div gantt data="data"></div>')($scope) $scope.$digest() $timeout.flush() $scope.$destroy() } ) describe('from-date/to-date', function () { let $scope let ganttElement let ganttApi beforeEach(function () { $scope = $rootScope.$new() $scope.data = angular.copy(mockData) $scope.fromDate = undefined $scope.toDate = undefined $scope.api = function (api) { ganttApi = api } ganttElement = $compile('<div gantt data="data" api="api" from-date="fromDate" to-date="toDate"><gantt-table></gantt-table></div>')($scope) $scope.$digest() $timeout.flush() }) it('should support native date', function () { $scope.fromDate = new Date(2013, 1, 1) $scope.toDate = new Date(2014, 1, 1) $scope.$digest() checkData($scope.data, ganttElement) } ) it('should support null date', function () { $scope.fromDate = null $scope.toDate = null $scope.$digest() checkData($scope.data, ganttElement) } ) it('should support moment', function () { $scope.fromDate = moment(new Date(2013, 1, 1)) $scope.toDate = moment(new Date(2014, 1, 1)) $scope.$digest() checkData($scope.data, ganttElement) } ) it('should support invalid moment', function () { $scope.fromDate = moment(null) $scope.toDate = moment(null) $scope.$digest() checkData($scope.data, ganttElement) } ) }) })
the_stack
export interface OpenApiV3 { openapi: "3.0.2"; info: InfoObject; servers?: ServerObject[]; paths: PathsObject; components?: ComponentsObject; security?: SecurityRequirementObject[]; tags?: TagObject[]; externalDocs?: ExternalDocumentationObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#info-object export interface InfoObject { title: string; description?: string; termsOfService?: string; contact?: ContactObject; license?: LicenseObject; version: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#contact-object export interface ContactObject { name?: string; url?: string; email?: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#license-object export interface LicenseObject { name: string; url?: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#server-object export interface ServerObject { url: string; description?: string; variables?: { [serverVariable: string]: ServerVariableObject }; } // https://github.com/OAI/OpenAPI-Specification/blob/3.0.2/versions/3.0.2.md#serverVariableObject export interface ServerVariableObject { enum?: string[]; default: string; description?: string; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#pathsObject export interface PathsObject { [path: string]: PathItemObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#pathItemObject export interface PathItemObject { $ref?: string; summary?: string; description?: string; get?: OperationObject; put?: OperationObject; post?: OperationObject; delete?: OperationObject; options?: OperationObject; head?: OperationObject; patch?: OperationObject; trace?: OperationObject; servers?: ServerObject[]; parameters?: (ParameterObject | ReferenceObject)[]; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject export interface OperationObject { tags?: string[]; summary?: string; description?: string; externalDocs?: ExternalDocumentationObject; operationId?: string; parameters?: (ParameterObject | ReferenceObject)[]; requestBody?: RequestBodyObject | ReferenceObject; responses: ResponsesObject; callbacks?: { [callback: string]: CallbackObject | ReferenceObject }; deprecated?: boolean; security?: SecurityRequirementObject[]; servers?: ServerObject[]; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#referenceObject export interface ReferenceObject { $ref: string; /** * WARNING * * `nullable: true` will occur when exactly one type reference is combined with null. * * Example: * * `MyType | null` * * https://swagger.io/docs/specification/using-ref/#considerations * * Schema references cannot contain sibling elements. `nullable` therefore should * not be combined with schema reference objects. This rule was misunderstood during * development on the OpenAPI 3 generator at Airtasker. This will be removed in a * future version of Spot when Airtasker's tooling supports an alternative valid * representation for the above scenario. * * TODO: Find a way to remove this * A possible seemingly accepted workaround to this is to wrap the schema reference * into an allOf. * * Example: * * ``` * nullable: true * allOf: * - $ref: #/components/schemas/MyType * ``` */ nullable?: boolean; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#requestBodyObject export interface RequestBodyObject { description?: string; content: { [mediaType: string]: MediaTypeObject }; required?: boolean; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#mediaTypeObject export type MediaTypeObject = { schema?: SchemaObject | ReferenceObject; encoding?: { [encoding: string]: EncodingObject }; } & MutuallyExclusiveExample; // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject export type SchemaObject = | NumberSchemaObject | IntegerSchemaObject | StringSchemaObject | BooleanSchemaObject | ArraySchemaObject | ObjectSchemaObject | AnySchemaObject | AllOfSchemaObject | OneOfSchemaObject | AnyOfSchemaObject | NotSchemaObject; interface SchemaObjectBase { nullable?: boolean; not?: SchemaObject | ReferenceObject; title?: string; description?: string; example?: any; // eslint-disable-line @typescript-eslint/no-explicit-any externalDocs?: ExternalDocumentationObject; deprecated?: boolean; } export interface NumberSchemaObject extends SchemaObjectBase, NumberSchemaObjectBase { type: "number"; format?: "float" | "double"; } export interface IntegerSchemaObject extends SchemaObjectBase, NumberSchemaObjectBase { type: "integer"; format?: "int32" | "int64"; } interface NumberSchemaObjectBase { maximum?: number; exclusiveMaximum?: boolean; minimum?: number; exclusiveMinimum?: boolean; multipleOf?: number; enum?: (number | null)[]; default?: number; } export interface StringSchemaObject extends SchemaObjectBase { type: "string"; maxLength?: number; minLength?: number; /** * OpenAPI allows custom formats. We constrain the format here to those * that OpenAPI has defined and custom formats that Spot may produce. */ format?: "date" | "date-time" | "password" | "byte" | "binary"; pattern?: string; enum?: (string | null)[]; default?: string; } export interface BooleanSchemaObject extends SchemaObjectBase { type: "boolean"; enum?: (boolean | null)[]; default?: boolean; } export interface ArraySchemaObject extends SchemaObjectBase { type: "array"; items: SchemaObject | ReferenceObject; minItems?: number; maxItems?: number; uniqueItems?: boolean; default?: any[]; // eslint-disable-line @typescript-eslint/no-explicit-any } export interface ObjectSchemaObject extends SchemaObjectBase { type: "object"; properties?: ObjectPropertiesSchemaObject; required?: string[]; additionalProperties?: SchemaObject | ReferenceObject | boolean; maxProperties?: number; minProperties?: number; default?: any; // eslint-disable-line @typescript-eslint/no-explicit-any } export interface ObjectPropertiesSchemaObject { [name: string]: | (SchemaObject & ObjectPropertySchemaObjectBase) | ReferenceObject; } interface ObjectPropertySchemaObjectBase { xml?: XmlObject; readOnly?: boolean; writeOnly?: boolean; } export interface AnySchemaObject extends SchemaObjectBase { AnyValue: {}; } export interface AllOfSchemaObject extends SchemaObjectBase { allOf: (SchemaObject | ReferenceObject)[]; discriminator?: DiscriminatorObject; } export interface OneOfSchemaObject extends SchemaObjectBase { oneOf: (SchemaObject | ReferenceObject)[]; discriminator?: DiscriminatorObject; } export interface AnyOfSchemaObject extends SchemaObjectBase { anyOf: (SchemaObject | ReferenceObject)[]; discriminator?: DiscriminatorObject; } export interface NotSchemaObject extends SchemaObjectBase { not: SchemaObject | ReferenceObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#discriminatorObject export interface DiscriminatorObject { propertyName: string; mapping?: { [key: string]: string }; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#securitySchemeObject export type SecuritySchemeObject = | ApiKeySecuritySchemeObject | HttpSecuritySchemeObject | OAuth2SecuritySchemeObject | OpenIdConnectSecuritySchemeObject; export interface ApiKeySecuritySchemeObject extends SecuritySchemeObjectBase { type: "apiKey"; name: string; in: "query" | "header" | "cookie"; } export interface HttpSecuritySchemeObject extends SecuritySchemeObjectBase { type: "http"; scheme: string; bearerFormat?: string; } export interface OAuth2SecuritySchemeObject extends SecuritySchemeObjectBase { type: "oauth2"; flows: OAuthFlowsObject; } export interface OpenIdConnectSecuritySchemeObject extends SecuritySchemeObjectBase { type: "openIdConnect"; openIdConnectUrl: string; } interface SecuritySchemeObjectBase { type: SecuritySchemeType; description?: string; } type SecuritySchemeType = "apiKey" | "http" | "oauth2" | "openIdConnect"; // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#oauthFlowsObject export interface OAuthFlowsObject { implicit?: ImplicitOAuthFlowObject; password?: PasswordOAuthFlowObject; clientCredentials?: ClientCredentialsOAuthFlowObject; authorizationCode?: AuthorizationCodeOAuthFlowObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#oauthFlowObject export interface ImplicitOAuthFlowObject extends OAuthFlowObjectBase { authorizationUrl: string; } export interface PasswordOAuthFlowObject extends OAuthFlowObjectBase { tokenUrl: string; } export interface ClientCredentialsOAuthFlowObject extends OAuthFlowObjectBase { tokenUrl: string; } export interface AuthorizationCodeOAuthFlowObject extends OAuthFlowObjectBase { authorizationUrl: string; tokenUrl: string; } interface OAuthFlowObjectBase { refreshUrl?: string; scopes: { [scope: string]: string }; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#securityRequirementObject export interface SecurityRequirementObject { [name: string]: string[]; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#componentsObject export interface ComponentsObject { schemas?: { [schema: string]: SchemaObject | ReferenceObject }; responses?: { [response: string]: ResponseObject | ReferenceObject }; parameters?: { [parameter: string]: ParameterObject | ReferenceObject }; examples?: { [example: string]: ExampleObject | ReferenceObject }; requestBodies?: { [request: string]: RequestBodyObject | ReferenceObject }; headers?: { [header: string]: HeaderObject | ReferenceObject }; securitySchemes?: { [securityScheme: string]: SecuritySchemeObject | ReferenceObject; }; links?: { [link: string]: LinkObject | ReferenceObject }; callbacks?: { [callback: string]: CallbackObject | ReferenceObject }; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#xmlObject export interface XmlObject { name?: string; namespace?: string; prefix?: string; attribute?: boolean; wrapped?: boolean; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#exampleObject export type ExampleObject = { summary?: string; description?: string; value?: any; // eslint-disable-line @typescript-eslint/no-explicit-any externalValue?: string; } & MutuallyExclusiveExampleObjectValue; type MutuallyExclusiveExampleObjectValue = | { value: any; // eslint-disable-line @typescript-eslint/no-explicit-any externalValue?: never; } | { value?: never; externalValue: string; }; // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#encoding-object export interface EncodingObject { contentType?: string; headers?: { [name: string]: HeaderObject | ReferenceObject }; style?: string; explode?: boolean; allowReserved?: boolean; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#responsesObject export interface ResponsesObject { [statusCodeOrDefault: string]: ResponseObject | ReferenceObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#responseObject export interface ResponseObject { description: string; headers?: { [name: string]: HeaderObject | ReferenceObject }; content?: { [mediaType: string]: MediaTypeObject }; links?: { [link: string]: LinkObject | ReferenceObject }; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#parameterObject export type ParameterObject = | QueryParameterObject | HeaderParameterObject | PathParameterObject | CookieParameterObject; export type QueryParameterObject = ParameterObjectBase & { in: "query"; allowEmptyValue?: boolean; style?: "form" | "spaceDelimited" | "pipeDelimited" | "deepObject"; allowReserved?: boolean; }; export type HeaderParameterObject = ParameterObjectBase & { in: "header"; style?: "simple"; }; export type PathParameterObject = ParameterObjectBase & { in: "path"; required: true; style?: "simple" | "label" | "matrix"; }; export type CookieParameterObject = ParameterObjectBase & { in: "cookie"; style?: "form"; }; // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#headerObject export type HeaderObject = Omit<HeaderParameterObject, "name" | "in">; type ParameterObjectBase = { name: string; in: "query" | "header" | "path" | "cookie"; description?: string; required?: boolean; deprecated?: boolean; style?: ParameterStyle; explode?: boolean; schema?: SchemaObject | ReferenceObject; } & MutuallyExclusiveExample; type ParameterStyle = | "matrix" | "label" | "form" | "simple" | "spaceDelimited" | "pipeDelimited" | "deepObject"; // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#callbackObject export interface CallbackObject { [name: string]: PathItemObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#linkObject type LinkObject = { parameters?: { [name: string]: any }; // eslint-disable-line @typescript-eslint/no-explicit-any requestBody?: any; // eslint-disable-line @typescript-eslint/no-explicit-any description?: string; server?: ServerObject; } & MutuallyExclusiveLinkObjectOperation; type MutuallyExclusiveLinkObjectOperation = | { operationRef: string; operationId?: never; } | { operationRef?: never; operationId: string; }; // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#tagObject export interface TagObject { name: string; description?: string; externalDocs?: ExternalDocumentationObject; } // https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#externalDocumentationObject export interface ExternalDocumentationObject { description?: string; url: string; } // Common export type ExamplesSet = { [example: string]: ExampleObject | ReferenceObject; }; type MutuallyExclusiveExample = | { example?: any; // eslint-disable-line @typescript-eslint/no-explicit-any examples?: never; } | { example?: never; examples?: ExamplesSet; };
the_stack
* @module OrbitGT */ //package orbitgt.spatial.ecrs; type int8 = number; type int16 = number; type int32 = number; type float32 = number; type float64 = number; import { AList } from "../../system/collection/AList"; import { ASystem } from "../../system/runtime/ASystem"; import { Strings } from "../../system/runtime/Strings"; import { Coordinate } from "../geom/Coordinate"; import { Axis } from "./Axis"; import { CoordinateSystem } from "./CoordinateSystem"; import { Datum } from "./Datum"; import { Ellipsoid } from "./Ellipsoid"; import { Operation } from "./Operation"; import { OperationMethod } from "./OperationMethod"; import { Registry } from "./Registry"; import { Transform } from "./Transform"; import { Unit } from "./Unit"; import { VerticalModel } from "./VerticalModel"; /** * Class CRS defines the parameters of a coordinate reference system. * NOTE: geographic (lon-lat) CRSs have their coordinates in degrees (0..360) instead of radians (0..2PI). * NOTE: geocentric (ECEF) CRSs have their coordinates in meters. * * Based on the following document: * * Coordinate Conversions and Transformations including Formulas * Guidance Note Number 7, part 2 * Revised May 2005 * Available at: http://www.epsg.org/ * * @version 1.0 July 2005 */ /** @internal */ export class CRS { /** The type of a compound CRS */ public static readonly COMPOUND: int32 = 1; /** The type of a engineering CRS */ public static readonly ENGINEERING: int32 = 2; /** The type of a geocentric CRS */ public static readonly GEOCENTRIC: int32 = 3; /** The type of a geographic-2D CRS */ public static readonly GEOGRAPHIC_2D: int32 = 4; /** The type of a geographic-3D CRS */ public static readonly GEOGRAPHIC_3D: int32 = 5; /** The type of a projected CRS */ public static readonly PROJECTED: int32 = 6; /** The type of a vertical CRS */ public static readonly VERTICAL: int32 = 7; /** The identification code of the WGS 84 geocentric reference system */ public static readonly WGS84_GEOCENTRIC_CRS_CODE: int32 = 4978; /** The identification code of the WGS 84 3D coordinate reference system */ public static readonly WGS84_3D_CRS_CODE: int32 = 4979; /** The identification code of the WGS 84 2D coordinate reference system */ public static readonly WGS84_2D_CRS_CODE: int32 = 4326; /** The identification code of the WGS 84 datum */ private static readonly WGS84_DATUM_CODE: int32 = 6326; /** The identification code of the WGS 84 geocentric coordinate reference system */ public static readonly CRS_WGS84_GEOCENTRIC: string = "4978"; /** The identification code of the WGS 84 geographic coordinate reference system */ public static readonly CRS_WGS84_3D: string = "4979"; /** The identification code of the WGS 84 2D coordinate reference system */ public static readonly CRS_WGS84_2D: string = "4326"; /** The cache of the WGS 84 geocentric coordinate reference system (4978) */ private static _CACHE_WGS84_GEOCENTRIC: CRS = null; /** The cache of the WGS 84 geographic coordinate reference system (4979) */ private static _CACHE_WGS84_3D: CRS = null; /** The cache of the WGS 84 2D coordinate reference system (4326) */ private static _CACHE_WGS84_2D: CRS = null; /** The code */ private _code: int32; /** The name */ private _name: string; /** The area of use */ private _area: int32; /** The type (PROJECTED,GEOGRAPHIC_2D,GEOGRAPHIC_3D,GEOCENTRIC,VERTICAL,COMPOUND,...) */ private _type: int32; /** The coordinate-system code */ private _csCode: int32; /** The coordinate axes (defined by the csCode) */ private _axes: AList<Axis>; /** The coordinate system (can be null) */ private _coordinateSystem: CoordinateSystem; /** The datum */ private _datum: Datum; /** The base geographic CRS */ private _baseCRS: CRS; /** The projection (from the base CRS to this CRS) */ private _projection: Operation; /** The transformations from the base geocentric CRS to the geocentric WGS (CRS 4326) */ private _transformationsToWGS: AList<Operation>; /** The default transformation from the base geocentric CRS to the geocentric WGS (CRS 4326) */ private _transformationToWGS: Operation; /** The horizontal CRS (type COMPOUND) */ private _horizontalComponent: CRS; /** The vertical CRS (type COMPOUND) */ private _verticalComponent: CRS; /** The vertical model (type VERTICAL) */ private _verticalModel: VerticalModel; /** The text information (WKT) of the CRS */ private _textForm: string; /** The access time of the CRS (for garbage collecting the dynamic CRS) */ private _accessTime: float64; /** * Create a new CRS. * @param code the code. * @param name the name. * @param area the area of use. * @param type the type. * @param csCode the coordinate-system code. * @param datum the datum. * @param baseCRS the base geographic CRS. * @param projection the projection (from the base CRS to this CRS). * @param transformationsToWGS the transformations from the base geographic CRS to the WGS 84 datum (of CRS 4326). */ public constructor(code: int32, name: string, area: int32, type: int32, csCode: int32, datum: Datum, baseCRS: CRS, projection: Operation, transformationsToWGS: AList<Operation>) { /* Store the parameters */ this._code = code; this._name = name; this._area = area; this._type = type; this._csCode = csCode; this._axes = null; this._coordinateSystem = null; this._datum = datum; this._baseCRS = baseCRS; this._projection = projection; this._transformationsToWGS = transformationsToWGS; /* Get the default transform */ this._transformationToWGS = Operation.getLatestTransformation(transformationsToWGS); /* Clear */ this._horizontalComponent = null; this._verticalComponent = null; this._verticalModel = null; this._textForm = null; this._accessTime = 0.0; } /** * Create a compound CRS. * @param code the code. * @param name the name. * @param area the area of use. * @param horizontalCRS the horizontal CRS. * @param verticalCRS the vertical CRS. * @return the compound CRS. */ public static createCompound(code: int32, name: string, area: int32, horizontalCRS: CRS, verticalCRS: CRS): CRS { /* Check the parameters */ ASystem.assertNot(horizontalCRS == null, "No horizontal CRS"); ASystem.assertNot(verticalCRS == null, "No vertical CRS"); ASystem.assertNot(horizontalCRS.isVertical(), "CRS is not horizontal: " + horizontalCRS); ASystem.assertNot(verticalCRS.isVertical() == false, "CRS is not vertical: " + verticalCRS); /* Make the CRS */ let crs: CRS = new CRS(code, name, area, CRS.COMPOUND, 0/*csCode*/, null/*datum*/, null/*baseCRS*/, null/*projection*/, null/*transformationsToWGS*/); crs._horizontalComponent = horizontalCRS; crs._verticalComponent = verticalCRS; /* Return the CRS */ return crs; } /** * Get the code. * @return the code. */ public getCode(): int32 { return this._code; } /** * Get the string code. * @return the string code. */ public getStringCode(): string { return "" + this._code; } /** * Check if a code matches the CRS code. * @param code the code. * @return true if the code matches. */ public hasStringCode(code: string): boolean { return Strings.equals(code, this.getStringCode()); } /** * Get the name. * @return the name. */ public getName(): string { return this._name; } /** * Get the area of use. * @return the area. */ public getArea(): int32 { return this._area; } /** * Get the type. * @return the type. */ public getType(): int32 { return this._type; } /** * Get the type label. * @return the type label. */ public getTypeLabel(): string { return CRS.labelCRSType(this._type); } /** * Is this a geocentric CRS? * @return true for a geocentric CRS. */ public isGeoCentric(): boolean { return (this._type == CRS.GEOCENTRIC); } /** * Is this a geographic CRS? * @return true for a projected CRS. */ public isGeoGraphic(): boolean { return (this._type == CRS.GEOGRAPHIC_2D || this._type == CRS.GEOGRAPHIC_3D); } /** * Is this a geographic 2D CRS? * @return true for a projected 2D CRS. */ public isGeoGraphic2D(): boolean { return (this._type == CRS.GEOGRAPHIC_2D); } /** * Is this a geographic 3D CRS? * @return true for a projected 3D CRS. */ public isGeoGraphic3D(): boolean { return (this._type == CRS.GEOGRAPHIC_3D); } /** * Is this a projected CRS? * @return true for a projected CRS. */ public isProjectedType(): boolean { return (this._type == CRS.PROJECTED); } /** * Is this a projected CRS? * @return true for a projected CRS. */ public isProjected(): boolean { if (this._type == CRS.COMPOUND) return this._horizontalComponent.isProjected(); return (this._type == CRS.PROJECTED); } /** * Is this a vertical CRS? * @return true for a vertical CRS. */ public isVertical(): boolean { return (this._type == CRS.VERTICAL); } /** * Is this a compound CRS? * @return true for a compound CRS. */ public isCompound(): boolean { return (this._type == CRS.COMPOUND); } /** * Get the coordinate-system code. * @return the coordinate-system code. */ public getCoordinateSystemCode(): int32 { return this._csCode; } /** * Get the coordinate system. * @return the coordinate system (can be null if standard). */ public getCoordinateSystem(): CoordinateSystem { return this._coordinateSystem; } /** * Get the datum. * @return the datum. */ public getDatum(): Datum { if (this._datum != null) return this._datum; if (this._baseCRS != null) return this._baseCRS.getDatum(); return null; } /** * Get the code of the datum. * @return the code of the datum (0 if there is no datum). */ public getDatumCode(): int32 { let datum: Datum = this.getDatum(); return (datum == null) ? 0 : datum.getCode(); } /** * Set the datum. * @param datum the new datum (if null check the base CRS). */ public setDatum(datum: Datum): void { this._datum = datum; } /** * Get the ellipsoid. * @return the ellipsoid. */ public getEllipsoid(): Ellipsoid { return this.getDatum().getEllipsoid(); } /** * Get the base geographic CRS. * @return the base geographic CRS. */ public getBaseCRS(): CRS { return this._baseCRS; } /** * Set the base geographic CRS. * @param baseCRS the new base geographic CRS. */ public setBaseCRS(baseCRS: CRS): void { this._baseCRS = baseCRS; } /** * Get the coordinate axis of the CRS. * @return the coordinate axis of the CRS. */ public getAxes(): AList<Axis> { return this._axes; } /** * Set the coordinate axis of the CRS. * @param axis the coordinate axis of the CRS. */ public setAxes(axes: AList<Axis>): void { /* Store the parameters */ this._axes = axes; /* Update the coordinate system */ this._coordinateSystem = CoordinateSystem.create(this._type, this._csCode, this._axes); } /** * Get the unit code of the first coordinate axis of the CRS. * @return the unit code (defaults to METER). */ public getFirstAxisUnitCode(): int32 { if (this._type == CRS.COMPOUND) return this._horizontalComponent.getFirstAxisUnitCode(); if (this._axes == null) return Unit.METER; if (this._axes.size() == 0) return Unit.METER; return this._axes.get(0).getUnitCode(); } /** * Get the projection (from the base CRS to this CRS). * @return the projection. */ public getProjection(): Operation { return this._projection; } /** * Set the projection (from the base CRS to this CRS). * @param projection the projection. */ public setProjection(projection: Operation): void { this._projection = projection; } /** * Get the projection method (from the base CRS to this CRS). * @return the projection method. */ public getProjectionMethod(): OperationMethod { if (this._projection == null) return null; return this._projection.getMethod(); } /** * Get the horizontal component of a compound CRS. * @return the horizontal component of a compound CRS. */ public getHorizontalComponent(): CRS { /* Check the type */ ASystem.assertNot(this._type != CRS.COMPOUND, "CRS " + this._code + " is not compound"); /* Return the component */ return this._horizontalComponent; } /** * Check if there is a vertical component (only for type COMPOUND). * @return true if there is a vertical component. */ public hasVerticalComponent(): boolean { /* Check the type */ if (this._type != CRS.COMPOUND) return false; /* Check the component */ return (this._verticalComponent != null); } /** * Get the vertical component of a compound CRS. * @return the vertical component of a compound CRS. */ public getVerticalComponent(): CRS { /* Check the type */ ASystem.assertNot(this._type != CRS.COMPOUND, "CRS " + this._code + " is not compound"); /* Return the component */ return this._verticalComponent; } /** * Get the vertical model (only for type VERTICAL). * @return the vertical model. */ public getVerticalModel(): VerticalModel { return this._verticalModel; } /** * Set the vertical model (only for type VERTICAL). * @param verticalModel the vertical model. */ public setVerticalModel(verticalModel: VerticalModel): void { this._verticalModel = verticalModel; } /** * Peek at the transformations from the base geographic CRS to the WGS 84 datum (of CRS 4326). * @return the transformations. */ public peekTransformationsToWGS(): AList<Operation> { return this._transformationsToWGS; } /** * Get the transformations from the base geographic CRS to the WGS 84 datum (of CRS 4326). * @return the transformations. */ public getTransformationsToWGS(): AList<Operation> { if ((this._transformationsToWGS != null) && (this._transformationsToWGS.size() > 0)) return this._transformationsToWGS; if (this._baseCRS != null) return this._baseCRS.getTransformationsToWGS(); return new AList<Operation>(); } /** * Set the transformations from the base geographic CRS to the WGS 84 datum (of CRS 4326). * @param transformations the transformations. */ public setTransformationsToWGS(transformations: AList<Operation>): void { this._transformationsToWGS = transformations; } /** * Get the default transformation from the base geographic CRS to the WGS 84 datum (of CRS 4326). * @return a transformation (null if not available). */ public getTransformationToWGS(): Operation { if (this._transformationToWGS != null) return this._transformationToWGS; if (this._baseCRS != null) return this._baseCRS.getTransformationToWGS(); return null; } /** * Set the default transformation from the base geographic CRS to the WGS 84 datum (of CRS 4326). * @param transformation a transformation (null if not available). */ public setTransformationToWGS(transformation: Operation): void { this._transformationToWGS = transformation; } /** * Convert to a geocentric coordinate. * @param local the coordinate in this CRS. * @return the geocentric coordinate. */ public toGeoCentric(local: Coordinate): Coordinate { /* Projection ? */ if (this._type == CRS.PROJECTED) { /* We need a geographic base CRS */ ASystem.assertNot(this._baseCRS.isGeoGraphic() == false, "Projected CRS '" + this._code + "' needs a geographic base CRS '" + this._baseCRS.getCode() + "', not '" + this._baseCRS.getTypeLabel() + "'"); /* Convert to standard units */ let projected: Coordinate = local.copy(); if (this._coordinateSystem != null) this._coordinateSystem.localToStandard(projected, projected); /* Inverse the projection to get geographic (lon,lat) coordinates (radians) */ let geographic: Coordinate = new Coordinate(0.0, 0.0, 0.0); this._projection.reverse(geographic, projected); /* The geographic coordinates are in degrees */ geographic.setX(geographic.getX() / Math.PI * 180.0); geographic.setY(geographic.getY() / Math.PI * 180.0); /* Let the base CRS calculate the geocentric coordinates */ return this._baseCRS.toGeoCentric(geographic); } /* Geocentric ? */ if (this._type == CRS.GEOCENTRIC) { /* Already geocentric */ return local.copy(); } /* Geographic ? */ if (this._type == CRS.GEOGRAPHIC_2D || this._type == CRS.GEOGRAPHIC_3D) { /* All geographic coordinates are in degrees */ let geographic: Coordinate = local.copy(); geographic.setX(geographic.getX() / 180.0 * Math.PI); geographic.setY(geographic.getY() / 180.0 * Math.PI); /* Convert from geographic (radians) to geocentric */ let geocentric: Coordinate = new Coordinate(0.0, 0.0, 0.0); this._datum.getEllipsoid().toGeoCentric(geographic, geocentric); /* Return the geocentric coordinates */ return geocentric; } /* We cannot transform */ ASystem.assertNot(true, "No geocentric transform for " + this); return null; } /** * Convert from a geocentric coordinate. * @param geocentric the geocentric coordinate. * @return the coordinate in this CRS. */ public fromGeoCentric(geocentric: Coordinate): Coordinate { /* Projection ? */ if (this._type == CRS.PROJECTED) { /* We need a geographic base CRS */ ASystem.assertNot(this._baseCRS.isGeoGraphic() == false, "Projected CRS '" + this._code + "' needs a geographic base CRS '" + this._baseCRS.getCode() + "', not '" + this._baseCRS.getTypeLabel() + "'"); /* Get the geographic coordinate */ let geographic: Coordinate = this._baseCRS.fromGeoCentric(geocentric); /* The geographic coordinates are in degrees */ geographic.setX(geographic.getX() / 180.0 * Math.PI); geographic.setY(geographic.getY() / 180.0 * Math.PI); /* Make the projection */ let projected: Coordinate = new Coordinate(0.0, 0.0, 0.0); this._projection.forward(geographic, projected); /* Convert to local units */ if (this._coordinateSystem != null) this._coordinateSystem.standardToLocal(projected, projected); /* Return the projected coordinate */ return projected; } /* Geocentric ? */ if (this._type == CRS.GEOCENTRIC) { /* Already geocentric */ return geocentric.copy(); } /* Geographic ? */ if (this._type == CRS.GEOGRAPHIC_2D || this._type == CRS.GEOGRAPHIC_3D) { /* Convert from geocentric to geographic (radians) */ let geographic: Coordinate = new Coordinate(0.0, 0.0, 0.0); this._datum.getEllipsoid().toGeoGraphic(geocentric, geographic); /* All geographic coordinates need to be in degrees */ geographic.setX(geographic.getX() / Math.PI * 180.0); geographic.setY(geographic.getY() / Math.PI * 180.0); /* Return the geographic coordinate */ return geographic; } /* We cannot transform */ ASystem.assertNot(true, "No geocentric transform for " + this); return null; } /** * Check if this CRS is a projection of another CRS. * @param geographic the geographic CRS to check. * @return true if this is a projection of the geographic CRS. */ public isProjectionOf(geographic: CRS): boolean { /* This has to be a projection */ if (this._type != CRS.PROJECTED) return false; if (this._projection == null) return false; if (this._baseCRS == null) return false; /* We need a geographic system */ if (geographic._type != CRS.GEOGRAPHIC_2D && geographic._type != CRS.GEOGRAPHIC_3D) return false; /* Is this our base CRS? */ return (this._baseCRS.isCompatible(geographic)); } /** * Convert from a geographic coordinate to a projected coordinate. * @param geographic the source geographic coordinate (in degrees). * @param projected the target projected coordinate (use null to create a new coordinate). * @return the projected coordinate. */ public toProjected(geographic: Coordinate, projected: Coordinate): Coordinate { /* Create target? */ if (projected == null) projected = new Coordinate(0.0, 0.0, 0.0); /* The geographic coordinates are kept in degrees */ projected.setX(geographic.getX() / 180.0 * Math.PI); projected.setY(geographic.getY() / 180.0 * Math.PI); projected.setZ(geographic.getZ()); /* Make the projection */ this._projection.forward(projected, projected); /* Convert to local units */ if (this._coordinateSystem != null) this._coordinateSystem.standardToLocal(projected, projected); /* Return the result */ return projected; } /** * Convert from a projected coordinate to a geographic coordinate. * @param projected the source projected coordinate. * @param geographic the target geographic coordinate (in degrees) (use null to create a new coordinate). * @return the geographic coordinate. */ public fromProjected(projected: Coordinate, geographic: Coordinate): Coordinate { /* Create target? */ if (geographic == null) geographic = new Coordinate(0.0, 0.0, 0.0); /* Convert to standard units */ let projected2: Coordinate = projected.copy(); if (this._coordinateSystem != null) this._coordinateSystem.localToStandard(projected2, projected2); /* Inverse the projection to get the geographic (lon,lat) coordinates (radians) */ this._projection.reverse(geographic, projected2); /* The geographic coordinates are kept in degrees */ geographic.setX(geographic.getX() / Math.PI * 180.0); geographic.setY(geographic.getY() / Math.PI * 180.0); /* Return the result */ return geographic; } /** * Get the WGS 84 2D geocentric reference system. * @return the WGS 84 2D geocentric reference system. */ private static getWGS84_GeoCentric(): CRS { if (CRS._CACHE_WGS84_GEOCENTRIC == null) CRS._CACHE_WGS84_GEOCENTRIC = Registry.getCRS2(CRS.CRS_WGS84_GEOCENTRIC); return CRS._CACHE_WGS84_GEOCENTRIC; } /** * Get the WGS 84 2D geographic reference system. * @return the WGS 84 2D geographic reference system. */ private static getWGS84_3D(): CRS { if (CRS._CACHE_WGS84_3D == null) CRS._CACHE_WGS84_3D = Registry.getCRS2(CRS.CRS_WGS84_3D); return CRS._CACHE_WGS84_3D; } /** * Get the WGS 84 2D coordinate reference system. * @return the WGS 84 2D coordinate reference system. */ private static getWGS84_2D(): CRS { if (CRS._CACHE_WGS84_2D == null) CRS._CACHE_WGS84_2D = Registry.getCRS2(CRS.CRS_WGS84_2D); return CRS._CACHE_WGS84_2D; } /** * Is a conversion to and from the WGS 84 coordinate system possible? * @return true if possible. */ public isWGSCompatible(): boolean { /* Already in WGS ? */ if (this.getDatum().getCode() == CRS.WGS84_DATUM_CODE) return true; /* Get the transformation from the local datum to the WGS datum */ let localToWGS: Operation = this.getTransformationToWGS(); if (localToWGS == null) return false; /* Compatible */ return true; } /** * Convert a coordinate to the WGS 84 (geographic 2D) coordinate system. * @param source the coordinates in this CRS. * @param wgsTransformationIndex the index of the WGS transformation to use (negative for the default transformation). * @return the WGS 84 coordinate, x is longitude(-180..+180), y is latitude(-90..+90) and z is height (the z height is the same as the local height). */ public toWGSi(source: Coordinate, wgsTransformationIndex: int32): Coordinate { /* Already in the WGS datum ? */ if (this.getDatum().getCode() == CRS.WGS84_DATUM_CODE) { /* Geocentric ? */ if (this._type == CRS.GEOCENTRIC) { /* Convert from geocentric to geographic coordinates */ let ageographic: Coordinate = new Coordinate(0.0, 0.0, 0.0); this._datum.getEllipsoid().toGeoGraphic(source/*geocentric*/, ageographic); /* The WGS coordinates need to be in degrees */ ageographic.setX(ageographic.getX() / Math.PI * 180.0); ageographic.setY(ageographic.getY() / Math.PI * 180.0); /* Return the WGS coordinates */ return ageographic; } /* Projected ? */ if (this._projection != null) { /* Convert to standard units */ let projected: Coordinate = source.copy(); if (this._coordinateSystem != null) this._coordinateSystem.localToStandard(projected, projected); /* Inverse the projection to go from projected to geographic (lon,lat) coordinates */ let ageographic: Coordinate = new Coordinate(0.0, 0.0, 0.0); this._projection.reverse(ageographic, projected); /* The WGS coordinates need to be in degrees */ ageographic.setX(ageographic.getX() / Math.PI * 180.0); ageographic.setY(ageographic.getY() / Math.PI * 180.0); /* Return the WGS coordinates */ return ageographic; } /* Geographic */ return new Coordinate(source.getX(), source.getY(), source.getZ()); } /* Get the transformation from the local datum to the WGS datum */ let localToWGS: Operation = (wgsTransformationIndex < 0) ? this.getTransformationToWGS() : this.getTransformationsToWGS().get(wgsTransformationIndex); // if (localToWGS==null) // { // /* We cannot transform */ // ASystem.assert(false,"No datum transformation from "+this+" to WGS"); // } /* Does the transform work on the projected coordinates (like the OSTN02 grid correction)? */ let geocentric: Coordinate; if ((localToWGS != null) && localToWGS.getSourceCRS().isProjected()) { /* Start with the projected coordinate */ geocentric = new Coordinate(source.getX(), source.getY(), source.getZ()); } else { /* Calculate the geocentric coordinate */ geocentric = this.toGeoCentric(new Coordinate(source.getX(), source.getY(), source.getZ())); } /* Apply the transform to the WGS datum */ if (localToWGS != null) localToWGS.forward(geocentric, geocentric); /* Get the geographic coordinate */ let geographic: Coordinate = CRS.getWGS84_2D().fromGeoCentric(geocentric); /* Does the transform work on the projected coordinates (like the OSTN02 grid correction)? */ if ((localToWGS != null) && localToWGS.getSourceCRS().isProjected()) { /* Assume we have the right Z */ } else { /* Restore the original Z (is this allowed??) <ISSUE> */ geographic.setZ(source.getZ()); } /* Return the WGS geographic coordinates */ return geographic; } /** * Convert a coordinate to the WGS 84 (geographic 2D) coordinate system. * @param source the coordinates in this CRS. * @return the WGS 84 coordinate, x is longitude(-180..+180), y is latitude(-90..+90) and z is height (the z height is the same as the local height). */ public toWGS(source: Coordinate): Coordinate { return this.toWGSi(source, -1); } /** * Convert from the WGS 84 (geographic 2D) coordinate system to this coordinate system. * @param source the coordinates in the WGS 84 coordinate system, where x is longitude(-180..+180), y is latitude(-90..+90) and z is height. * @param wgsTransformationIndex the index of the WGS transformation to use (negative for the default transformation). * @return the coordinates in this CRS (the z height is the same as the WGS height). */ public fromWGSi(source: Coordinate, wgsTransformationIndex: int32): Coordinate { /* Already in the WGS datum ? */ if (this.getDatum().getCode() == CRS.WGS84_DATUM_CODE) { /* Geocentric ? */ if (this._type == CRS.GEOCENTRIC) { /* Convert to radians */ let lon: float64 = source.getX() / 180.0 * Math.PI; let lat: float64 = source.getY() / 180.0 * Math.PI; let geographic: Coordinate = new Coordinate(lon, lat, source.getZ()); /* Convert from geographic to geocentric coordinates */ let geocentric: Coordinate = new Coordinate(0.0, 0.0, 0.0); this._datum.getEllipsoid().toGeoCentric(geographic, geocentric); /* Return the geocentric coordinates */ return geocentric; } /* Projected ? */ if (this._projection != null) { /* Convert to radians */ let lon: float64 = source.getX() / 180.0 * Math.PI; let lat: float64 = source.getY() / 180.0 * Math.PI; let geographic: Coordinate = new Coordinate(lon, lat, source.getZ()); /* Use the projection to go from geographic (lon,lat) coordinates to projected coordinates */ let projected: Coordinate = new Coordinate(0.0, 0.0, 0.0); this._projection.forward(geographic, projected); /* Convert to local units */ if (this._coordinateSystem != null) this._coordinateSystem.standardToLocal(projected, projected); /* Return the projected coordinates */ return projected; } /* Geographic */ return new Coordinate(source.getX(), source.getY(), source.getZ()); } /* Get the transformation from the local datum to the WGS datum */ let localToWGS: Operation = (wgsTransformationIndex < 0) ? this.getTransformationToWGS() : this.getTransformationsToWGS().get(wgsTransformationIndex); // if (localToWGS==null) // { // /* We cannot transform */ // ASystem.assert(false,"No datum transformation from "+this+" to WGS"); // } /* Transform from the WGS datum to the local datum */ let localGeocentric: Coordinate = CRS.getWGS84_2D().toGeoCentric(source/*geographic*/); if (localToWGS != null) localToWGS.reverse(localGeocentric, localGeocentric); /* Does the transform work on the projected coordinates (like the OSTN02 grid correction)? */ if ((localToWGS != null) && localToWGS.getSourceCRS().isProjected()) { /* We already have the result */ return localGeocentric; } else { /* Convert from geocentric to local coordinates */ let local: Coordinate = this.fromGeoCentric(localGeocentric); /* Restore the original Z (is this allowed??) <ISSUE> */ local.setZ(source.getZ()); /* Return the local coordinates */ return local; } } /** * Convert from the WGS 84 (geographic 2D) coordinate system to this coordinate system. * @param source the coordinates in the WGS 84 coordinate system, where x is longitude(-180..+180), y is latitude(-90..+90) and z is height. * @return the coordinates in this CRS (the z height is the same as the WGS height). */ public fromWGS(source: Coordinate): Coordinate { return this.fromWGSi(source, -1); } /** * Check if another CRS is compatible with this one. * @param other the other CRS. * @return true if compatible. */ public isCompatible(other: CRS): boolean { /* Check the base parameters */ if (other._code == this._code) return true; if (other._type != this._type) return false; if (other._csCode != this._csCode) return false; /* Geographic? */ if (this.isGeoCentric() || this.isGeoGraphic()) { /* Same datum? */ if (Datum.areCompatible(other.getDatum(), this.getDatum()) == false) return false; /* We need the same transformation to WGS (check CRS 2039 for example: wgs compatible datum, but with geocentric translation to wgs) */ if (Operation.isCompatibleOperation(other.getTransformationToWGS(), this.getTransformationToWGS()) == false) return false; return true; } /* Projected? */ else if (this.isProjected()) { /* Same projection? */ if (Operation.isCompatibleOperation(other._projection, this._projection) == false) return false; /* Has base CRS? */ if (other._baseCRS == null || this._baseCRS == null) return false; /* Same base? */ return (other._baseCRS.isCompatible(this._baseCRS)); } /* Vertical? */ else if (this.isVertical()) { /* Same datum? */ if (Datum.areCompatible(other.getDatum(), this.getDatum()) == false) return false; return true; } /* Compound? */ else if (this.isCompound()) { /* Same components? */ if (CRS.areCompatible(other._horizontalComponent, this._horizontalComponent) == false) return false; if (CRS.areCompatible(other._verticalComponent, this._verticalComponent) == false) return false; return true; } /* Other */ else { return false; } } /** * Check if two CRSs are compatible. * @param crs1 the first CRS. * @param crs2 the second CRS. * @return true if compatible. */ public static areCompatible(crs1: CRS, crs2: CRS): boolean { if (crs1 == null) return (crs2 == null); if (crs2 == null) return false; return crs1.isCompatible(crs2); } /** * Get the text form of the CRS. * @return the text form of the CRS. */ public getTextForm(): string { return this._textForm; } /** * Set the text form of the CRS. * @param textForm the text form of the CRS. */ public setTextForm(textForm: string): void { this._textForm = textForm; } /** * Get the access time. * @return the access time. */ public getAccessTime(): float64 { return this._accessTime; } /** * Set the access time. * @param time the access time. */ public setAccessTime(time: float64): void { this._accessTime = time; } /** * The standard toString method. * @see Object#toString */ public toString(): string { return "[CRS:code=" + this._code + ",name='" + this._name + "',area=" + this._area + ",type='" + CRS.labelCRSType(this._type) + "',datum=" + this._datum + ",baseCRS=" + this._baseCRS + ",wgs-transform=" + (this._transformationToWGS != null) + "]"; } /** * Get the type of a CRS. * @param crsKind the type of CRS. * @return a parsed type. */ public static parseCRSType(crsKind: string): int32 { if (Strings.equalsIgnoreCase(crsKind, "compound")) return CRS.COMPOUND; if (Strings.equalsIgnoreCase(crsKind, "engineering")) return CRS.ENGINEERING; if (Strings.equalsIgnoreCase(crsKind, "geocentric")) return CRS.GEOCENTRIC; if (Strings.equalsIgnoreCase(crsKind, "geographic 2D")) return CRS.GEOGRAPHIC_2D; if (Strings.equalsIgnoreCase(crsKind, "geographic 3D")) return CRS.GEOGRAPHIC_3D; if (Strings.equalsIgnoreCase(crsKind, "projected")) return CRS.PROJECTED; if (Strings.equalsIgnoreCase(crsKind, "vertical")) return CRS.VERTICAL; ASystem.assert0(false, "CRS kind '" + crsKind + "' not found"); return 0; } /** * Get the label of a type of a CRS. * @param crsType the type of CRS. * @return a label. */ public static labelCRSType(crsType: int32): string { if (crsType == CRS.COMPOUND) return "compound"; if (crsType == CRS.ENGINEERING) return "engineering"; if (crsType == CRS.GEOCENTRIC) return "geocentric"; if (crsType == CRS.GEOGRAPHIC_2D) return "geographic 2D"; if (crsType == CRS.GEOGRAPHIC_3D) return "geographic 3D"; if (crsType == CRS.PROJECTED) return "projected"; if (crsType == CRS.VERTICAL) return "vertical"; ASystem.assert0(false, "CRS type '" + crsType + "' not found"); return null; } }
the_stack
import React, { useState, useContext } from "react"; import styled, { css, ThemeContext } from "styled-components"; import { Helmet } from "react-helmet"; import { Button, Card, CompanyCard, JobCard, ReviewCard, Checkbox, InputButtonCombo, Link, PageContainer, StarRating, Select, Text, TextArea, TextInput, Icon, IconName, Spinner, HeadingShimmer, ParagraphShimmer, } from "src/components"; import { useScrollTopOnMount } from "src/shared/hooks/useScrollTopOnMount"; import Section from "./components/Section"; /******************************************************************* * **Utility functions/constants** * *******************************************************************/ const inputOptions = [ { label: "Option 1", value: "option-1" }, { label: "Option 2", value: "option-2" }, { label: "Option 3", value: "option-3" }, { label: "Option 4", value: "option-4" }, { label: "Option 5", value: "option-5" }, { label: "Option 5", value: "option-5" }, { label: "Option 5", value: "option-5" }, { label: "Option 5", value: "option-5" }, { label: "Option 5", value: "option-5" }, { label: "Option 5", value: "option-5" }, { label: "Option 6", value: "option-6" }, ]; /******************************************************************* * **Styles** * *******************************************************************/ const landingCardStyles = css` width: 350px; height: 180px; `; const LandingCompanyCard = styled(CompanyCard)` ${landingCardStyles} `; const LandingJobCard = styled(JobCard)` ${landingCardStyles} `; const LandingReviewCard = styled(ReviewCard)` ${landingCardStyles} `; const SectionSpacer = styled.div` & > * { margin-right: 15px; } `; const DesignPageContainer = styled(PageContainer)` & > section { max-width: 45%; } `; const PaletteSquare = styled(Card)` width: 100px; height: 100px; margin-bottom: 10px; display: inline-flex; justify-content: center; align-items: center; ${({ theme, backgroundColor }) => backgroundColor === theme.color.backgroundPrimary && `border: 2px solid ${theme.color.textPrimary}`}; `; /******************************************************************* * **Component** * *******************************************************************/ const DesignSystemPage = () => { useScrollTopOnMount(); const [numvalue, setNumvalue] = useState(3); const [checkboxChecked, setChecked] = useState(false); const theme = useContext(ThemeContext); return ( <> <Helmet> <title>Design system • intern+</title> </Helmet> <DesignPageContainer id="design-system-page"> <Text variant="heading1" as="h1"> Design System </Text> <Section heading="Colors"> <SectionSpacer> {(Object.values(theme.color) as string[]).map((color: string) => ( <PaletteSquare backgroundColor={color} key={color}> <Text variant="subheading" color={ color === theme.color.textPrimary ? "white" : "textPrimary" } > {color} </Text> </PaletteSquare> ))} </SectionSpacer> </Section> <Section heading="Typeface"> <SectionSpacer> <span> <Text heading size={40} as="div"> Aa </Text> <Text heading size={20} as="div"> Samsung Sharp Sans </Text> </span> <span> <Text size={40} as="div"> Aa </Text> <Text size={20} as="div"> Roboto </Text> </span> </SectionSpacer> </Section> <Text variant="heading1" as="h1"> Components </Text> <Section heading="Text & Link"> <div> <Text variant="heading1" as="div"> Heading 1 </Text> <Text variant="heading2" as="div"> Heading 2 </Text> <Text variant="heading3" as="div"> Heading 3 </Text> <Text variant="heading4" as="div"> Heading 4 </Text> </div> <div> <Text variant="subheading" as="div"> Subheading </Text> <Text variant="body" as="div"> Body text </Text> <Text variant="body" italic color="burlywood" as="div"> I'm super extra colourful and italicized. </Text> <Link to="https://www.youtube.com/watch?v=dQw4w9WgXcQ" newTab> <Text variant="body">Here's a link.</Text> </Link> </div> </Section> <Section heading="Icon"> <SectionSpacer> <Icon name={IconName.EDIT} size={24} /> <Icon name={IconName.STAR_FILLED} size={24} /> <Icon name={IconName.X_SQUARE} size={24} /> <Icon name={IconName.X} size={24} /> </SectionSpacer> </Section> <Section heading="TextInput"> <TextInput color="backgroundSecondary" variant="body" /> <TextInput color="backgroundSecondary" placeholder="I have placeholder text." /> <TextInput color="backgroundSecondary" disabled placeholder="I'm a disabled input." /> <TextInput color="backgroundSecondary" variant="heading2" placeholder="I'm a big input." /> </Section> <Section> <Section heading="TextArea"> <TextArea color="backgroundSecondary" variant="body" placeholder="I can hold lots of text." /> </Section> <Section heading="Select"> <Select color="backgroundSecondary" variant="body" options={inputOptions} placeholder="Go ahead, pick something." /> </Section> </Section> <Section heading="Button"> <SectionSpacer> <Button color="backgroundSecondary"> <Text variant="body">Regular</Text> </Button> <Button color="#9e7fa3"> <Text variant="body" color="backgroundPrimary"> Colored </Text> </Button> <Button disabled color="backgroundSecondary"> <Text variant="body">Disabled</Text> </Button> </SectionSpacer> </Section> <Section heading="InputButtonCombo"> <InputButtonCombo value="some search value" buttonText="Search" onChange={() => {}} onEnterTrigger={() => alert("enter!")} /> </Section> <Section heading="Checkbox"> <SectionSpacer> <Checkbox checked={checkboxChecked} onChange={(e) => setChecked(e.target.checked)} > <Text variant="subheading">I agree to the terms.</Text> </Checkbox> <Checkbox disabled checked={true}> <Text variant="subheading">I'm a disabled checkbox.</Text> </Checkbox> </SectionSpacer> </Section> <Section heading="StarRating"> <SectionSpacer> <StarRating size={20} maxStars={8} value={numvalue} onChange={(stars: number) => setNumvalue(stars)} /> <StarRating readOnly size={26} maxStars={5} value={numvalue} onChange={(stars: number) => setNumvalue(stars)} /> </SectionSpacer> </Section> <Section heading="Card"> <Card backgroundColor="backgroundSecondary" onClick={() => alert("clicked card")} > <Text variant="heading3" as="div"> I'm a normal card. </Text> </Card> <LandingCompanyCard name="Company A" linkTo="https://www.youtube.com/watch?v=dQw4w9WgXcQ" avgRating={4.2} numRatings={130} /> <LandingJobCard heading="Technical Program Manager Intern - Storefronts Team" subheading="Seattle, Washington" avgRating={4.2} numRatings={22} minHourlySalary={32} maxHourlySalary={48} hourlySalaryCurrency="USD" backgroundColor="#11BBBD" linkTo="https://www.youtube.com/watch?v=dQw4w9WgXcQ" /> <LandingReviewCard heading="Anonymous" subheading="Feb 29, 2019" rating={4} linkTo="https://www.youtube.com/watch?v=dQw4w9WgXcQ" backgroundColor="#FFE0FC" > <Text variant="body"> A quickly changing company going through a lot of growth. When I was interning, teams were still being figured out, but working at such a company will provide a neat learning experience. A quickly changing company going through a lot of growth. When I was interning, teams were still being figured out, but working at such a company will provide a neat learning experience. </Text> </LandingReviewCard> </Section> <Section heading="Loading States"> <HeadingShimmer /> <ParagraphShimmer /> <Spinner /> </Section> </DesignPageContainer> </> ); }; export default DesignSystemPage;
the_stack
import { create as XMLBuilder } from 'xmlbuilder' // Options NS import { Options as OptionsNS } from './AMCPConnectionOptions' import CasparCGVersion = OptionsNS.CasparCGVersion /***/ export namespace Config { /***/ export namespace v2xx { /***/ export class CasparCGConfigVO { public channelGrid: boolean = false public flash: v2xx.Flash = new v2xx.Flash() public templateHosts: Array<v2xx.TemplateHost> = [] } /***/ export class Channel { public _type: string = 'channel' public videoMode: string = 'PAL' // @todo: literal public consumers: Array<Consumer> = [] public straightAlphaOutput: boolean = false public channelLayout: string = 'stereo' } /***/ export class Consumer { public _type: string } /***/ export class DecklinkConsumer extends Consumer { _type = 'decklink' public device: number = 1 public keyDevice: Number | null = null public embeddedAudio: boolean = false public channelLayout: string = 'stereo' public latency: string = 'normal' // @todo: literal public keyer: string = 'external' // @todo: literal public keyOnly: boolean = false public bufferDepth: number = 3 } /***/ export class BluefishConsumer extends Consumer { _type = 'bluefish' public device: number = 1 public embeddedAudio: boolean = false public channelLayout: string = 'stereo' public keyOnly: boolean = false } /***/ export class SystemAudioConsumer extends Consumer { _type = 'system-audio' } /***/ export class ScreenConsumer extends Consumer { _type = 'screen' public device: number = 1 // @todo: wrong default implemented in caspar, should be 0::: public aspectRatio: string = 'default' // @todo: literal public stretch: string = 'fill' // @todo: literal public windowed: boolean = true public keyOnly: boolean = false public autoDeinterlace: boolean = true public vsync: boolean = false public borderless: boolean = false } /***/ export class NewtekIvgaConsumer extends Consumer { _type = 'newtek-ivga' } /***/ export class Controller { public _type: string = 'tcp' public port: number | null = null public protocol: string = '' } /***/ export class Mixer { public blendModes: boolean = false public straightAlpha: boolean = false public mipmappingDefaultOn: boolean = false } /***/ export class OscClient { public _type: string = 'predefined-client' public address: string = '' public port: number | null = null } /***/ export class Thumbnails { public generateThumbnails: boolean = true public width: number = 256 public height: number = 144 public videoGrid: number = 2 public scanIntervalMillis: number = 5000 public generateDelayMillis: number = 2000 public mipmap: boolean = false public videoMode: string = '720p5000' // @todo: literal } /***/ export class Flash { bufferDepth: string | number = 'auto' } /***/ export class TemplateHost { public _type: string = 'template-host' public videoMode: string = '' // @todo: literal public filename: string = '' public width: number | null = null public height: number | null = null } /***/ export class Osc { public defaultPort: number = 6250 public predefinedClients: Array<OscClient> = [] } /***/ export const defaultAMCPController: v2xx.Controller = { _type: new v2xx.Controller()._type, port: 5250, protocol: 'AMCP' } } /***/ export namespace v207 { /***/ export class CasparCGConfigVO extends v2xx.CasparCGConfigVO { public _version: number public paths: v207.Paths = new v207.Paths() public channels: Array<v207.Channel> = [new v2xx.Channel()] public controllers: Array<v2xx.Controller> = [v2xx.defaultAMCPController] public mixer: v207.Mixer = new v207.Mixer() public logLevel: string = 'trace' // @todo: literal public autoDeinterlace: boolean = true public autoTranscode: boolean = true public pipelineTokens: number = 2 public thumbnails: v207.Thumbnails = new v207.Thumbnails() public osc: v2xx.Osc = new v2xx.Osc() public audio: v207.Audio = new v207.Audio() } /***/ export class Channel extends v2xx.Channel { public consumers: Array<v207.Consumer> = [] } /***/ export class Paths { mediaPath: string = 'media\\' logPath: string = 'log\\' dataPath: string = 'data\\' templatePath: string = 'templates\\' thumbnailsPath: string = 'thumbnails\\' } /***/ export class Consumer extends v2xx.Consumer { } /***/ export class DecklinkConsumer extends v2xx.DecklinkConsumer { public customAllocator: boolean = true } /***/ export class BluefishConsumer extends v2xx.BluefishConsumer { } /***/ export class SystemAudioConsumer extends v2xx.SystemAudioConsumer { } /***/ export class ScreenConsumer extends v2xx.ScreenConsumer { public name: string = 'Screen Consumer' } /***/ export class NewtekIvgaConsumer extends v2xx.NewtekIvgaConsumer { public channelLayout: string = 'stereo' public provideSync: boolean = true } /***/ export class FileConsumer extends v2xx.Consumer { _type = 'file' public path: string = '' public vcodec: string = 'libx264' public separateKey: boolean = false } /***/ export class StreamConsumer extends v2xx.Consumer { _type = 'stream' public path: string = '' public args: string = '' } /***/ export class Thumbnails extends v2xx.Thumbnails { } /***/ export class Mixer extends v2xx.Mixer { public chromaKey: boolean = false } /***/ export class Osc extends v2xx.Osc { } /***/ export class ChannelLayout { public _type: string = 'channel-layout' public name: string = '' public type: string = '' public numChannels: number | null = null public channels: string = '' } /***/ export class MixConfig { public _type: string = 'mix-config' public from: string = '' public to: string = '' public mix: string = '' public mappings: Array<string> = [] } /***/ export class Audio { public channelLayouts: Array<v207.ChannelLayout> = [] public mixConfigs: Array<v207.MixConfig> = [] } } /***/ export namespace v21x { export const defaultLOGController: v2xx.Controller = { _type: new v2xx.Controller()._type, port: 3250, protocol: 'LOG' } /***/ export class CasparCGConfigVO extends v2xx.CasparCGConfigVO { public _version: number public paths: v21x.Paths = new v21x.Paths() public channels: Array<v21x.Channel> = [new v2xx.Channel()] public controllers: Array<v2xx.Controller> = [v2xx.defaultAMCPController, v21x.defaultLOGController] public lockClearPhrase: string = 'secret' public mixer: v21x.Mixer = new v21x.Mixer() public logLevel: string = 'info' // @todo: literal public logCategories: string = 'communication' // @todo: literal or strongtype public forceDeinterlace: boolean = false public accelerator: string = 'auto' // @todo: literal public thumbnails: v21x.Thumbnails = new v21x.Thumbnails() public html: v21x.Html = new v21x.Html() public osc: v21x.Osc = new v21x.Osc() public audio: v21x.Audio = new v21x.Audio() } /***/ export class Channel extends v2xx.Channel { public consumers: Array<v21x.Consumer> = [] } /***/ export class Paths { mediaPath: string = 'media/' logPath: string = 'log/' dataPath: string = 'data/' templatePath: string = 'template/' thumbnailPath: string = 'thumbnail/' fontPath: string = 'font/' } /***/ export class Consumer extends v2xx.Consumer { } /***/ export class DecklinkConsumer extends v2xx.DecklinkConsumer { } /***/ export class BluefishConsumer extends v2xx.BluefishConsumer { } /***/ export class SystemAudioConsumer extends v2xx.SystemAudioConsumer { public channelLayout: string = 'stereo' public latency: number = 200 } /***/ export class ScreenConsumer extends v2xx.ScreenConsumer { public interactive: boolean = true } /***/ export class NewtekIvgaConsumer extends v2xx.NewtekIvgaConsumer { } /***/ export class FfmpegConsumer extends v2xx.Consumer { _type = 'ffmpeg' public path: string = '' public args: string = '' public separateKey: boolean = false public monoStreams: boolean = false } /***/ export class SynctoConsumer extends v2xx.Consumer { _type = 'syncto' public channelId: Number | null = null } /***/ export class Mixer extends v2xx.Mixer { } /***/ export class Thumbnails extends v2xx.Thumbnails { public mipmap: boolean = true } /***/ export class Html { remoteDebuggingPort: number | null = null } /***/ export class Osc extends v2xx.Osc { public disableSendToAmcpClients: boolean = false } /***/ export class ChannelLayout { public _type: string = 'channel-layout' public name: string = '' public type: string = '' public numChannels: number | null = null public channelOrder: string = '' } /***/ export class MixConfig { public _type: string = 'mix-config' public fromType: string = '' public toTypes: string = '' public mix: string = '' } /***/ export class Audio { public channelLayouts: Array<v21x.ChannelLayout> = [] public mixConfigs: Array<v21x.MixConfig> = [] } } /***/ export namespace Utils { export type factoryMembers = 'config' | 'channel' | 'decklink' | 'bluefish' | 'system-audio' | 'screen' | 'newtek-ivga' | 'ffmpeg' | 'file' | 'ffmpeg' | 'stream' | 'syncto' | 'tcp' | 'predefined-client' | 'template-host' | 'channel-layout' | 'mix-config' export type FactyoryTypes = v207.CasparCGConfigVO | v21x.CasparCGConfigVO | v2xx.Consumer | v2xx.Channel | v2xx.Controller | v2xx.OscClient | v2xx.TemplateHost | v207.ChannelLayout | v207.MixConfig | v21x.ChannelLayout | v21x.MixConfig | undefined export function configMemberFactory(version: CasparCGVersion, memberName: factoryMembers | string, initValues?: Object): FactyoryTypes { let member: FactyoryTypes = undefined switch (memberName) { case 'config': if (version < 2100) { member = new v207.CasparCGConfigVO() } else { member = new v21x.CasparCGConfigVO() } break case 'channel': if (version < 2100) { member = new v207.Channel() } else { member = new v21x.Channel() } break case 'decklink': if (version < 2100) { member = new v207.DecklinkConsumer() } else { member = new v21x.DecklinkConsumer() } break case 'bluefish': member = new v2xx.BluefishConsumer() break case 'system-audio': if (version < 2100) { member = new v207.SystemAudioConsumer() } else { member = new v21x.SystemAudioConsumer() } break case 'screen': if (version < 2100) { member = new v207.ScreenConsumer() } else { member = new v21x.ScreenConsumer() } break case 'newtek-ivga': if (version < 2100) { member = new v207.NewtekIvgaConsumer() } else { member = new v21x.NewtekIvgaConsumer() } break case 'ffmpeg': if (version > 2100) { member = new v21x.FfmpegConsumer() } break case 'file': if (version < 2100) { member = new v207.FileConsumer() } break case 'stream': if (version < 2100) { member = new v207.StreamConsumer() } break case 'syncto': if (version > 2100) { member = new v21x.SynctoConsumer() } break case 'tcp': member = new v2xx.Controller() break case 'predefined-client': member = new v2xx.OscClient() break case 'template-host': member = new v2xx.TemplateHost() break case 'channel-layout': if (version < 2100) { member = new v207.ChannelLayout() } else { member = new v21x.ChannelLayout() } break case 'mix-config': if (version < 2100) { member = new v207.MixConfig() } else { member = new v21x.MixConfig() } break } if (member && initValues) { for (let key in initValues) { if (member.hasOwnProperty(key)) { if (typeof (member as any)[key] === ((typeof (initValues as any)[key]) || undefined)) { (member as any)[key] = (initValues as any)[key] } } } } return member } } /***/ export namespace Intermediate { import Config207VO = v207.CasparCGConfigVO import Config210VO = v21x.CasparCGConfigVO /***/ export class Audio { public channelLayouts: Array<v21x.ChannelLayout> = [] public mixConfigs: Array<Intermediate.MixConfig> = [] } /***/ export class MixConfig { public _type: string = 'mix-config' public fromType: string = '' public toTypes: string = '' public mix: { mixType: string, destinations: { [destination: string]: Array<{ source: string, expression: string }> } } } /***/ export class Mixer extends v207.Mixer { chromaKey: boolean } /***/ export interface ICasparCGConfig { paths: v21x.Paths channels: Array<v2xx.Channel> controllers: Array<v2xx.Controller> lockClearPhrase: string | null mixer: Intermediate.Mixer logLevel: string logCategories: string channelGrid: boolean forceDeinterlace: boolean autoDeinterlace: boolean autoTranscode: boolean pipelineTokens: number accelerator: string thumbnails: v21x.Thumbnails flash: v2xx.Flash html: v21x.Html templateHosts: Array<v2xx.TemplateHost> osc: v2xx.Osc audio: Intermediate.Audio readonly VO: v207.CasparCGConfigVO | v21x.CasparCGConfigVO readonly vo: v207.CasparCGConfigVO | v21x.CasparCGConfigVO readonly v207VO: v207.CasparCGConfigVO readonly v210VO: v21x.CasparCGConfigVO readonly XML: Object | null readonly xml: Object | null readonly v207XML: Object readonly v210XML: Object readonly XMLString: string readonly v207XMLString: string readonly v210XMLString: string readonly _version: CasparCGVersion import(configVO: Object): void importFromV207VO(configVO: Object): void importFromV210VO(configVO: Object): void } /***/ export class CasparCGConfig implements ICasparCGConfig { public paths: v21x.Paths = new v21x.Paths() public channels: Array<v2xx.Channel> = [] public controllers: Array<v2xx.Controller> = [] public lockClearPhrase: string | null = null public mixer: Intermediate.Mixer = new Intermediate.Mixer() public logLevel: string = 'info' // @todo literal public logCategories: string = 'communication' // @todo literal public channelGrid: boolean = false public forceDeinterlace: boolean = false public autoDeinterlace: boolean = true public autoTranscode: boolean = true public pipelineTokens: number = 2 public accelerator: string = 'auto' // @todo literal public thumbnails: v21x.Thumbnails = new v21x.Thumbnails() public flash: v2xx.Flash = new v2xx.Flash() public html: v21x.Html = new v21x.Html() public templateHosts: Array<v2xx.TemplateHost> = [] public osc: v21x.Osc = new v21x.Osc() public audio: Intermediate.Audio = new Intermediate.Audio() // tslint:disable-next-line:variable-name private __version: CasparCGVersion /***/ public constructor(initVersionOrConfigVO: Config207VO | Config210VO | {} | CasparCGVersion) { // is a version if (typeof initVersionOrConfigVO === 'number') { if (initVersionOrConfigVO >= 2100) { this.__version = CasparCGVersion.V210 } else if (initVersionOrConfigVO === 2007) { this.__version = CasparCGVersion.V207 } return } // is initVO if (initVersionOrConfigVO) { if (initVersionOrConfigVO instanceof Config207VO) { this.__version = CasparCGVersion.V207 } else if (initVersionOrConfigVO instanceof Config210VO) { this.__version = CasparCGVersion.V210 } else if ((typeof initVersionOrConfigVO === 'object') && (initVersionOrConfigVO as any)['_version']) { if ((initVersionOrConfigVO as any)['_version'] >= 2100) { this.__version = CasparCGVersion.V210 } else if ((initVersionOrConfigVO as any)['_version'] >= 2007) { this.__version = CasparCGVersion.V207 } } this.import(initVersionOrConfigVO) } } /***/ static addFormattedXMLChildsFromObject(root: any, data: any, blacklist?: Array<string>): Object { blacklist && blacklist.push('arrayNo', 'array-no') for (let key in data) { if ((key === 'constructor') || (blacklist && blacklist.indexOf(key) > -1)) { continue } let value: string = data[key] key = CasparCGConfig.mixedCaseToDashed(key) root.ele.call(root, key, value) } return root } /***/ static addFormattedXMLChildsFromArray(root: any, data: any, whitelist?: Array<string>): Object { if (whitelist) { whitelist.forEach((key) => { if (data.hasOwnProperty(key)) { let value: string = data[key] let keyBlocks: Array<string> = key.split(/(?=[A-Z])/) key = keyBlocks.map((i) => i.toLowerCase()).join('-') root.ele.call(root, key, value) } }) } return root } /***/ static dashedToMixedCase(rawString: string): string { let keyBlocks: Array<string> = rawString.split(/-/) if (keyBlocks.length > 1) { return keyBlocks.map((i, o) => { if (o > 0) { i = i.toLowerCase() i = i.slice(0, 1).toUpperCase() + i.slice(1) } else { i = i.toLowerCase() } return i }).join('') } else { return rawString } } /***/ static dashedToCamelCase(rawString: string): string { let keyBlocks: Array<string> = rawString.split(/-/) if (keyBlocks.length > 1) { return keyBlocks.map((i) => { i = i.toLowerCase() i = i.slice(0, 1).toUpperCase() + i.slice(1) return i }).join('') } else { return rawString } } /***/ static mixedCaseToDashed(mixedCased: string): string { let keyBlocks: Array<string> = mixedCased.split(/(?=[A-Z])/) return keyBlocks.map((i) => i.toLowerCase()).join('-') } /***/ public import(configVO: any): void { let version = configVO._version || this._version if (version === CasparCGVersion.V207) { this.importFromV207VO(configVO) } else if (version === CasparCGVersion.V210) { this.importFromV210VO(configVO) } else { throw new Error(`Unsupported CasparCGVersion in 'configVO': {$version}`) } } /***/ public importFromV207VO(configVO: any): void { // root level this.importValues(configVO, this, ['log-level', 'channel-grid', 'auto-deinterlace', 'auto-transcode', 'pipeline-tokens']) // paths this.importValues(configVO.paths, this.paths, ['media-path', 'log-path', 'data-path', 'template-path', 'thumbnails-path']) // channels this.findListMembers(configVO, 'channels').forEach((i) => { let channel: v2xx.Channel = new v2xx.Channel() this.importValues(i, channel, ['video-mode', 'channel-layout', 'straight-alpha-output']) this.findListMembers(i, 'consumers').forEach((o: any) => { let consumerName: string = CasparCGConfig.dashedToCamelCase(o['_type']) + 'Consumer' this.importListMembers(o, consumerName, v21x) channel.consumers.push(o as v2xx.Consumer) }) this.channels.push(channel) }) // controllers this.findListMembers(configVO, 'controllers').forEach((i) => { let controller: v2xx.Controller = new v2xx.Controller() this.importAllValues(i, controller) this.controllers.push(controller) }) // mixer this.importValues(configVO.mixer, this.mixer, ['blend-modes', 'mipmapping-default-on', 'straight-alpha', 'chroma-key']) // templatehosts this.findListMembers(configVO, 'template-hosts').forEach((i) => { let templateHost: v2xx.TemplateHost = new v2xx.TemplateHost() this.importAllValues(i, templateHost) this.templateHosts.push(templateHost) }) // flash this.importValues(configVO.flash, this.flash, ['buffer-depth']) // thumbnails this.importValues(configVO.thumbnails, this.thumbnails, ['generate-thumbnails', 'width', 'height', 'video-grid', 'scan-interval-millis', 'generate-delay-millis', 'video-mode', 'mipmap']) // osc this.importValues(configVO.osc, this.osc, ['default-port']) this.findListMembers(configVO.osc, 'predefined-clients').forEach((i) => { let client: v2xx.OscClient = new v2xx.OscClient() this.importAllValues(i, client) this.osc.predefinedClients.push(client) }) // audio if (configVO.hasOwnProperty('audio')) { if (configVO['audio'].hasOwnProperty('channelLayouts')) { this.audio.channelLayouts = new Array<v21x.ChannelLayout>() configVO['audio']['channelLayouts'].forEach((i: v207.ChannelLayout) => { let channelLayout: v21x.ChannelLayout = new v21x.ChannelLayout() channelLayout._type = i._type channelLayout.channelOrder = i.channels channelLayout.name = i.name channelLayout.numChannels = i.numChannels channelLayout.type = i.type this.audio.channelLayouts.push(channelLayout) }) } if (configVO['audio'].hasOwnProperty('mixConfigs')) { this.audio.mixConfigs = new Array<Intermediate.MixConfig>() configVO['audio']['mixConfigs'].forEach((i: v207.MixConfig) => { let mixConfig: Intermediate.MixConfig = new Intermediate.MixConfig() mixConfig._type = i._type mixConfig.fromType = i.from mixConfig.toTypes = i.to mixConfig.mix = { mixType: i.mix, destinations: {} } // convert 2.0.x mix-config to 2.1.x let destinations: { [destination: string]: Array<{ source: string, expression: string }> } = {} let mapSections: RegExpMatchArray | null for (let o: number = 0; o < i.mappings.length; o++) { mapSections = i.mappings[o].match(/(\S+)\s+(\S+)\s+(\S+)/) if (mapSections !== null) { let src: string = mapSections[1] let dst: string = mapSections[2] let expr: string = mapSections[3] if (!destinations.hasOwnProperty(dst)) { destinations[dst] = [] } destinations[dst].push({ source: src, expression: expr }) } } mixConfig.mix.destinations = destinations this.audio.mixConfigs.push(mixConfig) }) } } } /***/ public importFromV210VO(configVO: any): void { // root level this.importValues(configVO, this, ['lockClear-phrase', 'log-level', 'log-categories', 'force-deinterlace', 'channel-grid', 'accelerator']) // paths this.importValues(configVO.paths, this.paths, ['media-path', 'log-path', 'data-path', 'template-path', 'thumbnail-path', 'font-path']) // channels this.findListMembers(configVO, 'channels').forEach((i) => { let channel: v2xx.Channel = new v2xx.Channel() this.importValues(i, channel, ['video-mode', 'channel-layout', 'straight-alpha-output']) this.findListMembers(i, 'consumers').forEach((o: any) => { let consumerName: string = CasparCGConfig.dashedToCamelCase(o['_type']) + 'Consumer' this.importListMembers(o, consumerName, v21x) channel.consumers.push(o as v2xx.Consumer) }) this.channels.push(channel) }) // controllers this.findListMembers(configVO, 'controllers').forEach((i) => { let controller: v2xx.Controller = new v2xx.Controller() this.importAllValues(i, controller) this.controllers.push(controller) }) // mixer this.importValues(configVO['mixer'], this.mixer, ['blend-modes', 'mipmapping-default-on', 'straight-alpha']) // templatehosts this.findListMembers(configVO, 'template-hosts').forEach((i) => { let templateHost: v2xx.TemplateHost = new v2xx.TemplateHost() this.importAllValues(i, templateHost) this.templateHosts.push(templateHost) }) // flash this.importValues(configVO.flash, this.flash, ['buffer-depth']) // html this.importValues(configVO.html, this.html, ['remote-debugging-port']) // thumbnails this.importValues(configVO.thumbnails, this.thumbnails, ['generate-thumbnails', 'width', 'height', 'video-grid', 'scan-interval-millis', 'generate-delay-millis', 'video-mode', 'mipmap']) // osc this.importValues(configVO.osc, this.osc, ['default-port', 'disable-send-to-amcp-clients']) this.findListMembers(configVO.osc, 'predefined-clients').forEach((i) => { let client: v2xx.OscClient = new v2xx.OscClient() this.importAllValues(i, client) this.osc.predefinedClients.push(client) }) // audio if (configVO.hasOwnProperty('audio')) { if (configVO['audio'].hasOwnProperty('channelLayouts')) { this.audio.channelLayouts = configVO['audio']['channelLayouts'] } if (configVO['audio'].hasOwnProperty('mixConfigs')) { this.audio.mixConfigs = new Array<Intermediate.MixConfig>() configVO['audio']['mixConfigs'].forEach((i: v21x.MixConfig) => { let mixConfig: Intermediate.MixConfig = new Intermediate.MixConfig() mixConfig._type = i._type mixConfig.fromType = i.fromType mixConfig.toTypes = i.toTypes let destinations: { [destination: string]: Array<{ source: string, expression: string }> } = {} let mixType: string = i.mix.match(/\&lt\;|\</g) !== null ? 'average' : 'add' let src: string let dest: string let expr: string i.mix.split('|').map((i) => i.replace(/^\s*|\s*$/g, '')).forEach((o) => { let srcDstSplit = o.split(/\&lt\;|\<|\=/) dest = srcDstSplit[0].replace(/^\s*|\s*$/g, '') destinations[dest] = [] srcDstSplit[1].split('+').forEach((u) => { let exprSplit: Array<string> = u.split('*') if (exprSplit.length > 1) { expr = exprSplit[0].replace(/^\s*|\s*$/g, '') src = exprSplit[1].replace(/^\s*|\s*$/g, '') } else { src = exprSplit[0].replace(/^\s*|\s*$/g, '') expr = '1.0' } destinations[dest].push({ source: src, expression: expr }) }) }) mixConfig.mix = { mixType: mixType, destinations: destinations } this.audio.mixConfigs.push(mixConfig) }) } } } /***/ public get VO(): Config207VO | Config210VO { if (this._version === CasparCGVersion.V207) { return this.v207VO } else if (this._version === CasparCGVersion.V210) { return this.v210VO } throw new Error('@todo') // @todo: throw } /***/ public get vo(): Config207VO | Config210VO { return this.VO } /***/ public get v207VO(): Config207VO { // let configVO: Config207VO = {}; let configVO: Config207VO = new Config207VO() configVO._version = this._version // paths configVO.paths = new v207.Paths() configVO.paths.dataPath = this.paths.dataPath configVO.paths.logPath = this.paths.logPath configVO.paths.mediaPath = this.paths.mediaPath configVO.paths.templatePath = this.paths.templatePath configVO.paths.thumbnailsPath = this.paths.thumbnailPath // channels configVO.channels = this.channels // controllers configVO.controllers = this.controllers // single values on root configVO.logLevel = this.logLevel configVO.autoDeinterlace = this.autoDeinterlace configVO.autoTranscode = this.autoTranscode configVO.pipelineTokens = this.pipelineTokens configVO.channelGrid = this.channelGrid // mixer configVO.mixer = new v207.Mixer() configVO.mixer.blendModes = this.mixer.blendModes if (this.mixer.chromaKey) configVO.mixer.chromaKey = this.mixer.chromaKey configVO.mixer.mipmappingDefaultOn = this.mixer.mipmappingDefaultOn configVO.mixer.straightAlpha = this.mixer.straightAlpha // flash configVO.flash = this.flash // template hosts configVO.templateHosts = this.templateHosts // thumbnails configVO.thumbnails = this.thumbnails // osc configVO.osc = new v2xx.Osc() if (this.osc.defaultPort) configVO.osc.defaultPort = this.osc.defaultPort if (this.osc.predefinedClients) configVO.osc.predefinedClients = this.osc.predefinedClients // audio configVO.audio = new v207.Audio() this.audio.channelLayouts.forEach((i) => { let channelLayout: v207.ChannelLayout = new v207.ChannelLayout() channelLayout.name = i.name channelLayout.numChannels = i.numChannels channelLayout.type = i.type channelLayout.channels = i.channelOrder configVO.audio.channelLayouts.push(channelLayout) }) this.audio.mixConfigs.forEach((i) => { let mixConfig: v207.MixConfig = new v207.MixConfig() mixConfig.from = i.fromType mixConfig.to = i.toTypes mixConfig.mix = i.mix.mixType for (let o in i.mix.destinations) { i.mix.destinations[o].forEach((u) => { mixConfig.mappings.push([u.source, o, u.expression].join(' ')) }) } configVO.audio.mixConfigs.push(mixConfig) }) return configVO } /***/ public get v210VO(): Config210VO { let configVO: Config210VO = new Config210VO() configVO._version = this._version // paths configVO.paths = this.paths // channels configVO.channels = this.channels // controllers configVO.controllers = this.controllers // single values on root if (typeof this.lockClearPhrase === 'string') configVO.lockClearPhrase = this.lockClearPhrase configVO.logLevel = this.logLevel configVO.logCategories = this.logCategories configVO.forceDeinterlace = this.forceDeinterlace configVO.channelGrid = this.channelGrid configVO.accelerator = this.accelerator // mixer configVO.mixer = new v21x.Mixer() configVO.mixer.blendModes = this.mixer.blendModes configVO.mixer.mipmappingDefaultOn = this.mixer.mipmappingDefaultOn configVO.mixer.straightAlpha = this.mixer.straightAlpha // flash configVO.flash = this.flash // html configVO.html = this.html // template hosts configVO.templateHosts = this.templateHosts // thumbnails configVO.thumbnails = this.thumbnails // osc configVO.osc = this.osc // audio configVO.audio = new v21x.Audio() configVO.audio.channelLayouts = this.audio.channelLayouts this.audio.mixConfigs.forEach((i) => { let mixConfig: v21x.MixConfig = new v21x.MixConfig() mixConfig.fromType = i.fromType mixConfig.toTypes = i.toTypes let mixOperator: string let destinationStrings: Array<string> = [] for (let o in i.mix.destinations) { let destinationSubStrings: Array<string> = [] let destinations = i.mix.destinations[o] mixOperator = (destinations.length > 1 && i.mix.mixType === 'average') ? '<' : '=' destinations.forEach((u) => { destinationSubStrings.push(u.expression === '1.0' ? u.source : u.expression + '*' + u.source) }) destinationStrings.push(o + ' ' + mixOperator + ' ' + destinationSubStrings.join(' + ')) } mixConfig.mix = destinationStrings.join(' | ') configVO.audio.mixConfigs.push(mixConfig) }) return configVO } /***/ public get XML(): Object | null { if (this._version === CasparCGVersion.V207) { return this.v207XML } else if (this._version === CasparCGVersion.V210) { return this.v210XML } return null // @todo: throw error } /***/ public get xml(): Object | null { return this.XML } /***/ public get v207XML(): any { let xml = XMLBuilder('configuration') // paths let paths: v207.Paths = new v207.Paths() paths.dataPath = this.paths.dataPath paths.logPath = this.paths.logPath paths.mediaPath = this.paths.mediaPath paths.templatePath = this.paths.templatePath paths.thumbnailsPath = this.paths.thumbnailPath CasparCGConfig.addFormattedXMLChildsFromObject(xml.ele('paths'), paths) // , ["mediaPath", "logPath", "dataPath", "templatesPath", "thumbnailPath"]); // channels let channels = xml.ele('channels') this.channels.forEach((i) => { let channel = channels.ele('channel') CasparCGConfig.addFormattedXMLChildsFromObject(channel, i, ['_type', 'consumers', '_consumers']) // consumer let consumers = channel.ele('consumers') i.consumers.forEach((i) => { let consumer = consumers.ele(i._type) CasparCGConfig.addFormattedXMLChildsFromObject(consumer, i, ['_type']) }) }) // controllers let controllers = xml.ele('controllers') this.controllers.forEach((i) => { let controller = controllers.ele(i._type) CasparCGConfig.addFormattedXMLChildsFromObject(controller, i, ['_type']) }) // all root-level single values CasparCGConfig.addFormattedXMLChildsFromArray(xml, this, ['logLevel', 'autoDeinterlace', 'autoTranscode', 'pipelineTokens', 'channelGrid']) // mixer if (this.mixer) { CasparCGConfig.addFormattedXMLChildsFromObject(xml.ele('mixer'), this.mixer) } // flash if (this.flash) { CasparCGConfig.addFormattedXMLChildsFromObject(xml.ele('flash'), this.flash) } // template hosts if (this.templateHosts && this.templateHosts.length > 0) { let templateHosts = xml.ele('template-hosts') this.templateHosts.forEach((i) => { let templatehost = templateHosts.ele(i._type) CasparCGConfig.addFormattedXMLChildsFromObject(templatehost, i, ['_type']) }) } // thumbnails if (this.thumbnails) { CasparCGConfig.addFormattedXMLChildsFromObject(xml.ele('thumbnails'), this.thumbnails) } // osc if (this.osc) { let osc = xml.ele('osc') osc.ele('default-port', this.osc.defaultPort) // predefined clients if (this.osc.predefinedClients && this.osc.predefinedClients.length > 0) { let predefinedClients = osc.ele('predefined-clients') this.osc.predefinedClients.forEach((i) => { // predefinedClients let client = predefinedClients.ele(i._type) CasparCGConfig.addFormattedXMLChildsFromObject(client, i, ['_type']) }) } } // audio if (this.audio && ((this.audio.channelLayouts && this.audio.channelLayouts.length > 0) || (this.audio.mixConfigs && this.audio.mixConfigs.length > 0))) { let audio = xml.ele('audio') if (this.audio.channelLayouts && this.audio.channelLayouts.length > 0) { let channelLayouts = audio.ele('channel-layouts') this.audio.channelLayouts.forEach((i) => { let channelLayout = channelLayouts.ele('channel-layout') if (i.name) channelLayout.att('name', i.name) if (i.type) channelLayout.att('type', i.type) if (i.numChannels) channelLayout.att('num-channels', i.numChannels) if (i.channelOrder) channelLayout.att('channels', i.channelOrder) }) } if (this.audio.mixConfigs && this.audio.mixConfigs.length > 0) { let mixConfigs = audio.ele('mix-configs') this.audio.mixConfigs.forEach((i) => { let mixConfig = mixConfigs.ele('mix-config') mixConfig.ele('from', i.fromType) mixConfig.ele('to', i.toTypes) mixConfig.ele('mix', i.mix.mixType) let mappings = mixConfig.ele('mappings') for (let o in i.mix.destinations) { let destination: Array<{ source: string, expression: string }> = i.mix.destinations[o] destination.forEach((u) => { mappings.ele('mapping', u.source + ' ' + o + ' ' + u.expression) }) } }) } } return xml } /***/ public get v210XML(): any { let xml = XMLBuilder('configuration') // paths CasparCGConfig.addFormattedXMLChildsFromObject(xml.ele('paths'), this.paths) // , ["mediaPath", "logPath", "dataPath", "templatePath", "thumbnailPath", "fontpath"]); // channels let channels = xml.ele('channels') this.channels.forEach((i) => { let channel = channels.ele('channel') CasparCGConfig.addFormattedXMLChildsFromObject(channel, i, ['_type', 'consumers', '_consumers']) // consumer let consumers = channel.ele('consumers') i.consumers.forEach((i) => { let consumer = consumers.ele(i._type) CasparCGConfig.addFormattedXMLChildsFromObject(consumer, i, ['_type']) }) }) // controllers let controllers = xml.ele('controllers') this.controllers.forEach((i) => { let controller = controllers.ele(i._type) CasparCGConfig.addFormattedXMLChildsFromObject(controller, i, ['_type']) }) // all root-level single values CasparCGConfig.addFormattedXMLChildsFromArray(xml, this, ['lockClearPhrase', 'logLevel', 'logCategories', 'forceDeinterlace', 'channelGrid', 'accelerator']) // mixer if (this.mixer) { let mixer = xml.ele('mixer') mixer.ele('blend-modes', this.mixer.blendModes) mixer.ele('mipmapping-default-on', this.mixer.mipmappingDefaultOn) mixer.ele('straight-alpha', this.mixer.straightAlpha) } // flash if (this.flash) { CasparCGConfig.addFormattedXMLChildsFromObject(xml.ele('flash'), this.flash) } // html if (this.html) { CasparCGConfig.addFormattedXMLChildsFromObject(xml.ele('html'), this.html) } // template hosts if (this.templateHosts && this.templateHosts.length > 0) { let templateHosts = xml.ele('template-hosts') this.templateHosts.forEach((i) => { let templatehost = templateHosts.ele(i._type) CasparCGConfig.addFormattedXMLChildsFromObject(templatehost, i, ['_type']) }) } // thumbnails if (this.thumbnails) { CasparCGConfig.addFormattedXMLChildsFromObject(xml.ele('thumbnails'), this.thumbnails) } // osc if (this.osc) { let osc = xml.ele('osc') CasparCGConfig.addFormattedXMLChildsFromArray(osc, this.osc, ['defaultPort', 'disableSendToAmcpClients']) // predefined clients if (this.osc.predefinedClients && this.osc.predefinedClients.length > 0) { let predefinedClients = osc.ele('predefined-clients') this.osc.predefinedClients.forEach((i) => { // predefinedClients let client = predefinedClients.ele(i._type) CasparCGConfig.addFormattedXMLChildsFromObject(client, i, ['_type']) }) } } // audio if (this.audio && ((this.audio.channelLayouts && this.audio.channelLayouts.length > 0) || (this.audio.mixConfigs && this.audio.mixConfigs.length > 0))) { let audio = xml.ele('audio') if (this.audio.channelLayouts && this.audio.channelLayouts.length > 0) { let channelLayouts = audio.ele('channel-layouts') this.audio.channelLayouts.forEach((i) => { let channelLayout = channelLayouts.ele('channel-layout') if (i.name) channelLayout.att('name', i.name) if (i.type) channelLayout.att('type', i.type) if (i.numChannels) channelLayout.att('num-channels', i.numChannels) if (i.channelOrder) channelLayout.att('channel-order', i.channelOrder) }) } if (this.audio.mixConfigs && this.audio.mixConfigs.length > 0) { let mixConfigs = audio.ele('mix-configs') this.audio.mixConfigs.forEach((i) => { let mixStrings: Array<string> = [] let mixOperator: string = i.mix.mixType === 'average' ? '<' : i.mix.mixType === 'add' ? '=' : '' let destination: Array<{ source: string, expression: string }> for (let o in i.mix.destinations) { destination = i.mix.destinations[o] if (destination.length > 1) { let subSourceStrings: Array<string> = [] destination.forEach((u) => { subSourceStrings.push(u.expression === '1.0' ? u.source : (u.expression.toString() + '*' + u.source)) }) mixStrings.push(o + ' ' + mixOperator + ' ' + subSourceStrings.join(' + ')) } else { mixStrings.push(o + ' = ' + (destination[0].expression === '1.0' ? destination[0].source : (destination[0].expression.toString() + '*' + destination[0].source))) } } mixConfigs.ele('mix-config') .att('from-type', i.fromType) .att('to-types', i.toTypes) .att('mix', mixStrings.join(' | ')) }) } } return xml } /***/ public get XMLString(): string { if (this._version === CasparCGVersion.V207) { return this.v207XMLString } else if (this._version === CasparCGVersion.V210) { return this.v210XMLString } return '' // @todo: throw error } /***/ public get v207XMLString(): string { return this.v207XML.end({ pretty: true }) } /***/ public get v210XMLString(): string { return this.v210XML.end({ pretty: true }) } /***/ public get _version(): CasparCGVersion { return this.__version } /***/ private importAllValues(sourceRoot: Object, destRoot: Object): void { let keys: Array<string> = [] for (let i in sourceRoot) { keys.push(i) } this.importValues(sourceRoot, destRoot, keys) } /***/ private importValues(sourceRoot: any, destRoot: any, values: Array<string>): void { values.forEach((dashedKey) => { let camelKey = CasparCGConfig.dashedToMixedCase(dashedKey) // sets value if key is valid if (sourceRoot && sourceRoot.hasOwnProperty(dashedKey) && sourceRoot[dashedKey] !== undefined && sourceRoot[dashedKey] !== null) { if (destRoot && destRoot.hasOwnProperty(camelKey)) { destRoot[camelKey] = sourceRoot[dashedKey] // @todo: type checking/reflection/cast?? } } else if (sourceRoot && sourceRoot.hasOwnProperty(camelKey) && sourceRoot[camelKey] !== undefined && sourceRoot[camelKey] !== null) { if (destRoot && destRoot.hasOwnProperty(camelKey)) { destRoot[camelKey] = sourceRoot[camelKey] // @todo: type checking/reflection/cast?? } } }) } /***/ private findListMembers(root: any, childKey: string): Array<Object> { let pairs: Array<Array<any>> = [] for (let i in root) { pairs.push([i, root[i]]) } childKey = CasparCGConfig.dashedToMixedCase(childKey) for (let i of pairs) { let outerKey: string = CasparCGConfig.dashedToMixedCase(i[0].toString()) let outerValue: any = i[1] // filter top-level possible arrays if (childKey === outerKey) { let flatArray: Array<Object> = [] for (let innerKey in outerValue) { let innerValue: any = outerValue[innerKey] if (typeof innerValue === 'object') { if (Array.isArray(innerValue)) { // multiple innervalues innerValue.forEach((o: any) => { if (typeof o !== 'object') { // "" string values, i.e. empty screen consumers o = {} } if (!o['_type']) { o['_type'] = innerKey } flatArray.push(o) }) } else { // single inner object if (!innerValue['_type']) { innerValue['_type'] = innerKey } flatArray.push(innerValue) } // update outer member with transformed array of inner members } else { flatArray.push({ _type: innerKey }) } } return flatArray } } return [] } /***/ private importListMembers(root: Object, memberName: string, restrictedNamespace?: Object) { let namespace: any | undefined if (restrictedNamespace) { namespace = restrictedNamespace } else { if ((v21x as any)[memberName]) { namespace = v2xx } else if ((v207 as any)[memberName]) { namespace = v207 } else if ((v2xx as any)[memberName]) { namespace = v2xx } } if (namespace && namespace.hasOwnProperty(memberName)) { let member: v2xx.Consumer = new namespace[memberName]() this.importAllValues(root, member) } } } } }
the_stack
import Flyout = require("../Controls/Flyout"); /** * Represents a command to be displayed in a Menu object. **/ export declare class MediaPlayer { //#region Constructors /** * Creates a new MenuCommand object. * @constructor * @param element The DOM element that hosts the MediaPlayer control. * @param options Each property of the options object corresponds to one of the control's properties or events. **/ constructor(element?: HTMLElement, options?: any); //#endregion Constructors //#region Methods /** * Adds a new timeline marker. * @param time The marker time. * @param type The marker type. * @param data The marker data. * @param extraClass An extra class that can be used to style the marker. **/ addMarker(time: number, type: string, data: any, extraClass: string): void; /** * Seeks to the previous chapter marker. **/ chapterSkipBack(): void; /** * Seeks to the next chapter marker. **/ chapterSkipForward(): void; /** * Disposes this control. **/ dispose(): void; /** * Increases the playback rate of the media. **/ fastForward(): void; /** * Navigates to the real-time position in live streamed media. **/ goToLive(): void; /** * Hides all the UI associated with the MediaPlayer. **/ hideControls(): void; /** * Plays the next track. **/ nextTrack(): void; /** * Pauses the media. **/ pause(): void; /** * Sets the playbackRate to the default playbackRate for the media and plays the media. **/ play(): void; /** * Plays the next track. **/ previousTrack(): void; /** * The time of the marker to remove. **/ removeMarker(): void; /** * Decreases the playbackRate of the media. **/ rewind(): void; /** * The position in seconds to seek to. **/ seek(): void; /** * Sets the metadata fields for the given peice of media. This method should be called before changing the video stream. * @param contentType The type of content that will be played by the mediaPlayer. * @param metadata A collection of name value pairs that provide additional information about the current media. **/ setContentMetadata(contentType: string, metadata: any): void; /** * Displays the UI associated with the MediaPlayer. **/ showControls(): void; /** * Stops the media. **/ stop(): void; /** * Moves the current timeline position backward by a short interval. **/ timeSkipBack(): void; /** * Moves the current timeline position forward short interval. **/ timeSkipForward(): void; //#endregion Properties //#region Properties /** * Gets a property that specifies whether the transport controls are visible. **/ controlsVisible: boolean; /** * The following property only exists to make it easier for app developers who created apps prior * to Windows 10 to migrate to Windows 10. Developers are recommended to use the above property instead. **/ isControlsVisible: boolean; /** * Gets or sets maximum playback position of the media. By default, the value is the duration of the media. **/ endTime: boolean; /** * The DOM element that hosts the MediaPlayer control. **/ element: HTMLElement; /** * Gets or sets a value indicating whether the MediaPlayer is using a layout that minimized space used, but only has room for a limited number of * commands or a layout that has room for a lot of commands, but takes up more space. **/ compact: boolean; /** * Gets or sets a value indicating whether the MediaPlayer is full screen. **/ fullScreen: boolean; /** * The following property only exists to make it easier for app developers who created apps prior * to Windows 10 to migrate to Windows 10. Developers are recommended to use the above property instead. **/ isFullScreen: boolean; /** * Gets or sets a value indicating whether to use thumbnails for fast forward, rewind and scrubbing. If true, the fast forward, rewind and scrub operations * will pause the mediaElement and cycle thumbnails as the user changes position. If false, the fast forward, rewind operations will increase or decrease * the mediaElement's playbackRate and the scrub operation will move the position. **/ thumbnailEnabled: boolean; /** * The following property is purposely not documented. It only exists to make it easier for app developers who created * apps prior to Windows 10 to migrate to Windows 10. The property forwards to the real property above. **/ isThumbnailEnabled: boolean; /** * Gets or sets the MediaPlayer's marker collection. **/ markers: any; /** * Gets or sets an interface that your application can implement to have more control over synchronization between * the MediaPlayer and your media. **/ mediaElementAdapter: any; /** * Gets or sets the playback mode, which specifies how many transport controls are shown. **/ layout: string; /** * Gets or sets minimum playback position of the media. By default the value is zero. **/ startTime: number; /** * Gets the current time as it is represented in the UI. While fast forwarding or rewinding, this property may be different than the video or audio * tag's 'currentTime' property. This is because during an fast forward or rewind operation, the media is paused while the timeline animates to * simulate a fast forward or rewind operation. **/ targetCurrentTime: number; /** * Gets the playbackRate as it is represented in the UI. While fast forwarding or rewinding, this property may be different than the video or audio * tag's 'playbackRate' property. This is because during an fast forward or rewind operation, the media is paused while the timeline animates to * simulate a fast forward or rewind operation. **/ targetPlaybackRate: number; /** * Gets or sets a function that converts raw time data from the video or audio tag into text to display in the UI of the MediaPlayer. **/ timeFormatter: any; /** * Sets the path to the current thumbnail image to display. **/ thumbnailImage: string; /** * Gets or sets whether the CAST button is visible. **/ castButtonVisible: boolean; /** * Gets or sets whether the cast button is enabled. **/ castButtonEnabled: boolean; /** * Gets or sets whether the chapter skip back button is visible. **/ chapterSkipBackButtonVisible: boolean; /** * Gets or sets whether the chapter skip back button is enabled. **/ chapterSkipBackButtonEnabled: boolean; /** * Gets or sets whether the chapter skip forward button is visible. **/ chapterSkipForwardButtonVisible: boolean; /** * Gets or sets whether the chapter skip forward button is enabled. **/ chapterSkipForwardButtonEnabled: boolean; /** * Gets or sets whether the fast forward button is visible. **/ fastForwardButtonVisible: boolean; /** * Gets or sets whether the fast forward button is enabled. **/ fastForwardButtonEnabled: boolean; /** * Gets or sets whether the full screen button is visible. **/ fullscreenButtonVisible: boolean; /** * Gets or sets whether the more button is enabled. **/ fullscreenButtonEnabled: boolean; /** * Gets or sets whether the LIVE button is visible. **/ goToLiveButtonVisible: boolean; /** * Gets or sets whether the LIVE button is enabled. **/ goToLiveButtonEnabled: boolean; /** * Gets or sets whether the next track button is visible. **/ nextTrackButtonVisible: boolean; /** * Gets or sets whether the next track button is enabled. **/ nextTrackButtonEnabled: boolean; /** * Gets or sets whether the play from beginning button is visible. **/ playFromBeginningButtonVisible: boolean; /** * Gets or sets whether the play from beginning button is enabled. **/ playFromBeginningButtonEnabled: boolean; /** * Gets or sets whether the play / pause button is visible. **/ playPauseButtonVisible: boolean; /** * Gets or sets whether the play / pause button is enabled. **/ playPauseButtonEnabled: boolean; /** * Gets or sets whether the playback rate button is visible. **/ playbackRateButtonVisible: boolean; /** * Gets or sets whether the playback rate button is enabled. **/ playbackRateButtonEnabled: boolean; /** * Gets or sets whether the previous track button is enabled. **/ previousTrackButtonEnabled: boolean; /** * Gets or sets whether the rewind button is visible. **/ rewindButtonVisible: boolean; /** * Gets or sets whether the rewind button is enabled. **/ rewindButtonEnabled: boolean; /** * Gets or sets whether the seek bar is visible. **/ seekBarVisible: boolean; /** * Gets or sets whether the seeking is enabled. **/ seekingEnabled: boolean; /** * Gets or sets whether the stop button is visible. **/ stopButtonVisible: boolean; /** * Gets or sets whether the stop button is enabled. **/ stopButtonEnabled: boolean; /** * Gets or sets whether the time skip back button is visible. **/ timeSkipBackButtonVisible: boolean; /** * Gets or sets whether the time skip back button is enabled. **/ timeSkipBackButtonEnabled: boolean; /** * Gets or sets whether the time skip forward button is visible. **/ timeSkipForwardButtonVisible: boolean; /** * Gets or sets whether the time skip forward button is enabled. **/ timeSkipForwardButtonEnabled: boolean; /** * Gets or sets whether the volume button is visible. **/ volumeButtonVisible: boolean; /** * Gets or sets whether the volume button is enabled. **/ volumeButtonEnabled: boolean; /** * Gets or sets whether the zoom button is visible. **/ zoomButtonVisible: boolean; /** * Gets or sets whether the zoom button is enabled. **/ zoomButtonEnabled: boolean; //#endregion Properties }
the_stack
'use strict'; const cors = require('cors'); const { debug, info, warn, error } = require('portal-env').Logger('portal-auth:utils'); const passwordValidator = require('portal-env').PasswordValidator; import * as wicked from 'wicked-sdk'; const crypto = require('crypto'); const url = require('url'); const fs = require('fs'); const path = require('path'); const request = require('request'); const qs = require('querystring'); import { failMessage, failError, failOAuth, makeError } from './utils-fail'; import { NameSpec, StringCallback, SimpleCallback, AuthRequest, AuthResponse, AuthSession } from './types'; import { OidcProfile, WickedApi, WickedPool, Callback, WickedUserShortInfo, WickedError, WickedPasswordStrategy, WickedGrant } from 'wicked-sdk'; export const utils = { app: null, init: function (app) { debug('init()'); utils.app = app; }, getUtc: function () { return Math.floor((new Date()).getTime() / 1000); }, createRandomId: function () { return crypto.randomBytes(20).toString('hex'); }, clone: function (o): object { // Ahem. return JSON.parse(JSON.stringify(o)); }, jsonError: function (res, message: string, status: number): void { debug('Error ' + status + ': ' + message); res.status(status).json({ message: message }); }, getJson: function (ob): any { if (typeof ob === "string") return JSON.parse(ob); return ob; }, getText: function (ob: any) { if (ob instanceof String || typeof ob === "string") return ob; return JSON.stringify(ob, null, 2); }, delay: async function (ms) { return new Promise(function (resolve) { setTimeout(() => { resolve(); }, ms); }); }, // https://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript parseBool: function (str: any): boolean { debug(`parseBool(${str})`); if (str == null) return false; if (typeof (str) === 'boolean') return (str === true); if (typeof (str) === 'string') { if (str == "") return false; str = str.replace(/^\s+|\s+$/g, ''); if (str.toLowerCase() == 'true' || str.toLowerCase() == 'yes') return true; str = str.replace(/,/g, '.'); str = str.replace(/^\s*\-\s*/g, '-'); } if (!isNaN(str)) return (parseFloat(str) != 0); return false; }, isPublic: function (uriName: string): boolean { return uriName.endsWith('jpg') || uriName.endsWith('jpeg') || uriName.endsWith('png') || uriName.endsWith('gif') || uriName.endsWith('css'); }, pipe: function (req, res, uri: string): void { let apiUrl = wicked.getInternalApiUrl(); if (!apiUrl.endsWith('/')) apiUrl += '/'; apiUrl += uri; request.get({ url: apiUrl, headers: { 'X-Authenticated-Scope': 'read_content' } }).pipe(res); }, getExternalUrl: function (): string { debug(`getExternalUrl()`); return utils.app.get('external_url'); }, splitName: function (fullName: string, username: string): NameSpec { debug('splitName(): fullName = ' + fullName + ', username = ' + username); var name = { firstName: '', lastName: fullName, fullName: fullName }; if (!fullName) { if (username) { name.lastName = ''; name.fullName = username; } else { name.lastName = ''; name.fullName = 'Unknown'; } } else { var spaceIndex = fullName.indexOf(' '); if (spaceIndex < 0) return name; name.firstName = fullName.substring(0, spaceIndex); name.lastName = fullName.substring(spaceIndex + 1); } debug(name); return name; }, makeFullName: function (familyName, givenName): string { if (familyName && givenName) return givenName + ' ' + familyName; if (familyName) return familyName; if (givenName) return givenName; return 'Unknown Username'; }, makeUsername: function (fullName, username): string { debug('makeUsername(): fullName = ' + fullName + ', username = ' + username); if (username) return username; return fullName; }, normalizeRedirectUri(s: string): string { let tmp = s; if (tmp.endsWith('/')) tmp = tmp.substring(0, s.length - 1); if (tmp.indexOf('?') >= 0) tmp = tmp.substring(0, tmp.indexOf('?')); return tmp; }, cors: function () { const optionsDelegate = (req, callback) => { const origin = req.header('Origin'); debug('in CORS options delegate. req.headers = '); debug(req.headers); if (isCorsHostValid(origin)) callback(null, _allowOptions); // Mirror origin, it's okay else callback(null, _denyOptions); }; return cors(optionsDelegate); }, _packageVersion: "", getVersion: function () { if (!utils._packageVersion) { const packageFile = path.join(__dirname, '..', '..', 'package.json'); if (fs.existsSync(packageFile)) { try { const packageInfo = JSON.parse(fs.readFileSync(packageFile, 'utf8')); if (packageInfo.version) utils._packageVersion = packageInfo.version; } catch (ex) { error(ex); } } if (!utils._packageVersion) // something went wrong utils._packageVersion = "0.0.0"; } return utils._packageVersion; }, _apiInfoMap: {} as { [apiId: string]: { success: boolean, data?: WickedApi } }, getApiInfo: function (apiId: string, callback: Callback<WickedApi>): void { debug(`getApiInfo(${apiId})`); if (utils._apiInfoMap[apiId] && utils._apiInfoMap[apiId].success) return callback(null, utils._apiInfoMap[apiId].data); wicked.getApi(apiId, (err, apiInfo) => { if (err) { utils._apiInfoMap[apiId] = { success: false }; return callback(err); } utils._apiInfoMap[apiId] = { data: apiInfo, success: true }; return callback(null, apiInfo); }); }, getApiInfoAsync: async function (apiId: string) { debug(`getApiInfo(${apiId})`); if (utils._apiInfoMap[apiId] && utils._apiInfoMap[apiId].success) return utils._apiInfoMap[apiId].data; try { const apiInfo = await wicked.getApi(apiId) as WickedApi utils._apiInfoMap[apiId] = { data: apiInfo, success: true }; return apiInfo; } catch (err) { utils._apiInfoMap[apiId] = { success: false }; throw (err); } }, getApiRegistrationPoolAsync: async (apiId: string): Promise<string> => { debug(`getApiRegistrationPoolAsync(${apiId})`); const apiInfo = await utils.getApiInfoAsync(apiId); let poolId = apiInfo.registrationPool; if (!poolId) debug(`API ${apiId} does not have a registration pool setting`); // Yes, poolId can be null or undefined here return poolId; }, getApiRegistrationPool: function (apiId: string, callback: StringCallback) { debug(`getApiRegistrationPool(${apiId})`); (async () => { try { const poolId = await this.getApiRegistrationPoolAsync(apiId); return callback(null, poolId); } catch (err) { return callback(err); } })(); }, _poolInfoMap: {} as { [poolId: string]: { success: boolean, data?: WickedPool } }, getPoolInfo: function (poolId: string, callback: Callback<WickedPool>): void { const instance = this; (async () => { try { const poolInfo = await instance.getPoolInfoAsync(poolId); return callback(null, poolInfo); } catch (err) { return callback(err); } })(); }, getPoolInfoAsync: async function (poolId: string): Promise<WickedPool> { debug(`getPoolInfo(${poolId})`); if (utils._poolInfoMap[poolId] && utils._poolInfoMap[poolId].success) return utils._poolInfoMap[poolId].data; try { const poolInfo = await wicked.getRegistrationPool(poolId); utils._poolInfoMap[poolId] = { data: poolInfo, success: true }; return poolInfo; } catch (err) { utils._poolInfoMap[poolId] = { success: false }; throw err; } }, getPoolInfoByApi: function (apiId: string, callback: Callback<WickedPool>) { debug(`getPoolInfoByApi(${apiId})`); utils.getApiRegistrationPool(apiId, (err, poolId) => { if (err) return callback(err); if (!poolId) return callback(makeError(`API ${apiId} does not have a registration pool`, 500)); utils.getPoolInfo(poolId, callback); }); }, verifyRecaptcha: function (req, callback) { if (req.app.glob.recaptcha && req.app.glob.recaptcha.useRecaptcha) { var secretKey = req.app.glob.recaptcha.secretKey; var recaptchaResponse = req.body['g-recaptcha-response']; request.post({ url: 'https://www.google.com/recaptcha/api/siteverify', formData: { secret: secretKey, response: recaptchaResponse } }, function (err, apiResponse, apiBody) { if (err) return callback(err); var recaptchaBody = utils.getJson(apiBody); if (!recaptchaBody.success) { return failMessage(401, 'ReCAPTCHA response invalid - Please try again', callback); } callback(null); }); } else { callback(null); } }, createVerificationRequest: function (trustUsers: boolean, authMethodId: string, email: string, callback: SimpleCallback) { debug(`createVerificationRequest(${authMethodId}, ${email})`); if (trustUsers) { debug('not creating verification requests, users are implicitly trusted'); return callback(null); } // Assemble the link to the verification page: // const globals = wicked.getGlobals(); const authUrl = utils.getExternalUrl(); const verificationLink = `${authUrl}/${authMethodId}/verify/{{id}}`; // Now we need to create a verification request with the wicked API (as the machine user) const verifBody = { type: 'email', email: email, link: verificationLink }; wicked.apiPost('/verifications', verifBody, null, callback); }, createViewModel: function (req, authMethodId: string, csrfSource?: string): any { if (!csrfSource) csrfSource = 'generic'; const csrfToken = `${csrfSource}-${utils.createRandomId()}`; req.session.csrfToken = csrfToken; return { title: req.app.glob.title, portalUrl: wicked.getExternalPortalUrl(), baseUrl: req.app.get('base_path'), csrfToken: csrfToken, loginUrl: `${authMethodId}/login`, logoutUrl: `logout`, signupUrl: `${authMethodId}/signup`, registerUrl: `${authMethodId}/register`, forgotPasswordUrl: `${authMethodId}/forgotpassword`, verifyEmailUrl: `${authMethodId}/verifyemail`, verifyPostUrl: `${authMethodId}/verify`, emailMissingUrl: `${authMethodId}/emailmissing`, grantUrl: `${authMethodId}/grant`, manageGrantsUrl: `${authMethodId}/grants`, selectNamespaceUrl: `${authMethodId}/selectnamespace`, recaptcha: req.app.glob.recaptcha, changePasswordUrl: `${authMethodId}/changepassword` }; }, getAndDeleteCsrfToken: function (req, csrfSource?: string): string { debug('getAndDeleteCsrfToken()'); if (!csrfSource) csrfSource = 'generic'; const csrfToken = req.session.csrfToken; delete req.session.csrfToken; if (!csrfToken || !csrfToken.startsWith(csrfSource)) { error(`getAndDeleteCsrfToken: Either no CSRF token is present, or the source mismatches: ${csrfToken} (source ${csrfSource})`) return "<invalid csrf source or csrf not present>"; } return csrfToken; }, hasSession(req, authMethodId: string): boolean { return req.session && req.session[authMethodId]; }, getSession(req, authMethodId: string): AuthSession { if (!req.session || !req.session[authMethodId]) throw new WickedError('Invalid session state, not using a browser?', 400); return req.session[authMethodId]; }, deleteSession(req, authMethodId): void { debug(`deleteSession(${authMethodId})`); if (!req.session || !req.session[authMethodId]) return; delete req.session[authMethodId]; }, hasAuthRequest: function (req, authMethodId: string): boolean { return (req.session && req.session[authMethodId] && req.session[authMethodId].authRequest); }, getAuthRequest: function (req, authMethodId: string): AuthRequest { if (!req.session || !req.session[authMethodId]) throw new WickedError('Invalid session state, not using a browser?', 400); return req.session[authMethodId].authRequest; }, setAuthRequest: function (req, authMethodId: string, authRequest: AuthRequest): void { if (!req.session || !req.session[authMethodId]) throw new WickedError('Invalid session state, not using a browser?', 400); req.session[authMethodId].authRequest = authRequest; }, getAuthResponse: function (req, authMethodId: string): AuthResponse { if (!req.session || !req.session[authMethodId]) throw new WickedError('Invalid session state, not using a browser?', 400); return req.session[authMethodId].authResponse; }, setAuthResponse: function (req, authMethodId: string, authResponse: AuthResponse): void { if (!req.session || !req.session[authMethodId]) throw new WickedError('Invalid session state, not using a browser?', 400); req.session[authMethodId].authResponse = authResponse; }, /** * Checks for a user by custom ID. * * @param {*} customId custom ID to check a user for; if there is a user * with this custom ID in the wicked database, the user will already have * an email address, and thus the IdP would not have to ask for one, in * case it doesn't provide one (e.g. Twitter). */ getUserByCustomId: async function (customId: string): Promise<WickedUserShortInfo> { debug(`getUserByCustomId(${customId})`); try { const shortInfoList = await wicked.getUserByCustomId(customId); // Now we should have the user ID here: if (!Array.isArray(shortInfoList) || shortInfoList.length <= 0 || !shortInfoList[0].id) throw new Error('getUserByCustomId: Get user short info by email did not return a user id'); return shortInfoList[0]; } catch (err) { if (err.statusCode == 404) { // Not found return null; } // Unexpected error throw err; } }, /** * Returns `true` if the user has an established session with the given `authMethodId`. The function * also checks whether the user has a "profile, which is required if the user is truly logged in. * * @param {*} req The incoming request * @param {*} authMethodId The auth method id this request applies to */ isLoggedIn: function (req, authMethodId: string): boolean { let isLoggedIn = false; if (req.session && req.session[authMethodId] && req.session[authMethodId].authResponse && req.session[authMethodId].authResponse.profile) isLoggedIn = true; debug(`isLoggedIn(${authMethodId}): ${isLoggedIn}`); return isLoggedIn; }, /** * Returns the associated user OIDC profile if the user is logged in; otherwise an Error is thrown. * * @param {*} req * @param {*} authMethodId */ getProfile: function (req, authMethodId: string): OidcProfile { if (!utils.isLoggedIn(req, authMethodId)) throw new Error('Cannot get profile if not logged in'); return utils.getAuthResponse(req, authMethodId).profile; }, /** * Makes sure a user is logged in, and then redirects back to the original URL as per * the given req object. */ loginAndRedirectBack: function (req, res, authMethodId: string): void { const thisUri = req.originalUrl; const redirectUri = `${req.app.get('base_path')}/${authMethodId}/login?redirect_uri=${qs.escape(thisUri)}`; return res.redirect(redirectUri); }, decodeBase64: function (s) { const decoded = Buffer.from(s, 'base64').toString(); // Verify it's really a base64 string const encoded = Buffer.from(decoded).toString('base64'); if (s !== encoded) throw new Error('Input string is not a valid base64 encoded string'); return decoded; }, render(req, res, template: string, viewModel, authRequest?: AuthRequest): void { if (process.env.ALLOW_RENDER_JSON) { const accept = req.get('accept'); if (accept && accept.toLowerCase() === 'application/json') { viewModel.would_be_html = true; viewModel.template = template; return res.json(viewModel); } } viewModel.app_name = viewModel.title; if (authRequest) { if (authRequest.app_name && authRequest.app_id && authRequest.app_id !== '__portal') viewModel.app_name = authRequest.app_name; if (authRequest.app_url) viewModel.portalUrl = authRequest.app_url; } viewModel.i18n = getI18n(req, template); debug(viewModel); res.render(template, viewModel); }, getUserGrantAsync: async function (userId: string, applicationId: string, apiId): Promise<WickedGrant> { try { const userGrant = await wicked.getUserGrant(userId, applicationId, apiId); return userGrant; } catch (err) { if (err.status === 404 || err.statusCode === 404) { return { grants: [] }; } throw err; } }, _gitLastCommit: null, getGitLastCommit() { if (!utils._gitLastCommit) { const lastCommitFile = path.join(__dirname, '..', '..', 'git_last_commit'); if (fs.existsSync(lastCommitFile)) utils._gitLastCommit = fs.readFileSync(lastCommitFile, 'utf8'); else utils._gitLastCommit = '(no last git commit found - running locally?)'; } return utils._gitLastCommit; }, _gitBranch: null, getGitBranch() { if (!utils._gitBranch) { const gitBranchFile = path.join(__dirname, '..', '..', 'git_branch'); if (fs.existsSync(gitBranchFile)) utils._gitBranch = fs.readFileSync(gitBranchFile, 'utf8'); else utils._gitBranch = '(unknown)'; } return utils._gitBranch; }, _buildDate: null, getBuildDate() { if (!utils._buildDate) { const buildDateFile = path.join(__dirname, '..', '..', 'build_date'); if (fs.existsSync(buildDateFile)) utils._buildDate = fs.readFileSync(buildDateFile, 'utf8'); else utils._buildDate = '(unknown build date)'; } return utils._buildDate; } }; let _globalI18n = {}; function loadGlobalI18n(desiredLanguage) { if (_globalI18n[desiredLanguage]) return _globalI18n[desiredLanguage]; const fileName = path.join(__dirname, '..', 'views', `password_validation.${desiredLanguage}.json`); const strategyName = wicked.getPasswordStrategy(); const passwordStrategy = passwordValidator.getStrategy(strategyName) as WickedPasswordStrategy; const i18n = JSON.parse(fs.readFileSync(fileName)); const translations = { password_rules: i18n[strategyName], password_regex: passwordStrategy.regex }; _globalI18n[desiredLanguage] = translations; return translations; } function mergeGlobalI18n(i18n, desiredLanguage) { const globalI18n = loadGlobalI18n(desiredLanguage); for (let k in globalI18n) i18n[k] = globalI18n[k]; } const _i18nMap = new Map<string, object>(); function getI18n(req, template: string): object { debug(`getI18n(${template})`); let desiredLanguage = req.acceptsLanguages('en', 'de'); if (!desiredLanguage) desiredLanguage = 'en'; const key = `${template}:${desiredLanguage}`; if (_i18nMap.has(key)) return _i18nMap.get(key); let i18nFile = path.join(__dirname, '..', 'views', `${template}.${desiredLanguage}.json`); if (!fs.existsSync(i18nFile)) i18nFile = path.join(__dirname, '..', 'views', `${template}.en.json`); if (!fs.existsSync(i18nFile)) { debug(`getI18n(): No translation file found for template ${template}.`); _i18nMap.set(key, {}); return {} } const i18n = JSON.parse(fs.readFileSync(i18nFile, 'utf8')); mergeGlobalI18n(i18n, desiredLanguage); console.log(`Template: ${template}`); console.log(i18n); _i18nMap.set(key, i18n); return i18n; } // ============================== // HELPER METHODS // ============================== const _validCorsHosts = {}; function storeRedirectUriForCors(uri) { debug('storeRedirectUriForCors() ' + uri); try { const parsedUri = url.parse(uri); const host = parsedUri.protocol + '//' + parsedUri.host; _validCorsHosts[host] = true; debug(_validCorsHosts); } catch (ex) { error('storeRedirectUriForCors() - Invalid URI: ' + uri); } } function isCorsHostValid(host) { debug('isCorsHostValid(): ' + host); if (_validCorsHosts[host]) { debug('Yes, ' + host + ' is valid.'); return true; } debug('*** ' + host + ' is not a valid CORS origin.'); return false; } const _allowOptions = { origin: true, credentials: true, allowedHeaders: [ 'Accept', 'Accept-Encoding', 'Connection', 'User-Agent', 'Content-Type', 'Cookie', 'Host', 'Origin', 'Referer' ] }; const _denyOptions = { origin: false }; // module.exports = utils;
the_stack
import { Serializer, Client, BeaconMessage, WalletClientOptions, LocalStorage, TransportType, BeaconRequestOutputMessage, BeaconResponseInputMessage, AppMetadata, PermissionInfo, TransportStatus, WalletP2PTransport, DisconnectMessage } from '../..' import { PermissionManager } from '../../managers/PermissionManager' import { AppMetadataManager } from '../../managers/AppMetadataManager' import { ConnectionContext } from '../../types/ConnectionContext' import { IncomingRequestInterceptor } from '../../interceptors/IncomingRequestInterceptor' import { OutgoingResponseInterceptor } from '../../interceptors/OutgoingResponseInterceptor' import { BeaconRequestMessage } from '../../types/beacon/BeaconRequestMessage' import { BeaconMessageType } from '../../types/beacon/BeaconMessageType' import { AcknowledgeResponseInput } from '../../types/beacon/messages/BeaconResponseInputMessage' import { getSenderId } from '../../utils/get-sender-id' import { ExtendedP2PPairingResponse } from '../../types/P2PPairingResponse' import { ExposedPromise } from '../../utils/exposed-promise' import { ExtendedPeerInfo, PeerInfo } from '../../types/PeerInfo' import { Logger } from '../../utils/Logger' const logger = new Logger('WalletClient') /** * @publicapi * * The WalletClient has to be used in the wallet. It handles all the logic related to connecting to beacon-compatible * dapps and handling/responding to requests. * * @category Wallet */ export class WalletClient extends Client { /** * Returns whether or not the transport is connected */ protected readonly _isConnected: ExposedPromise<boolean> = new ExposedPromise() public get isConnected(): Promise<boolean> { return this._isConnected.promise } private readonly permissionManager: PermissionManager private readonly appMetadataManager: AppMetadataManager /** * This array stores pending requests, meaning requests we received and have not yet handled / sent a response. */ private pendingRequests: [BeaconRequestMessage, ConnectionContext][] = [] constructor(config: WalletClientOptions) { super({ storage: new LocalStorage(), ...config }) this.permissionManager = new PermissionManager(new LocalStorage()) this.appMetadataManager = new AppMetadataManager(new LocalStorage()) } public async init(): Promise<TransportType> { const keyPair = await this.keyPair // We wait for keypair here so the P2P Transport creation is not delayed and causing issues const p2pTransport = new WalletP2PTransport( this.name, keyPair, this.storage, this.matrixNodes, this.iconUrl, this.appUrl ) return super.init(p2pTransport) } /** * This method initiates a connection to the P2P network and registers a callback that will be called * whenever a message is received. * * @param newMessageCallback The callback that will be invoked for every message the transport receives. */ public async connect( newMessageCallback: ( message: BeaconRequestOutputMessage, connectionContext: ConnectionContext ) => void ): Promise<void> { this.handleResponse = async ( message: BeaconRequestMessage | DisconnectMessage, connectionContext: ConnectionContext ): Promise<void> => { if (message.type === BeaconMessageType.Disconnect) { const transport = await this.transport const peers: ExtendedPeerInfo[] = await transport.getPeers() const peer: ExtendedPeerInfo | undefined = peers.find( (peerEl) => peerEl.senderId === message.senderId ) if (peer) { await this.removePeer(peer as any) } return } if (!this.pendingRequests.some((request) => request[0].id === message.id)) { this.pendingRequests.push([message, connectionContext]) if (message.version !== '1') { await this.sendAcknowledgeResponse(message, connectionContext) } await IncomingRequestInterceptor.intercept({ message, connectionInfo: connectionContext, appMetadataManager: this.appMetadataManager, interceptorCallback: newMessageCallback }) } } return this._connect() } /** * The method will attempt to initiate a connection using the active transport. */ public async _connect(): Promise<void> { const transport: WalletP2PTransport = (await this.transport) as WalletP2PTransport if (transport.connectionStatus === TransportStatus.NOT_CONNECTED) { await transport.connect() transport .addListener(async (message: unknown, connectionInfo: ConnectionContext) => { if (typeof message === 'string') { const deserializedMessage = (await new Serializer().deserialize( message )) as BeaconRequestMessage this.handleResponse(deserializedMessage, connectionInfo) } }) .catch((error) => logger.log('_connect', error)) this._isConnected.resolve(true) } else { // NO-OP } } /** * This method sends a response for a specific request back to the DApp * * @param message The BeaconResponseMessage that will be sent back to the DApp */ public async respond(message: BeaconResponseInputMessage): Promise<void> { const request = this.pendingRequests.find( (pendingRequest) => pendingRequest[0].id === message.id ) if (!request) { throw new Error('No matching request found!') } this.pendingRequests = this.pendingRequests.filter( (pendingRequest) => pendingRequest[0].id !== message.id ) await OutgoingResponseInterceptor.intercept({ senderId: await getSenderId(await this.beaconId), request: request[0], message, ownAppMetadata: await this.getOwnAppMetadata(), permissionManager: this.permissionManager, appMetadataManager: this.appMetadataManager, interceptorCallback: async (response: BeaconMessage): Promise<void> => { await this.respondToMessage(response, request[1]) } }) } public async getAppMetadataList(): Promise<AppMetadata[]> { return this.appMetadataManager.getAppMetadataList() } public async getAppMetadata(senderId: string): Promise<AppMetadata | undefined> { return this.appMetadataManager.getAppMetadata(senderId) } public async removeAppMetadata(senderId: string): Promise<void> { return this.appMetadataManager.removeAppMetadata(senderId) } public async removeAllAppMetadata(): Promise<void> { return this.appMetadataManager.removeAllAppMetadata() } public async getPermissions(): Promise<PermissionInfo[]> { return this.permissionManager.getPermissions() } public async getPermission(accountIdentifier: string): Promise<PermissionInfo | undefined> { return this.permissionManager.getPermission(accountIdentifier) } public async removePermission(accountIdentifier: string): Promise<void> { return this.permissionManager.removePermission(accountIdentifier) } public async removeAllPermissions(): Promise<void> { return this.permissionManager.removeAllPermissions() } /** * Add a new peer to the known peers * @param peer The new peer to add */ public async addPeer(peer: PeerInfo, sendPairingResponse: boolean = true): Promise<void> { const extendedPeer: ExtendedPeerInfo = { ...peer, senderId: await getSenderId(peer.publicKey) } return (await this.transport).addPeer(extendedPeer, sendPairingResponse) } public async removePeer( peer: ExtendedP2PPairingResponse, sendDisconnectToPeer: boolean = false ): Promise<void> { const removePeerResult = (await this.transport).removePeer(peer) await this.removePermissionsForPeers([peer]) if (sendDisconnectToPeer) { await this.sendDisconnectToPeer(peer) } return removePeerResult } public async removeAllPeers(sendDisconnectToPeers: boolean = false): Promise<void> { const peers: ExtendedP2PPairingResponse[] = await (await this.transport).getPeers() const removePeerResult = (await this.transport).removeAllPeers() await this.removePermissionsForPeers(peers) if (sendDisconnectToPeers) { const disconnectPromises = peers.map((peer) => this.sendDisconnectToPeer(peer)) await Promise.all(disconnectPromises) } return removePeerResult } private async removePermissionsForPeers( peersToRemove: ExtendedP2PPairingResponse[] ): Promise<void> { const permissions = await this.permissionManager.getPermissions() const peerIdsToRemove = peersToRemove.map((peer) => peer.senderId) // Remove all permissions with origin of the specified peer const permissionsToRemove = permissions.filter((permission) => peerIdsToRemove.includes(permission.appMetadata.senderId) ) const permissionIdentifiersToRemove = permissionsToRemove.map( (permissionInfo) => permissionInfo.accountIdentifier ) await this.permissionManager.removePermissions(permissionIdentifiersToRemove) } /** * Send an acknowledge message back to the sender * * @param message The message that was received */ private async sendAcknowledgeResponse( request: BeaconRequestMessage, connectionContext: ConnectionContext ): Promise<void> { // Acknowledge the message const acknowledgeResponse: AcknowledgeResponseInput = { id: request.id, type: BeaconMessageType.Acknowledge } await OutgoingResponseInterceptor.intercept({ senderId: await getSenderId(await this.beaconId), request, message: acknowledgeResponse, ownAppMetadata: await this.getOwnAppMetadata(), permissionManager: this.permissionManager, appMetadataManager: this.appMetadataManager, interceptorCallback: async (response: BeaconMessage): Promise<void> => { await this.respondToMessage(response, connectionContext) } }) } /** * An internal method to send a BeaconMessage to the DApp * * @param response Send a message back to the DApp */ private async respondToMessage( response: BeaconMessage, connectionContext: ConnectionContext ): Promise<void> { const serializedMessage: string = await new Serializer().serialize(response) if (connectionContext) { const peerInfos = await this.getPeers() const peer = peerInfos.find((peerInfo) => peerInfo.publicKey === connectionContext.id) await (await this.transport).send(serializedMessage, peer) } else { await (await this.transport).send(serializedMessage) } } }
the_stack
import BigNumber from 'bignumber.js'; import { EventEmitter } from 'events'; import { ClientRuntimeError, NotCampaigningError } from './errors'; import { Lease } from './lease'; import { Namespace } from './namespace'; import { IKeyValue } from './rpc'; import { getDeferred, IDeferred, toBuffer } from './util'; const UnsetCurrent = Symbol('unset'); /** * Object returned from election.observer() that exposees information about * the current election. * @noInheritDoc */ export class ElectionObserver extends EventEmitter { /** * Gets whether the election has any leader. */ public get hasLeader() { return !!this.current; } private running = true; private runLoop: Promise<void>; private disposer?: () => void; private current: IKeyValue | typeof UnsetCurrent | undefined = UnsetCurrent; constructor(private readonly namespace: Namespace) { super(); this.runLoop = this.loop().catch(err => { this.emit('error', err); }); } /** * change is fired when the elected value changes. It can be fired with * undefined if there's no longer a leader. */ public on(event: 'change', handler: (value: string | undefined) => void): this; /** * disconnected is fired when the underlying watcher is disconnected. Etcd3 * will automatically attempt to reconnect in the background. This has the * same semantics as the `disconnected` event on the {@link Watcher}. */ public on(event: 'disconnected', handler: (value: Error) => void): this; /** * error is fired if the underlying election watcher * experiences an unrecoverable error. */ public on(event: 'error', handler: (value: Error) => void): this; /** * Implements EventEmitter.on(...). */ public on(event: string, handler: (...args: any[]) => void): this { return super.on(event, handler); } /** * Closes the election observer. */ public async cancel() { this.running = false; this.disposer?.(); await this.runLoop; } /** * Returns the currently-elected leader value (passed to `campaign()` or * `proclaim()`), or undefined if there's no elected leader. */ public leader(encoding?: BufferEncoding): string | undefined; /** * Returns the currently-elected leader value (passed to `campaign()` or * `proclaim()`), or undefined if there's no elected leader. */ public leader(encoding: 'buffer'): Buffer | undefined; public leader(encoding: BufferEncoding | 'buffer' = 'utf-8') { const leader = this.current; if (!leader || leader === UnsetCurrent) { return undefined; } return encoding === 'buffer' ? leader.value : leader.value.toString(encoding); } private setLeader(kv: IKeyValue | undefined) { const prev = this.current; this.current = kv; if (prev === UnsetCurrent) { this.emit('change', undefined); } else if (kv === undefined) { if (prev !== undefined) { this.emit('change', undefined); } } else if (!prev || !kv.value.equals(prev.value)) { this.emit('change', kv.value.toString()); } } private async loop() { // @see https://github.com/etcd-io/etcd/blob/28d1af294e4394df1ed967a4ac4fbaf437be3463/client/v3/concurrency/election.go#L177 while (this.running) { const allKeys = await this.namespace.getAll().sort('Create', 'Ascend').limit(1).exec(); let leader: IKeyValue | undefined = allKeys.kvs[0]; let revision = allKeys.header.revision; if (!this.running) { return; // if closed when doing async work } if (!leader) { this.setLeader(undefined); const watcher = this.namespace .watch() .startRevision(allKeys.header.revision) .prefix('') .only('put') .watcher(); await new Promise<void>((resolve, reject) => { watcher.on('data', data => { let done = false; for (const event of data.events) { if (event.type === 'Put') { leader = event.kv; revision = event.kv.mod_revision; done = true; } } if (done) { resolve(); } }); watcher.on('error', reject); this.disposer = resolve; }).finally(() => watcher.cancel()); if (!this.running) { return; // if closed when doing async work } } if (!leader) { throw new ClientRuntimeError('unreachable lack of election leader'); } this.setLeader(leader); const watcher = this.namespace .watch() .startRevision(new BigNumber(revision).plus(1).toString()) .key(leader.key) .watcher(); await new Promise<void>((resolve, reject) => { watcher!.on('put', kv => this.setLeader(kv)); watcher!.on('delete', () => resolve()); watcher!.on('error', reject); this.disposer = () => { resolve(); return watcher.cancel(); }; }).finally(() => watcher.cancel()); } } } const ResignedCampaign = Symbol('ResignedCampaign'); /** * A Campaign is returned from {@link Election.campaign}. See the docs on that * method for an example. * @noInheritDoc */ export class Campaign extends EventEmitter { private lease: Lease; private keyRevision?: string | typeof ResignedCampaign; private value: Buffer; private pendingProclaimation?: IDeferred<void>; constructor(private readonly namespace: Namespace, value: string | Buffer, ttl: number) { super(); this.value = toBuffer(value); this.lease = this.namespace.lease(ttl); this.lease.on('lost', err => this.emit('error', err)); this.start().catch(error => { this.resign().catch(() => undefined); this.pendingProclaimation?.reject(error); this.emit('error', error); }); } /** * elected is fired when the current instance becomes the leader. */ public on(event: 'elected', handler: () => void): this; /** * error is fired if the underlying lease experiences an error. When this * is emitted, the campaign has failed. You should handle this and create * a new campaign if appropriate. */ public on(event: 'error', handler: (error: Error) => void): this; /** * Implements EventEmitter.on(...). */ public on(event: string, handler: (...args: any[]) => void): this { return super.on(event, handler); } /** * Helper function that returns a promise when the node becomes the leader. * If `resign()` is called before this happens, the promise never resolves. * If an error is emitted, the promise is rejected. */ public wait() { return new Promise<this>((resolve, reject) => { this.on('elected', () => resolve(this)); this.on('error', reject); }); } /** * Updates the value announced by this candidate (without starting a new * election). If this candidate is currently the leader, then the change * will be seen on other consumers as well. * * @throws NotCampaigningError if the instance is no longer campaigning */ public async proclaim(value: string | Buffer) { if (this.keyRevision === ResignedCampaign) { throw new NotCampaigningError(); } const buf = toBuffer(value); if (buf.equals(this.value)) { return Promise.resolve(); } return this.proclaimInner(buf, this.keyRevision); } /** * Gets the etcd key in which the proclaimed value is stored. This is derived * from the underlying lease, and thus may throw if the lease was not granted * successfully. */ public async getCampaignKey() { const leaseId = await this.lease.grant(); return this.namespace.prefix.toString() + leaseId; } /** * Resigns from the campaign. A new leader is elected if this instance was * formerly the leader. */ public async resign() { if (this.keyRevision !== ResignedCampaign) { this.keyRevision = ResignedCampaign; await this.lease.revoke(); } } private async start() { const leaseId = await this.lease.grant(); const originalValue = this.value; const result = await this.namespace .if(leaseId, 'Create', '==', 0) .then(this.namespace.put(leaseId).value(originalValue).lease(leaseId)) .else(this.namespace.get(leaseId)) .commit(); if (this.keyRevision === ResignedCampaign) { return; // torn down in the meantime } this.keyRevision = result.header.revision; if (result.succeeded) { if (this.pendingProclaimation) { await this.proclaimInner(this.value, this.keyRevision); this.pendingProclaimation.resolve(); } } else { const kv = result.responses[0].response_range.kvs[0]; this.keyRevision = kv.create_revision; if (!kv.value.equals(this.value)) { await this.proclaimInner(this.value, this.keyRevision); this.pendingProclaimation?.resolve(); } } await this.waitForElected(result.header.revision); this.emit('elected'); } private async proclaimInner(buf: Buffer, keyRevision: string | undefined) { if (!keyRevision) { this.pendingProclaimation = this.pendingProclaimation ?? getDeferred(); this.value = buf; return this.pendingProclaimation.promise; } const leaseId = await this.lease.grant(); const r = await this.namespace .if(leaseId, 'Create', '==', keyRevision) .then(this.namespace.put(leaseId).value(buf).lease(leaseId)) .commit(); this.value = buf; if (!r.succeeded) { this.resign().catch(() => undefined); throw new NotCampaigningError(); } } private async waitForElected(revision: string) { // find last created before this one const lastRevision = new BigNumber(revision).minus(1).toString(); const result = await this.namespace .getAll() .maxCreateRevision(lastRevision) .sort('Create', 'Descend') .limit(1) .exec(); // wait for all older keys to be deleted for us to become the leader await waitForDeletes( this.namespace, result.kvs.map(k => k.key), ); } } /** * Implementation of elections, as seen in etcd's Go client. Elections are * most commonly used if you need a single server in charge of a certain task; * you run an election on every server where your program is running, and * among them they will choose one "leader". * * There are two main entrypoints: campaigning via {@link Election.campaign}, * and observing the leader via {@link Election.observe}. * * @see https://github.com/etcd-io/etcd/blob/master/client/v3/concurrency/election.go * * @example * * ```js * const os = require('os'); * const client = new Etcd3(); * const election = client.election('singleton-job'); * * function runCampaign() { * const campaign = election.campaign(os.hostname()) * campaign.on('elected', () => { * // This server is now the leader! Let's start doing work * doSomeWork(); * }); * campaign.on('error', error => { * // An error happened that caused our campaign to fail. If we were the * // leader, make sure to stop doing work (another server is the leader * // now) and create a new campaign. * console.error(error); * stopDoingWork(); * setTimeout(runCampaign, 5000); * }); * } * * async function observeLeader() { * const observer = await election.observe(); * console.log('The current leader is', observer.leader()); * observer.on('change', leader => console.log('The new leader is', leader)); * observer.on('error', () => { * // Something happened that fatally interrupted observation. * setTimeout(observeLeader, 5000); * }); * } * ``` * @noInheritDoc */ export class Election { /** * Prefix used in the namespace for election-based operations. */ public static readonly prefix = 'election'; private readonly namespace: Namespace; /** * @internal */ constructor(parent: Namespace, public readonly name: string, private readonly ttl: number = 60) { this.namespace = parent.namespace(`${Election.prefix}/${this.name}/`); } /** * Puts the value as eligible for election. Multiple sessions can participate * in the election, but only one can be the leader at a time. * * A common pattern in cluster-based applications is to campaign the hostname * or IP of the current server, and allow the leader server to be elected * among them. * * You should listen to the `error` and `elected` events on the returned * object to know when the instance becomes the leader, and when its campaign * fails. Once you're finished, you can use {@link Campaign.resign} to * forfeit its bid at leadership. * * Once acquired, instance will not lose its leadership unless `resign()` * is called, or `error` is emitted. */ public campaign(value: string) { return new Campaign(this.namespace, value, this.ttl); } /** * Returns the currently-elected leader value (passed to `campaign()` or * `proclaim()`), or undefined if there's no elected leader. */ public async leader(encoding?: BufferEncoding): Promise<string | undefined>; /** * Returns the currently-elected leader value (passed to `campaign()` or * `proclaim()`), or undefined if there's no elected leader. */ public async leader(encoding: 'buffer'): Promise<Buffer | undefined>; public async leader(encoding: BufferEncoding | 'buffer' = 'utf-8') { const result = await this.namespace.getAll().sort('Create', 'Ascend').limit(1).exec(); const leader = result.kvs[0]; if (leader === undefined) { return undefined; } return encoding === 'buffer' ? leader.value : leader.value.toString(); } /** * Creates an observer for the election, which emits events when results * change. The observer must be closed using `observer.cancel()` when * you're finished with it. */ public async observe() { const observer = new ElectionObserver(this.namespace); return new Promise<ElectionObserver>((resolve, reject) => { observer.once('change', () => resolve(observer)); observer.once('error', reject); }); } } async function waitForDelete(namespace: Namespace, key: Buffer, rev: string) { const watcher = await namespace.watch().key(key).startRevision(rev).only('delete').create(); const deleteOrError = new Promise((resolve, reject) => { watcher.once('delete', resolve); watcher.once('error', reject); }); try { await deleteOrError; } finally { await watcher.cancel(); } } /** * Returns a function that resolves when all of the given keys are deleted. */ async function waitForDeletes(namespace: Namespace, keys: Buffer[]) { for (const key of keys) { const res = await namespace.get(key).exec(); if (res.kvs.length) { await waitForDelete(namespace, key, res.header.revision); } } }
the_stack
import * as _ from 'lodash'; import * as setProtocolUtils from 'set-protocol-utils'; import * as ethUtil from 'ethereumjs-util'; import { Address } from 'set-protocol-utils'; import { BigNumber } from 'bignumber.js'; import { AuctionMockContract, AuctionGettersMockContract, LinearAuctionLiquidatorContract, LinearAuctionMockContract, LiquidatorMockContract, LiquidatorProxyContract, LiquidatorUtilsMockContract, OracleWhiteListContract, SetTokenContract, TWAPAuctionCallerContract, TWAPAuctionMockContract, TWAPAuctionGettersMockContract, TWAPLiquidatorContract, TwoAssetPriceBoundedLinearAuctionMockContract, } from '../contracts'; import { coerceStructBNValuesToString, getContractInstance, importArtifactsFromSource, txnFrom, getWeb3, } from '../web3Helper'; import { AUCTION_CURVE_DENOMINATOR, SCALE_FACTOR, ZERO, ONE_DAY_IN_SECONDS, } from '../constants'; import { AssetPairVolumeBounds, LinearAuction, TokenFlow } from '../auction'; import { ether } from '../units'; const web3 = getWeb3(); const AuctionMock = importArtifactsFromSource('AuctionMock'); const AuctionGettersMock = importArtifactsFromSource('AuctionGettersMock'); const LinearAuctionLiquidator = importArtifactsFromSource('LinearAuctionLiquidator'); const LinearAuctionMock = importArtifactsFromSource('LinearAuctionMock'); const LiquidatorMock = importArtifactsFromSource('LiquidatorMock'); const LiquidatorProxy = importArtifactsFromSource('LiquidatorProxy'); const LiquidatorUtilsMock = importArtifactsFromSource('LiquidatorUtilsMock'); const TWAPAuctionCaller = importArtifactsFromSource('TWAPAuctionCaller'); const TWAPAuctionMock = importArtifactsFromSource('TWAPAuctionMock'); const TWAPAuctionGettersMock = importArtifactsFromSource('TWAPAuctionGettersMock'); const TWAPLiquidator = importArtifactsFromSource('TWAPLiquidator'); const TwoAssetPriceBoundedLinearAuctionMock = importArtifactsFromSource('TwoAssetPriceBoundedLinearAuctionMock'); import { ERC20Helper } from './erc20Helper'; import { ValuationHelper } from './valuationHelper'; const { SetProtocolTestUtils: SetTestUtils, SetProtocolUtils: SetUtils } = setProtocolUtils; export interface AuctionData { maxNaturalUnit: BigNumber; minimumBid: BigNumber; startTime: BigNumber; startingCurrentSets: BigNumber; remainingCurrentSets: BigNumber; combinedTokenArray: Address[]; combinedCurrentSetUnits: BigNumber[]; combinedNextSetUnits: BigNumber[]; } export interface TestTWAPAuctionData { orderSize: BigNumber; orderRemaining: BigNumber; lastChunkAuctionEnd: BigNumber; chunkAuctionPeriod: BigNumber; chunkSize: BigNumber; remainingCurrentSets: BigNumber; } export class LiquidatorHelper { private _contractOwnerAddress: Address; private _erc20Helper: ERC20Helper; private _valuationHelper: ValuationHelper; constructor( contractOwnerAddress: Address, erc20Helper: ERC20Helper, valuationHelper: ValuationHelper ) { this._contractOwnerAddress = contractOwnerAddress; this._erc20Helper = erc20Helper; this._valuationHelper = valuationHelper; } /* ============ Deployment ============ */ public async deployAuctionMockAsync( from: Address = this._contractOwnerAddress ): Promise<AuctionMockContract> { const auctionMock = await AuctionMock.new(txnFrom(from)); return new AuctionMockContract(getContractInstance(auctionMock), txnFrom(from)); } public async deployAuctionGettersMockAsync( from: Address = this._contractOwnerAddress ): Promise<AuctionGettersMockContract> { const auctionGettersMock = await AuctionGettersMock.new(txnFrom(from)); return new AuctionGettersMockContract(getContractInstance(auctionGettersMock), txnFrom(from)); } public async deployTWAPAuctionGettersMockAsync( from: Address = this._contractOwnerAddress ): Promise<TWAPAuctionGettersMockContract> { const twapAuctionGettersMock = await TWAPAuctionGettersMock.new(txnFrom(from)); return new TWAPAuctionGettersMockContract(getContractInstance(twapAuctionGettersMock), txnFrom(from)); } public async deployTWAPAuctionCallerAsync( liquidator: Address, failAuctionPeriod: BigNumber = ONE_DAY_IN_SECONDS, from: Address = this._contractOwnerAddress ): Promise<TWAPAuctionCallerContract> { const auctionCaller = await TWAPAuctionCaller.new(liquidator, failAuctionPeriod, txnFrom(from)); return new TWAPAuctionCallerContract(getContractInstance(auctionCaller), txnFrom(from)); } public async deployLiquidatorProxyAsync( liquidator: Address, from: Address = this._contractOwnerAddress ): Promise<LiquidatorProxyContract> { const liquidatorProxy = await LiquidatorProxy.new(liquidator, txnFrom(from)); return new LiquidatorProxyContract(getContractInstance(liquidatorProxy), txnFrom(from)); } public async deployLiquidatorUtilsMockAsync( from: Address = this._contractOwnerAddress ): Promise<LiquidatorUtilsMockContract> { const liquidatorUtilsMock = await LiquidatorUtilsMock.new(txnFrom(from)); return new LiquidatorUtilsMockContract(getContractInstance(liquidatorUtilsMock), txnFrom(from)); } public async deployLinearAuctionMockAsync( oracleWhiteList: Address, auctionPeriod: BigNumber, rangeStart: BigNumber, rangeEnd: BigNumber, from: Address = this._contractOwnerAddress ): Promise<LinearAuctionMockContract> { const linearAuctionMock = await LinearAuctionMock.new( oracleWhiteList, auctionPeriod, rangeStart, rangeEnd, txnFrom(from) ); return new LinearAuctionMockContract(getContractInstance(linearAuctionMock), txnFrom(from)); } public async deployLinearAuctionLiquidatorAsync( core: Address, oracleWhiteList: Address, auctionPeriod: BigNumber, rangeStart: BigNumber, rangeEnd: BigNumber, name: string, from: Address = this._contractOwnerAddress ): Promise<LinearAuctionLiquidatorContract> { const linearAuctionLiquidator = await LinearAuctionLiquidator.new( core, oracleWhiteList, auctionPeriod, rangeStart, rangeEnd, name, txnFrom(from) ); return new LinearAuctionLiquidatorContract( getContractInstance(linearAuctionLiquidator), txnFrom(from) ); } public async deployTWAPLiquidatorAsync( core: Address, oracleWhiteList: Address, auctionPeriod: BigNumber, rangeStart: BigNumber, rangeEnd: BigNumber, assetPairBounds: AssetPairVolumeBounds[], name: string, from: Address = this._contractOwnerAddress ): Promise<TWAPLiquidatorContract> { const assetPairBoundsStr = []; for (let i = 0; i < assetPairBounds.length; i++) { assetPairBoundsStr.push(coerceStructBNValuesToString(assetPairBounds[i])); } const twapLiquidator = await TWAPLiquidator.new( core, oracleWhiteList, auctionPeriod, rangeStart, rangeEnd, assetPairBoundsStr, name, txnFrom(from) ); return new TWAPLiquidatorContract( getContractInstance(twapLiquidator), txnFrom(from) ); } public async deployTwoAssetPriceBoundedLinearAuctionMock( oracleWhiteList: Address, auctionPeriod: BigNumber, rangeStart: BigNumber, rangeEnd: BigNumber, from: Address = this._contractOwnerAddress ): Promise<TwoAssetPriceBoundedLinearAuctionMockContract> { const mockContract = await TwoAssetPriceBoundedLinearAuctionMock.new( oracleWhiteList, auctionPeriod, rangeStart, rangeEnd, txnFrom(from) ); return new TwoAssetPriceBoundedLinearAuctionMockContract( getContractInstance(mockContract), txnFrom(from) ); } public async deployTWAPAuctionMock( oracleWhiteList: Address, auctionPeriod: BigNumber, rangeStart: BigNumber, rangeEnd: BigNumber, assetPairBounds: AssetPairVolumeBounds[], from: Address = this._contractOwnerAddress ): Promise<TWAPAuctionMockContract> { const assetPairBoundsStr = []; for (let i = 0; i < assetPairBounds.length; i++) { assetPairBoundsStr.push(coerceStructBNValuesToString(assetPairBounds[i])); } const mockContract = await TWAPAuctionMock.new( oracleWhiteList, auctionPeriod, rangeStart, rangeEnd, assetPairBoundsStr, txnFrom(from) ); return new TWAPAuctionMockContract( getContractInstance(mockContract), txnFrom(from) ); } public async deployLiquidatorMockAsync( from: Address = this._contractOwnerAddress ): Promise<LiquidatorMockContract> { const liquidatorMock = await LiquidatorMock.new(txnFrom(from)); return new LiquidatorMockContract(getContractInstance(liquidatorMock), txnFrom(from)); } /* ============ Deploy Helpers ============ */ public generateTWAPLiquidatorCalldata( usdChunkSize: BigNumber, chunkAuctionPeriod: BigNumber, ): string { return SetTestUtils.bufferArrayToHex([ SetUtils.paddedBufferForBigNumber(usdChunkSize), SetUtils.paddedBufferForBigNumber(chunkAuctionPeriod), ]); } public generateAssetPairHashes( assetOne: Address, assetTwo: Address ): string { let hexString: string; const assetOneNum = new BigNumber(assetOne); const assetTwoNum = new BigNumber(assetTwo); if (assetOneNum.greaterThan(assetTwoNum)) { hexString = SetTestUtils.bufferArrayToHex([ ethUtil.toBuffer(assetTwo), ethUtil.toBuffer(assetOne), ]); } else { hexString = SetTestUtils.bufferArrayToHex([ ethUtil.toBuffer(assetOne), ethUtil.toBuffer(assetTwo), ]); } return web3.utils.soliditySha3(hexString); } /* ============ Bid-Related ============ */ // Get bid transfer values public async getBidPriceValues( setToken: SetTokenContract, quantity: BigNumber, combinedUnits: BigNumber[] ): Promise<BigNumber[]> { const naturalUnit = await setToken.naturalUnit.callAsync(); return combinedUnits.map(unit => unit.mul(quantity).div(naturalUnit)); } public async constructCombinedUnitArrayAsync( setToken: SetTokenContract, combinedTokenArray: Address[], minimumBid: BigNumber, ): Promise<BigNumber[]> { const setTokenComponents = await setToken.getComponents.callAsync(); const setTokenUnits = await setToken.getUnits.callAsync(); const setTokenNaturalUnit = await setToken.naturalUnit.callAsync(); // Create combined unit array for target Set const combinedSetTokenUnits: BigNumber[] = []; combinedTokenArray.forEach(address => { const index = setTokenComponents.indexOf(address); if (index != -1) { const totalTokenAmount = setTokenUnits[index].mul(minimumBid).div(setTokenNaturalUnit); combinedSetTokenUnits.push(totalTokenAmount); } else { combinedSetTokenUnits.push(new BigNumber(0)); } }); return combinedSetTokenUnits; } public async calculateMinimumBidAsync( linearAuction: LinearAuction, currentSet: SetTokenContract, nextSet: SetTokenContract, assetPairPrice: BigNumber, ): Promise<BigNumber> { const maxNaturalUnit = BigNumber.max( await currentSet.naturalUnit.callAsync(), await nextSet.naturalUnit.callAsync() ); const [assetOneDecimals, assetTwoDecimals] = await this._erc20Helper.getTokensDecimalsAsync( linearAuction.auction.combinedTokenArray ); const assetOneFullUnit = new BigNumber(10 ** assetOneDecimals.toNumber()); const assetTwoFullUnit = new BigNumber(10 ** assetTwoDecimals.toNumber()); const auctionFairValue = this.calculateAuctionBound( linearAuction, assetOneFullUnit, assetTwoFullUnit, assetPairPrice ); const tokenFlow = this.constructTokenFlow( linearAuction, maxNaturalUnit.mul(ether(1)), auctionFairValue ); const tokenFlowList = [ BigNumber.max(tokenFlow.inflow[0], tokenFlow.outflow[0]), BigNumber.max(tokenFlow.inflow[1], tokenFlow.outflow[1]), ]; let minimumBidMultiplier: BigNumber = ZERO; for (let i = 0; i < linearAuction.auction.combinedTokenArray.length; i++) { const currentMinBidMultiplier = ether(1000).div(tokenFlowList[i]).round(0, 2); minimumBidMultiplier = currentMinBidMultiplier.greaterThan(minimumBidMultiplier) ? currentMinBidMultiplier : minimumBidMultiplier; } return maxNaturalUnit.mul(minimumBidMultiplier); } public async calculateAuctionBoundsAsync( linearAuction: LinearAuction, startBound: BigNumber, endBound: BigNumber, oracleWhiteList: OracleWhiteListContract ): Promise<[BigNumber, BigNumber]> { const [assetOneDecimals, assetTwoDecimals] = await this._erc20Helper.getTokensDecimalsAsync( linearAuction.auction.combinedTokenArray ); const assetOneFullUnit = new BigNumber(10 ** assetOneDecimals.toNumber()); const assetTwoFullUnit = new BigNumber(10 ** assetTwoDecimals.toNumber()); const [assetOnePrice, assetTwoPrice] = await this._valuationHelper.getComponentPricesAsync( linearAuction.auction.combinedTokenArray, oracleWhiteList ); const startValue = this.calculateTwoAssetStartPrice( linearAuction, assetOneFullUnit, assetTwoFullUnit, assetOnePrice.div(assetTwoPrice), startBound ); const endValue = this.calculateTwoAssetEndPrice( linearAuction, assetOneFullUnit, assetTwoFullUnit, assetOnePrice.div(assetTwoPrice), endBound ); return [startValue, endValue]; } public calculateTwoAssetStartPrice( linearAuction: LinearAuction, assetOneFullUnit: BigNumber, assetTwoFullUnit: BigNumber, assetPairPrice: BigNumber, startBound: BigNumber ): BigNumber { const auctionFairValue = this.calculateAuctionBound( linearAuction, assetOneFullUnit, assetTwoFullUnit, assetPairPrice ); const tokenFlowIncreasing = this.isTokenFlowIncreasing( linearAuction.auction.combinedCurrentSetUnits[0], linearAuction.auction.combinedNextSetUnits[0], auctionFairValue ); let startPairPrice: BigNumber; if (tokenFlowIncreasing) { startPairPrice = assetPairPrice.mul(ether(1).sub(startBound)).div(ether(1)); } else { startPairPrice = assetPairPrice.mul(ether(1).add(startBound)).div(ether(1)); } const startValue = this.calculateAuctionBound( linearAuction, assetOneFullUnit, assetTwoFullUnit, startPairPrice ); return startValue; } public calculateTwoAssetEndPrice( linearAuction: LinearAuction, assetOneFullUnit: BigNumber, assetTwoFullUnit: BigNumber, assetPairPrice: BigNumber, endBound: BigNumber ): BigNumber { const auctionFairValue = this.calculateAuctionBound( linearAuction, assetOneFullUnit, assetTwoFullUnit, assetPairPrice ); const tokenFlowIncreasing = this.isTokenFlowIncreasing( linearAuction.auction.combinedCurrentSetUnits[0], linearAuction.auction.combinedNextSetUnits[0], auctionFairValue ); let endPairPrice: BigNumber; if (tokenFlowIncreasing) { endPairPrice = assetPairPrice.mul(ether(1).add(endBound)).div(ether(1)); } else { endPairPrice = assetPairPrice.mul(ether(1).sub(endBound)).div(ether(1)); } const endValue = this.calculateAuctionBound( linearAuction, assetOneFullUnit, assetTwoFullUnit, endPairPrice ); return endValue; } public calculateAuctionBound( linearAuction: LinearAuction, assetOneFullUnit: BigNumber, assetTwoFullUnit: BigNumber, targetPrice: BigNumber ): BigNumber { const combinedNextUnitArray = linearAuction.auction.combinedNextSetUnits; const combinedCurrentUnitArray = linearAuction.auction.combinedCurrentSetUnits; const calcNumerator = combinedNextUnitArray[1].mul(AUCTION_CURVE_DENOMINATOR).div(assetTwoFullUnit).add( targetPrice.mul(combinedNextUnitArray[0]).mul(AUCTION_CURVE_DENOMINATOR).div(assetOneFullUnit) ); const calcDenominator = combinedCurrentUnitArray[1].div(assetTwoFullUnit).add( targetPrice.mul(combinedCurrentUnitArray[0]).div(assetOneFullUnit) ); return calcNumerator.div(calcDenominator).round(0, 3); } public isTokenFlowIncreasing( assetOneCurrentUnit: BigNumber, assetOneNextUnit: BigNumber, fairValue: BigNumber ): boolean { return assetOneNextUnit.mul(AUCTION_CURVE_DENOMINATOR).greaterThan(assetOneCurrentUnit.mul(fairValue)); } public calculateCurrentPrice( linearAuction: LinearAuction, timestamp: BigNumber, auctionPeriod: BigNumber ): BigNumber { const elapsed = timestamp.sub(linearAuction.auction.startTime); const priceRange = new BigNumber(linearAuction.endPrice).sub(linearAuction.startPrice); const elapsedPrice = elapsed.mul(priceRange).div(auctionPeriod).round(0, 3); return new BigNumber(linearAuction.startPrice).add(elapsedPrice); } public async calculateFairValueAsync( currentSetToken: SetTokenContract, nextSetToken: SetTokenContract, oracleWhiteList: OracleWhiteListContract, from: Address = this._contractOwnerAddress, ): Promise<BigNumber> { const currentSetUSDValue = await this._valuationHelper.calculateSetTokenValueAsync( currentSetToken, oracleWhiteList ); const nextSetUSDValue = await this._valuationHelper.calculateSetTokenValueAsync(nextSetToken, oracleWhiteList); return nextSetUSDValue.mul(SCALE_FACTOR).div(currentSetUSDValue).round(0, 3); } public constructTokenFlow( linearAuction: LinearAuction, quantity: BigNumber, priceScaled: BigNumber, ): TokenFlow { const inflow: BigNumber[] = []; const outflow: BigNumber[] = []; // Calculate the inflows and outflow arrays; const { combinedTokenArray, combinedCurrentSetUnits, combinedNextSetUnits, maxNaturalUnit, } = linearAuction.auction; const unitsMultiplier = quantity.div(maxNaturalUnit).round(0, 3); for (let i = 0; i < combinedCurrentSetUnits.length; i++) { const flow = combinedNextSetUnits[i].mul(SCALE_FACTOR).sub(combinedCurrentSetUnits[i].mul(priceScaled)); if (flow.greaterThan(0)) { const inflowUnit = unitsMultiplier.mul( combinedNextSetUnits[i].mul(SCALE_FACTOR).sub(combinedCurrentSetUnits[i].mul(priceScaled)) ).div(priceScaled).round(0, 3); inflow.push(inflowUnit); outflow.push(ZERO); } else { const outflowUnit = unitsMultiplier.mul( combinedCurrentSetUnits[i].mul(priceScaled).sub(combinedNextSetUnits[i].mul(SCALE_FACTOR)) ).div(priceScaled).round(0, 3); outflow.push(outflowUnit); inflow.push(ZERO); } } return { addresses: combinedTokenArray, inflow, outflow, }; } public async calculateChunkSize( currentSet: SetTokenContract, nextSet: SetTokenContract, oracleWhiteList: OracleWhiteListContract, currentSetQuantity: BigNumber, usdChunkSize: BigNumber, ): Promise<BigNumber> { const rebalanceVolume = await this.calculateRebalanceVolumeAsync( currentSet, nextSet, oracleWhiteList, currentSetQuantity ); if (rebalanceVolume.div(usdChunkSize).greaterThanOrEqualTo(1)) { return currentSetQuantity.mul(usdChunkSize).div(rebalanceVolume).round(0, 3); } else { return currentSetQuantity; } } public calculateChunkAuctionMaximumBid( chunkAuctionSize: BigNumber, minimumBid: BigNumber, ): BigNumber { return chunkAuctionSize.div(minimumBid).round(0, 3).mul(minimumBid); } public async calculateRebalanceVolumeAsync( currentSet: SetTokenContract, nextSet: SetTokenContract, oracleWhiteList: OracleWhiteListContract, currentSetQuantity: BigNumber ): Promise<BigNumber> { const currentSetValue = await this._valuationHelper.calculateSetTokenValueAsync(currentSet, oracleWhiteList); const components = await currentSet.getComponents.callAsync(); const allocationAsset = components[0]; const currentSetAssetAllocation = await this.calculateAssetAllocationAsync( currentSet, oracleWhiteList, allocationAsset ); const nextSetAssetAllocation = await this.calculateAssetAllocationAsync(nextSet, oracleWhiteList, allocationAsset); const allocationChange = currentSetAssetAllocation.sub(nextSetAssetAllocation).abs(); return currentSetValue.mul(currentSetQuantity).mul(allocationChange).div(SCALE_FACTOR).div(SCALE_FACTOR); } public async calculateAssetAllocationAsync( setToken: SetTokenContract, oracleWhiteList: OracleWhiteListContract, asset: Address ): Promise<BigNumber> { const setValue = await this._valuationHelper.calculateSetTokenValueAsync(setToken, oracleWhiteList); const allocationValue = await this._valuationHelper.calculateAllocationValueAsync(setToken, oracleWhiteList, asset); return allocationValue.mul(ether(1)).div(setValue).round(0, 3); } }
the_stack
import React, { useState, useEffect } from "react"; import Grid from "@material-ui/core/Grid"; import List from "@material-ui/core/List"; import ListItemText from "@material-ui/core/ListItemText"; import ListItem from "@material-ui/core/ListItem"; import { makeStyles } from "@material-ui/core/styles"; import { MuiCloseIcon, MuiSkipPreviousIcon, MuiPlayArrowIcon, MuiSkipNextIcon, MuiShuffleIcon, MuiRepeatOneIcon, MuiStopIcon, MuiVolumeUpIcon, MuiVolumeOffIcon, MuiDevicesIcon, MuiAddCircleIcon, MuiFavoriteIcon, MuiFavoriteBorderIcon, MuiRefreshIcon, } from "../icons"; import IconButton from "@material-ui/core/IconButton"; import Typography from "@material-ui/core/Typography"; import { grey, deepPurple } from "@material-ui/core/colors"; import Box from "@material-ui/core/Box"; import Menu from "@material-ui/core/Menu"; import MenuItem from "@material-ui/core/MenuItem"; import Divider from "@material-ui/core/Divider"; import { DARK_BG_COLOR, DARK_BG_TEXT_COLOR, DARK_BG_TEXT_SECONDARY_COLOR, MAX_MENU_HEIGHT } from "../../utils/view_constants"; import Tooltip from "@material-ui/core/Tooltip"; import CardHeader from "@material-ui/core/CardHeader"; const useStyles = makeStyles((theme) => ({ buttonGroupItems: { display: "flex", flexDirection: "column", alignItems: "center", "& > *": { margin: theme.spacing(1), }, }, listContainer: { marginLeft: 10, marginRight: 10, marginBottom: 0, marginTop: 0, position: "relative", }, listItemIcon: { minWidth: "28px", }, menuHeaderPrimary: { wrap: "nowrap", overflow: "hidden", textOverflow: "ellipsis", color: deepPurple[200], marginRight: 10, }, menuHeaderSecondary: { wrap: "nowrap", overflow: "hidden", textOverflow: "ellipsis", color: grey[500], fontWeight: 300, fontSize: 12, marginRight: 10, }, cardHeaderAction: { color: theme.palette.secondary.main, }, cardHeaderTitle: { color: DARK_BG_TEXT_COLOR, }, cardHeaderSubheader: { color: DARK_BG_TEXT_SECONDARY_COLOR, }, playerControl: { width: "fit-content", border: `1px solid ${theme.palette.divider}`, borderRadius: theme.shape.borderRadius, backgroundColor: theme.palette.background.paper, color: theme.palette.text.secondary, "& svg": { margin: theme.spacing(1.5), }, "& hr": { margin: theme.spacing(0, 0.5), }, }, margin: { margin: 0, padding: 0, }, })); function getTrackName(currentTrack) { return isTrackAvailable(currentTrack) ? currentTrack?.name || "Select a track to play" : "Select a track to play"; } function getTrackDescription(currentTrack) { let description = ""; if (currentTrack && isTrackAvailable(currentTrack)) { if (currentTrack.artist && typeof currentTrack.artist === "string") { description += currentTrack.artist; } if (currentTrack.album && typeof currentTrack.album === "string") { if (description.length) { description += " - "; } description += currentTrack.album; } } return description; } function isRepeatingTrack(spotifyContext) { return !!(spotifyContext && spotifyContext.repeat_state === "track"); } function isShuffling(spotifyContext) { return !!(spotifyContext && spotifyContext.shuffle_state === true); } function isTrackAvailable(currentTrack) { return !!(currentTrack && currentTrack.id); } function isPaused(currentTrack) { return !!(currentTrack && currentTrack.state === "paused"); } function isPlaying(currentTrack) { return !!(currentTrack && currentTrack.state === "playing"); } function isMuted(currentTrack) { return !!(isTrackAvailable(currentTrack) && currentTrack.volume === 0); } function isLiked(currentTrack) { return !!(isTrackAvailable(currentTrack) && currentTrack.liked); } export default function AudioControl(props) { const classes = useStyles(); const [openMenu, setOpenMenu] = useState(false); useEffect(() => { if (openMenu !== props.openMenu) { setOpenMenu(props.openMenu); } }); const spotifyContext = props.stateData.spotifyPlayerContext; const currentTrack = props.stateData.currentlyRunningTrack; /** * primaryText, * secondaryText, * isActive */ const deviceMenuInfo = props.stateData.deviceMenuInfo; const runningTrackName = getTrackName(currentTrack); const runningTrackStatus = getTrackDescription(currentTrack); const enableControls = isTrackAvailable(currentTrack); const repeatingTrack = isRepeatingTrack(spotifyContext); const shuffling = isShuffling(spotifyContext); const paused = isPaused(currentTrack); const playing = isPlaying(currentTrack); const muted = isMuted(currentTrack); const liked = isLiked(currentTrack); /** * paused song * spotifyPlayerContext * {"timestamp":0,"device":{"id":"","is_active":"","is_restricted":false, * "name":"","type":"","volume_percent":0},"progress_ms":"","is_playing":false, * "currently_playing_type":"","actions":null,"item":null,"shuffle_state":false, * "repeat_state":"","context":null} * * currentlyRunningTrack: * {"artist":"Yves V","album":"Echo","genre":"","disc_number":1,"duration":180560,"played_count":0, * "track_number":1,"id":"57Zcl7oKKr29qHp38dzzWi","name":"Echo","state":"paused", * "volume":100,"popularity":67, * "artwork_url":"https://i.scdn.co/image/ab67616d0000b2730b74292f2a1f6825f10f3c4f", * "spotify_url":"spotify:track:57Zcl7oKKr29qHp38dzzWi","progress_ms":27898, * "uri":"spotify:track:57Zcl7oKKr29qHp38dzzWi"} */ function handleClose(event = null) { props.handleCloseCallback(); } // audio control functions function unMuteClick() { const command = { action: "musictime.unMute", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); } function muteClick() { const command = { action: "musictime.mute", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); } function repeatOneClick() { const command = { action: "musictime.repeatTrack", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); spotifyContext.repeat_state = "track"; } function disableRepeatClick() { const command = { action: "musictime.repeatOff", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); spotifyContext.repeat_state = "none"; } function playClick() { const command = { action: "musictime.play", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); } function pauseClick() { const command = { action: "musictime.pause", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); } function previousClick() { const command = { action: "musictime.previous", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); } function nextClick() { const command = { action: "musictime.next", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); } function disableShuffleClick() { const command = { action: "musictime.shuffleOff", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); spotifyContext.shuffle_state = false; } function enableShuffleClick() { const command = { action: "musictime.shuffleOn", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); spotifyContext.shuffle_state = true; } function connectDeviceClick() { const command = { action: "musictime.deviceSelector", command: "command_execute", }; props.vscode.postMessage(command); props.handleCloseCallback(); } function updateLikedClick() { const command = { action: !liked ? "musictime.like" : "musictime.unlike", command: "command_execute", arguments: [currentTrack], }; props.vscode.postMessage(command); props.handleCloseCallback(); } function refreshSongInfoClick() { const command = { action: "musictime.songTitleRefresh", command: "command_execute", }; props.vscode.postMessage(command); } return ( <Menu id="main_audio_options_menu" anchorEl={props.anchorEl} keepMounted open={openMenu} anchorOrigin={{ vertical: "top", horizontal: "right", }} transformOrigin={{ vertical: "bottom", horizontal: "right", }} PaperProps={{ style: { padding: 1, minWidth: 280, maxHeight: MAX_MENU_HEIGHT, backgroundColor: DARK_BG_COLOR, color: DARK_BG_TEXT_COLOR, }, }} > <MenuItem key="audio_options_menu_item" style={{ padding: 0, margin: 0 }}> <List disablePadding={true} dense={true} className={classes.listContainer}> <ListItem key={`audo-options-info-li`} disableGutters={true} dense={true}> <ListItemText primary={ <Typography noWrap className={classes.menuHeaderPrimary}> {runningTrackName} </Typography> } secondary={ <Typography noWrap className={classes.menuHeaderSecondary}> {runningTrackStatus} </Typography> } /> </ListItem> </List> <Box style={{ position: "absolute", right: 4, top: -6 }}> <Tooltip title="Refresh song information"> <IconButton edge="end" onClick={refreshSongInfoClick}> <MuiRefreshIcon fontSize="small" /> </IconButton> </Tooltip> <Tooltip title={liked ? "Unlike" : "Like"}> <IconButton edge="end" onClick={updateLikedClick}> {liked ? <MuiFavoriteIcon fontSize="small" /> : <MuiFavoriteBorderIcon fontSize="small" />} </IconButton> </Tooltip> <IconButton aria-label="Close" onClick={handleClose} edge="end"> <MuiCloseIcon fontSize="small" /> </IconButton> </Box> </MenuItem> <Divider /> <Grid container> <Grid item xs={12}> <CardHeader classes={{ title: classes.cardHeaderTitle, subheader: classes.cardHeaderSubheader, }} avatar={<MuiDevicesIcon />} action={ <Tooltip title={!deviceMenuInfo.isActive ? "Connect" : "Change Device"}> <IconButton onClick={connectDeviceClick}> <MuiAddCircleIcon /> </IconButton> </Tooltip> } title={deviceMenuInfo.primaryText} subheader={deviceMenuInfo.secondaryText || null} /> </Grid> <Grid item xs={12}> <div className={classes.buttonGroupItems}> {enableControls && ( <Grid container alignItems="center" className={classes.playerControl}> <Tooltip title="Previous"> <IconButton onClick={previousClick} className={classes.margin} size="small"> <MuiSkipPreviousIcon color="primary" fontSize="small" /> </IconButton> </Tooltip> {paused && ( <Tooltip title="Play"> <IconButton onClick={playClick} className={classes.margin} size="small"> <MuiPlayArrowIcon color="primary" fontSize="small" /> </IconButton> </Tooltip> )} {playing && ( <Tooltip title="Pause"> <IconButton onClick={pauseClick} className={classes.margin} size="small"> <MuiStopIcon color="primary" fontSize="small" /> </IconButton> </Tooltip> )} <Tooltip title="Next"> <IconButton onClick={nextClick} className={classes.margin} size="small"> <MuiSkipNextIcon color="primary" fontSize="small" /> </IconButton> </Tooltip> <Divider orientation="vertical" flexItem /> <Tooltip title={shuffling ? "Disable shuffle" : "Enable shuffle"}> <IconButton onClick={shuffling ? disableShuffleClick : enableShuffleClick} className={classes.margin} size="small"> <MuiShuffleIcon color={shuffling ? "action" : "primary"} fontSize="small" /> </IconButton> </Tooltip> {repeatingTrack ? ( <Tooltip title="Disable repeat"> <IconButton onClick={disableRepeatClick} className={classes.margin} size="small"> <MuiRepeatOneIcon color="action" fontSize="small" /> </IconButton> </Tooltip> ) : ( <Tooltip title="Enable repeat one"> <IconButton onClick={repeatOneClick} className={classes.margin} size="small"> <MuiRepeatOneIcon color="primary" fontSize="small" /> </IconButton> </Tooltip> )} {muted ? ( <Tooltip title="Unmute"> <IconButton onClick={unMuteClick} className={classes.margin} size="small"> <MuiVolumeOffIcon fontSize="small" /> </IconButton> </Tooltip> ) : ( <Tooltip title="Mute"> <IconButton onClick={muteClick} className={classes.margin} size="small"> <MuiVolumeUpIcon fontSize="small" /> </IconButton> </Tooltip> )} </Grid> )} </div> </Grid> </Grid> </Menu> ); }
the_stack
import { dew as _supportDewDew } from "./support.dew.js"; import { dew as _base64DewDew } from "./base64.dew.js"; import { dew as _nodejsUtilsDewDew } from "./nodejsUtils.dew.js"; import { dew as _npmSetImmediateShimDew } from "/npm:set-immediate-shim@1.0?dew"; import { dew as _externalDewDew } from "./external.dew.js"; var exports = {}, _dewExec = false; export function dew() { if (_dewExec) return exports; _dewExec = true; var support = _supportDewDew(); var base64 = _base64DewDew(); var nodejsUtils = _nodejsUtilsDewDew(); var setImmediate = _npmSetImmediateShimDew(); var external = _externalDewDew(); /** * Convert a string that pass as a "binary string": it should represent a byte * array but may have > 255 char codes. Be sure to take only the first byte * and returns the byte array. * @param {String} str the string to transform. * @return {Array|Uint8Array} the string in a binary format. */ function string2binary(str) { var result = null; if (support.uint8array) { result = new Uint8Array(str.length); } else { result = new Array(str.length); } return stringToArrayLike(str, result); } /** * Create a new blob with the given content and the given type. * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use * an Uint8Array because the stock browser of android 4 won't accept it (it * will be silently converted to a string, "[object Uint8Array]"). * * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge: * when a large amount of Array is used to create the Blob, the amount of * memory consumed is nearly 100 times the original data amount. * * @param {String} type the mime type of the blob. * @return {Blob} the created blob. */ exports.newBlob = function (part, type) { exports.checkSupport("blob"); try { // Blob constructor return new Blob([part], { type: type }); } catch (e) { try { // deprecated, browser only, old way var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder; var builder = new Builder(); builder.append(part); return builder.getBlob(type); } catch (e) { // well, fuck ?! throw new Error("Bug : can't construct the Blob."); } } }; /** * The identity function. * @param {Object} input the input. * @return {Object} the same input. */ function identity(input) { return input; } /** * Fill in an array with a string. * @param {String} str the string to use. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated). * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array. */ function stringToArrayLike(str, array) { for (var i = 0; i < str.length; ++i) { array[i] = str.charCodeAt(i) & 0xFF; } return array; } /** * An helper for the function arrayLikeToString. * This contains static information and functions that * can be optimized by the browser JIT compiler. */ var arrayToStringHelper = { /** * Transform an array of int into a string, chunk by chunk. * See the performances notes on arrayLikeToString. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. * @param {String} type the type of the array. * @param {Integer} chunk the chunk size. * @return {String} the resulting string. * @throws Error if the chunk is too big for the stack. */ stringifyByChunk: function (array, type, chunk) { var result = [], k = 0, len = array.length; // shortcut if (len <= chunk) { return String.fromCharCode.apply(null, array); } while (k < len) { if (type === "array" || type === "nodebuffer") { result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len)))); } else { result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len)))); } k += chunk; } return result.join(""); }, /** * Call String.fromCharCode on every item in the array. * This is the naive implementation, which generate A LOT of intermediate string. * This should be used when everything else fail. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. * @return {String} the result. */ stringifyByChar: function (array) { var resultStr = ""; for (var i = 0; i < array.length; i++) { resultStr += String.fromCharCode(array[i]); } return resultStr; }, applyCanBeUsed: { /** * true if the browser accepts to use String.fromCharCode on Uint8Array */ uint8array: function () { try { return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1; } catch (e) { return false; } }(), /** * true if the browser accepts to use String.fromCharCode on nodejs Buffer. */ nodebuffer: function () { try { return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1; } catch (e) { return false; } }() } }; /** * Transform an array-like object to a string. * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform. * @return {String} the result. */ function arrayLikeToString(array) { // Performances notes : // -------------------- // String.fromCharCode.apply(null, array) is the fastest, see // see http://jsperf.com/converting-a-uint8array-to-a-string/2 // but the stack is limited (and we can get huge arrays !). // // result += String.fromCharCode(array[i]); generate too many strings ! // // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2 // TODO : we now have workers that split the work. Do we still need that ? var chunk = 65536, type = exports.getTypeOf(array), canUseApply = true; if (type === "uint8array") { canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array; } else if (type === "nodebuffer") { canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer; } if (canUseApply) { while (chunk > 1) { try { return arrayToStringHelper.stringifyByChunk(array, type, chunk); } catch (e) { chunk = Math.floor(chunk / 2); } } } // no apply or chunk error : slow and painful algorithm // default browser on android 4.* return arrayToStringHelper.stringifyByChar(array); } exports.applyFromCharCode = arrayLikeToString; /** * Copy the data from an array-like to an other array-like. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array. * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated. * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array. */ function arrayLikeToArrayLike(arrayFrom, arrayTo) { for (var i = 0; i < arrayFrom.length; i++) { arrayTo[i] = arrayFrom[i]; } return arrayTo; } // a matrix containing functions to transform everything into everything. var transform = {}; // string to ? transform["string"] = { "string": identity, "array": function (input) { return stringToArrayLike(input, new Array(input.length)); }, "arraybuffer": function (input) { return transform["string"]["uint8array"](input).buffer; }, "uint8array": function (input) { return stringToArrayLike(input, new Uint8Array(input.length)); }, "nodebuffer": function (input) { return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length)); } }; // array to ? transform["array"] = { "string": arrayLikeToString, "array": identity, "arraybuffer": function (input) { return new Uint8Array(input).buffer; }, "uint8array": function (input) { return new Uint8Array(input); }, "nodebuffer": function (input) { return nodejsUtils.newBufferFrom(input); } }; // arraybuffer to ? transform["arraybuffer"] = { "string": function (input) { return arrayLikeToString(new Uint8Array(input)); }, "array": function (input) { return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength)); }, "arraybuffer": identity, "uint8array": function (input) { return new Uint8Array(input); }, "nodebuffer": function (input) { return nodejsUtils.newBufferFrom(new Uint8Array(input)); } }; // uint8array to ? transform["uint8array"] = { "string": arrayLikeToString, "array": function (input) { return arrayLikeToArrayLike(input, new Array(input.length)); }, "arraybuffer": function (input) { return input.buffer; }, "uint8array": identity, "nodebuffer": function (input) { return nodejsUtils.newBufferFrom(input); } }; // nodebuffer to ? transform["nodebuffer"] = { "string": arrayLikeToString, "array": function (input) { return arrayLikeToArrayLike(input, new Array(input.length)); }, "arraybuffer": function (input) { return transform["nodebuffer"]["uint8array"](input).buffer; }, "uint8array": function (input) { return arrayLikeToArrayLike(input, new Uint8Array(input.length)); }, "nodebuffer": identity }; /** * Transform an input into any type. * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer. * If no output type is specified, the unmodified input will be returned. * @param {String} outputType the output type. * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert. * @throws {Error} an Error if the browser doesn't support the requested output type. */ exports.transformTo = function (outputType, input) { if (!input) { // undefined, null, etc // an empty string won't harm. input = ""; } if (!outputType) { return input; } exports.checkSupport(outputType); var inputType = exports.getTypeOf(input); var result = transform[inputType][outputType](input); return result; }; /** * Return the type of the input. * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer. * @param {Object} input the input to identify. * @return {String} the (lowercase) type of the input. */ exports.getTypeOf = function (input) { if (typeof input === "string") { return "string"; } if (Object.prototype.toString.call(input) === "[object Array]") { return "array"; } if (support.nodebuffer && nodejsUtils.isBuffer(input)) { return "nodebuffer"; } if (support.uint8array && input instanceof Uint8Array) { return "uint8array"; } if (support.arraybuffer && input instanceof ArrayBuffer) { return "arraybuffer"; } }; /** * Throw an exception if the type is not supported. * @param {String} type the type to check. * @throws {Error} an Error if the browser doesn't support the requested type. */ exports.checkSupport = function (type) { var supported = support[type.toLowerCase()]; if (!supported) { throw new Error(type + " is not supported by this platform"); } }; exports.MAX_VALUE_16BITS = 65535; exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1 /** * Prettify a string read as binary. * @param {string} str the string to prettify. * @return {string} a pretty string. */ exports.pretty = function (str) { var res = '', code, i; for (i = 0; i < (str || "").length; i++) { code = str.charCodeAt(i); res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase(); } return res; }; /** * Defer the call of a function. * @param {Function} callback the function to call asynchronously. * @param {Array} args the arguments to give to the callback. */ exports.delay = function (callback, args, self) { setImmediate(function () { callback.apply(self || null, args || []); }); }; /** * Extends a prototype with an other, without calling a constructor with * side effects. Inspired by nodejs' `utils.inherits` * @param {Function} ctor the constructor to augment * @param {Function} superCtor the parent constructor to use */ exports.inherits = function (ctor, superCtor) { var Obj = function () {}; Obj.prototype = superCtor.prototype; ctor.prototype = new Obj(); }; /** * Merge the objects passed as parameters into a new one. * @private * @param {...Object} var_args All objects to merge. * @return {Object} a new object with the data of the others. */ exports.extend = function () { var result = {}, i, attr; for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers for (attr in arguments[i]) { if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") { result[attr] = arguments[i][attr]; } } } return result; }; /** * Transform arbitrary content into a Promise. * @param {String} name a name for the content being processed. * @param {Object} inputData the content to process. * @param {Boolean} isBinary true if the content is not an unicode string * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character. * @param {Boolean} isBase64 true if the string content is encoded with base64. * @return {Promise} a promise in a format usable by JSZip. */ exports.prepareContent = function (name, inputData, isBinary, isOptimizedBinaryString, isBase64) { // if inputData is already a promise, this flatten it. var promise = external.Promise.resolve(inputData).then(function (data) { var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1); if (isBlob && typeof FileReader !== "undefined") { return new external.Promise(function (resolve, reject) { var reader = new FileReader(); reader.onload = function (e) { resolve(e.target.result); }; reader.onerror = function (e) { reject(e.target.error); }; reader.readAsArrayBuffer(data); }); } else { return data; } }); return promise.then(function (data) { var dataType = exports.getTypeOf(data); if (!dataType) { return external.Promise.reject(new Error("Can't read the data of '" + name + "'. Is it " + "in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?")); } // special case : it's way easier to work with Uint8Array than with ArrayBuffer if (dataType === "arraybuffer") { data = exports.transformTo("uint8array", data); } else if (dataType === "string") { if (isBase64) { data = base64.decode(data); } else if (isBinary) { // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask if (isOptimizedBinaryString !== true) { // this is a string, not in a base64 format. // Be sure that this is a correct "binary string" data = string2binary(data); } } } return data; }); }; return exports; }
the_stack
import { makeTest, TestBedConfig, ItFuncConfig, ItFunc } from './scaffolding/runner'; import { DatasourceRemover, getDatasourceClassForRemovals } from './scaffolding/datasources/class'; import { Misc } from './miscellaneous/misc'; import { getDynamicSumSize, getDynamicSizeByIndex } from './miscellaneous/dynamicSize'; import { ItemsPredicate, SizeStrategy } from './miscellaneous/vscroll'; interface ICustom { remove: number[]; predicate?: ItemsPredicate; indexes?: number[]; } interface ICustomCommon { remove?: number[]; removeBwd?: number[]; removeFwd?: number[]; useIndexes?: boolean; text?: string; indexToRemove?: number; size?: number; increase?: boolean; indexToReload?: number; } interface ICustomFlush { text: string; fixRight: boolean; first: number; last: number; } interface ICustomBreak { predicate: unknown; } interface ICustomBoth { text: string; toRemove: number[]; increase?: boolean; result: { min: number; max: number; }; } const configList: TestBedConfig<ICustom>[] = [{ datasourceSettings: { startIndex: 1, bufferSize: 5, padding: 0.2, itemSize: 20 }, custom: { remove: [3, 4, 5] } }, { datasourceSettings: { startIndex: 55, bufferSize: 8, padding: 1, itemSize: 20 }, custom: { remove: [54, 55, 56, 57, 58] } }, { datasourceSettings: { startIndex: 10, bufferSize: 5, padding: 0.2, itemSize: 20 }, custom: { remove: [7, 8, 9] } }].map(config => ({ ...config, templateSettings: { viewportHeight: 100 }, datasourceClass: getDatasourceClassForRemovals({ settings: config.datasourceSettings, common: { limits: { min: -99, max: 100 } }, }) })); const configListInterrupted: TestBedConfig<ICustomCommon>[] = [{ ...configList[0], custom: { remove: [2, 3, 5, 6] } }, { ...configList[1], custom: { remove: [54, 56, 57, 58] } }]; const configListIncrease = configList.map(config => ({ ...config, custom: { ...config.custom, increase: true } })); const configListIndexes = [ configList[0], configListInterrupted[1], configListIncrease[2] ].map(config => ({ ...config, custom: { ...config.custom, useIndexes: true } })); const configListEmpty: TestBedConfig<ICustom>[] = [{ ...configList[0], custom: { ...configList[0].custom, predicate: (({ $index }) => $index > 999) } }, { ...configList[1], custom: { ...configList[1].custom, indexes: [999] } }]; const configListBad: TestBedConfig<ICustomBreak>[] = [{ ...configList[0], custom: { ...configList[0].custom, predicate: null } }, { ...configList[1], custom: { ...configList[1].custom, predicate: () => null } }, { ...configList[0], custom: { ...configList[0].custom, predicate: (_x: number, _y: number) => null } }]; const baseConfigOut = { ...configList[0], datasourceSettings: { ...configList[0].datasourceSettings, startIndex: 1, minIndex: -99, maxIndex: 100 } }; baseConfigOut.datasourceClass = getDatasourceClassForRemovals({ settings: baseConfigOut.datasourceSettings }); const configListOutFixed: TestBedConfig<ICustomCommon>[] = [{ ...baseConfigOut, custom: { remove: [51, 52, 53, 54, 55], useIndexes: true, text: 'forward' } }, { ...baseConfigOut, custom: { remove: [-51, -52, -53, -54, -55], useIndexes: true, text: 'backward' }, }, { ...baseConfigOut, custom: { removeBwd: [-51, -52, -53, -54, -55], removeFwd: [51, 52, 53, 54, 55], useIndexes: true, text: 'backward and forward' } }]; const configListDynamicBuffer: TestBedConfig<ICustomCommon>[] = [{ datasourceSettings: { startIndex: 10, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.5, sizeStrategy: SizeStrategy.Average }, custom: { indexToRemove: 11, size: 100, increase: false } }, { datasourceSettings: { startIndex: 11, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.5, sizeStrategy: SizeStrategy.Frequent }, custom: { indexToRemove: 9, size: 100, increase: false } }, { datasourceSettings: { startIndex: 10, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.5, sizeStrategy: SizeStrategy.Average }, custom: { indexToRemove: 11, size: 100, increase: true } }, { datasourceSettings: { startIndex: 11, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.5, sizeStrategy: SizeStrategy.Frequent }, custom: { indexToRemove: 9, size: 100, increase: true } }].map(config => ({ ...config, templateSettings: { viewportHeight: 100, dynamicSize: 'size' }, datasourceClass: getDatasourceClassForRemovals({ settings: config.datasourceSettings }) })); const configListDynamicVirtual: TestBedConfig<ICustomCommon>[] = [{ datasourceSettings: { startIndex: 20, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.5, sizeStrategy: SizeStrategy.Average }, datasourceDevSettings: { cacheOnReload: true }, custom: { indexToReload: 2, indexToRemove: 20, size: 100, increase: false } }, { datasourceSettings: { startIndex: 1, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.5, sizeStrategy: SizeStrategy.Frequent }, datasourceDevSettings: { cacheOnReload: true }, custom: { indexToReload: 15, indexToRemove: 1, size: 100, increase: false } }, { datasourceSettings: { startIndex: 20, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.5, sizeStrategy: SizeStrategy.Average }, datasourceDevSettings: { cacheOnReload: true }, custom: { indexToReload: 2, indexToRemove: 20, size: 100, increase: true } }, { datasourceSettings: { startIndex: 1, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.5, sizeStrategy: SizeStrategy.Frequent }, datasourceDevSettings: { cacheOnReload: true }, custom: { indexToReload: 15, indexToRemove: 1, size: 100, increase: true } }].map(config => ({ ...config, templateSettings: { viewportHeight: 100, dynamicSize: 'size' }, datasourceClass: getDatasourceClassForRemovals({ settings: config.datasourceSettings, devSettings: config.datasourceDevSettings }) })); const configListFlush: TestBedConfig<ICustomFlush>[] = [{ datasourceSettings: { startIndex: 1, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.5 }, custom: { text: 'bof', fixRight: false, first: 1, last: 8 } }, { datasourceSettings: { startIndex: 1, minIndex: 1, maxIndex: 15, bufferSize: 1, padding: 0.5 }, custom: { text: 'bof and 15 items', fixRight: true, first: 9, last: 15 } }, { datasourceSettings: { startIndex: 1, minIndex: 1, maxIndex: 30, bufferSize: 1, padding: 0.5 }, custom: { text: 'bof and 30 items', fixRight: true, first: 9, last: 16 } }, { datasourceSettings: { startIndex: 20, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.5 }, custom: { text: 'eof', fixRight: false, first: 5, last: 12 } }, { datasourceSettings: { startIndex: 15, minIndex: 1, maxIndex: 15, bufferSize: 1, padding: 0.5 }, custom: { text: 'eof and 15 items', fixRight: true, first: 9, last: 15 } }, { datasourceSettings: { startIndex: 15, minIndex: 1, maxIndex: 25, bufferSize: 1, padding: 0.5 }, custom: { text: 'eof and 25 items', fixRight: true, first: 18, last: 25 } }].map(config => ({ ...config, templateSettings: { viewportHeight: 100 }, datasourceClass: getDatasourceClassForRemovals({ settings: config.datasourceSettings }) })); const configListBufferAndVirtual: TestBedConfig<ICustomBoth>[] = [{ datasourceSettings: { startIndex: 1, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.3 }, custom: { text: 'the bottom virtual item is not reached', toRemove: [1, 20], increase: false, result: { min: 1, max: 18 } } }, { datasourceSettings: { startIndex: 1, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.3 }, custom: { text: 'the bottom virtual item is not reached (increase)', toRemove: [1, 20], increase: true, result: { min: 3, max: 20 } } }, { datasourceSettings: { startIndex: 20, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.3 }, custom: { text: 'the top virtual item is not reached', toRemove: [1, 20], increase: false, result: { min: 1, max: 18 } } }, { datasourceSettings: { startIndex: 20, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.3 }, custom: { text: 'the top virtual item is not reached (increase)', toRemove: [1, 20], increase: true, result: { min: 3, max: 20 } } }, { datasourceSettings: { startIndex: 1, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.3 }, custom: { text: 'the bottom virtual item is not reached, v2', toRemove: [2, 3, 17, 18], increase: false, result: { min: 1, max: 16 } } }, { datasourceSettings: { startIndex: 1, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.3 }, custom: { text: 'the bottom virtual item is not reached, v2 (increase)', toRemove: [2, 3, 17, 18], increase: true, result: { min: 5, max: 20 } } }, { datasourceSettings: { startIndex: 20, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.3 }, custom: { text: 'the top virtual item is not reached, v2', toRemove: [2, 3, 17, 18], increase: false, result: { min: 1, max: 16 } } }, { datasourceSettings: { startIndex: 20, minIndex: 1, maxIndex: 20, bufferSize: 1, padding: 0.3 }, custom: { text: 'the top virtual item is not reached (increase)', toRemove: [2, 3, 17, 18], increase: true, result: { min: 5, max: 20 } } }].map(config => ({ ...config, templateSettings: { viewportHeight: 100 }, datasourceClass: getDatasourceClassForRemovals({ settings: config.datasourceSettings }) })); const doRemove = async (config: TestBedConfig<ICustomCommon>, misc: Misc, byId = false) => { const { increase, useIndexes, remove, removeBwd, removeFwd } = config.custom; const indexList = remove || [...(removeBwd || []), ...(removeFwd || [])]; const ds = misc.datasource as DatasourceRemover; // remove item from the original datasource ds.remove(indexList, !!increase); // remove items from the UiScroll if (useIndexes) { await misc.adapter.remove({ indexes: indexList, increase }); } else { await misc.adapter.remove({ predicate: item => indexList.some((i: number) => i === (byId ? item.data.id : item.$index) ), increase }); } }; const shouldRemove = (config: TestBedConfig<ICustomCommon>, byId = false): ItFunc => misc => async done => { await misc.relaxNext(); const { size: bufferSizeBeforeRemove, minIndex, maxIndex, absMinIndex, absMaxIndex } = misc.scroller.buffer; const { remove, increase } = config.custom; const indexList = remove as number[]; const viewportSizeBeforeRemove = misc.getScrollableSize(); const sizeToRemove = indexList.length * misc.getItemSize(); const deltaSize = viewportSizeBeforeRemove - sizeToRemove; const loopPendingSub = misc.adapter.loopPending$.subscribe(loopPending => { if (!loopPending) { // when the first loop after the Remove is done const len = indexList.length; const { size, minIndex: min, maxIndex: max, absMinIndex: absMin, absMaxIndex: absMax } = misc.scroller.buffer; expect(size).toEqual(bufferSizeBeforeRemove - len); expect(min).toBe(minIndex + (increase ? len : 0)); expect(max).toBe(maxIndex - (increase ? 0 : len)); expect(absMin).toBe(absMinIndex + (increase ? len : 0)); expect(absMax).toBe(absMaxIndex - (increase ? 0 : len)); expect(deltaSize).toEqual(misc.getScrollableSize()); loopPendingSub.unsubscribe(); } }); await doRemove(config, misc, byId); const { firstIndex, lastIndex, items } = misc.scroller.buffer; if (!isNaN(firstIndex) && !isNaN(lastIndex)) { // check all items contents items.forEach(({ $index, data: { id } }) => { const diff = indexList.reduce((acc: number, index: number) => acc + (increase ? (id < index ? -1 : 0) : (id > index ? 1 : 0)), 0 ); expect(misc.checkElementContent($index, $index + diff)).toEqual(true); }); } done(); }; const shouldSkip: ItFuncConfig<ICustom> = config => misc => async done => { await misc.relaxNext(); const innerLoopCount = misc.innerLoopCount; const { predicate, indexes } = config.custom; if (predicate) { await misc.adapter.remove({ predicate }); } else if (indexes) { await misc.adapter.remove({ indexes }); } expect(misc.workflow.cyclesDone).toEqual(1); expect(misc.innerLoopCount).toEqual(innerLoopCount); expect(misc.workflow.errors.length).toEqual(0); done(); }; const shouldBreak: ItFuncConfig<ICustomBreak> = config => misc => async done => { await misc.relaxNext(); const innerLoopCount = misc.innerLoopCount; const predicate = config.custom.predicate as ItemsPredicate; // call remove with wrong predicate await misc.adapter.remove({ predicate }); expect(misc.workflow.cyclesDone).toEqual(1); expect(misc.innerLoopCount).toEqual(innerLoopCount); expect(misc.workflow.errors.length).toEqual(1); expect(misc.workflow.errors[0].process).toContain('remove'); done(); }; const shouldRemoveVirtual: ItFuncConfig<ICustomCommon> = config => misc => async done => { const minIndex = config.datasourceSettings.minIndex as number; const maxIndex = config.datasourceSettings.maxIndex as number; const itemSize = config.datasourceSettings.itemSize as number; const { remove, removeBwd, removeFwd } = config.custom; const indexList: number[] = remove || [...(removeBwd || []), ...(removeFwd || [])]; await misc.relaxNext(); const { $index: indexFirst, data: { id: idFirst } } = misc.adapter.firstVisible; await doRemove(config, misc); const size = (maxIndex - minIndex + 1 - indexList.length) * itemSize; const shift = indexList.reduce((acc: number, i) => acc + (i < indexFirst ? 1 : 0), 0); expect(misc.scroller.viewport.getScrollableSize()).toBe(size); expect(misc.adapter.firstVisible.$index).toBe(indexFirst - shift); expect(misc.adapter.firstVisible.data.id).toBe(idFirst); // let's scroll to the first row before the removed const min = Math.min(...(removeBwd || remove || [])); const prev = min - 1; const scrollPosition = Math.abs(minIndex - prev) * itemSize; misc.adapter.fix({ scrollPosition }); await misc.relaxNext(); expect(misc.adapter.firstVisible.$index).toBe(prev); expect(misc.checkElementContent(prev, prev)).toBe(true); expect(misc.checkElementContent(min, min + (removeBwd || remove || []).length)).toBe(true); // check if the very last row had been shifted misc.adapter.fix({ scrollPosition: Infinity }); await misc.relaxNext(); expect(misc.adapter.lastVisible.$index).toBe(maxIndex - indexList.length); expect(misc.checkElementContent(maxIndex - indexList.length, maxIndex)).toBe(true); expect(misc.scroller.viewport.getScrollableSize()).toBe(size); done(); }; const shouldRemoveDynamicSize: ItFuncConfig<ICustomCommon> = config => misc => async done => { const { indexToReload, size, increase } = config.custom; const indexToRemove = config.custom.indexToRemove as number; const minIndex = config.datasourceSettings.minIndex as number; const maxIndex = config.datasourceSettings.maxIndex as number; const ds = misc.datasource as DatasourceRemover; const finalSize = getDynamicSumSize(minIndex, maxIndex) - getDynamicSizeByIndex(indexToRemove); // set DS sizes ds.setSizes(getDynamicSizeByIndex); ds.data[indexToRemove - minIndex].size = size; await misc.relaxNext(); if (Number.isInteger(indexToReload)) { await misc.adapter.reload(indexToReload); } // remove item from DS and Scroller const { $index, data: { id } } = misc.adapter.firstVisible; const { defaultSize } = misc.scroller.buffer; ds.remove([indexToRemove], !!increase); await misc.adapter.remove({ indexes: [indexToRemove], increase }); let shift = 0; if (increase && indexToRemove > $index) { shift = 1; } else if (!increase && indexToRemove < $index) { shift = -1; } expect(misc.adapter.firstVisible.$index).toBe($index + shift); expect(misc.adapter.firstVisible.data.id).toBe(id); if (misc.scroller.settings.sizeStrategy === SizeStrategy.Average) { expect(misc.scroller.buffer.defaultSize).not.toBe(defaultSize); } await misc.scrollMinRelax(); await misc.scrollToIndexRecursively(maxIndex - (increase ? 0 : 1)); expect(misc.getScrollableSize()).toBe(finalSize); done(); }; const shouldFlush: ItFuncConfig<ICustomFlush> = config => misc => async done => { const { adapter, scroller: { state, buffer } } = misc; const { first, last, fixRight } = config.custom; await misc.relaxNext(); const ds = misc.datasource as DatasourceRemover; ds.remove(buffer.items.map(({ $index }) => $index), fixRight); await adapter.remove({ predicate: (_item) => true, increase: fixRight }); expect(misc.workflow.cyclesDone).toEqual(2); expect(state.cycle.innerLoop.count).toBeGreaterThan(1); expect(buffer.firstIndex).toEqual(first); expect(buffer.lastIndex).toEqual(last); done(); }; const shouldRemoveInBufferAndVirtual: ItFuncConfig<ICustomBoth> = config => misc => async done => { const { adapter, scroller: { buffer } } = misc; const { toRemove, increase, result } = config.custom; const ds = misc.datasource as DatasourceRemover; await misc.relaxNext(); ds.remove(toRemove, !!increase); await adapter.remove({ indexes: toRemove, increase }); expect(buffer.absMinIndex).toEqual(result.min); expect(buffer.absMaxIndex).toEqual(result.max); done(); }; describe('Adapter Remove Spec', () => { describe('Buffer', () => { configList.forEach(config => makeTest({ config, title: 'should remove by index', it: shouldRemove(config) }) ); configList.forEach(config => makeTest({ config, title: 'should remove by id', it: shouldRemove(config, true) }) ); configListInterrupted.forEach(config => makeTest({ config, title: 'should remove portion of non-continuous indexes', it: shouldRemove(config) }) ); configListIncrease.forEach(config => makeTest({ config, title: 'should increase indexes before removed items', it: shouldRemove(config) }) ); configListIndexes.forEach(config => makeTest({ config, title: 'should remove using "indexes" option', it: shouldRemove(config) }) ); }); describe('Empty', () => { configListEmpty.forEach(config => makeTest({ config, title: `should not remove due to empty ${config.custom.predicate ? 'predicate' : 'indexes'}`, it: shouldSkip(config) }) ); configListBad.forEach(config => makeTest({ config, title: 'should break due to wrong predicate', it: shouldBreak(config) }) ); }); describe('Virtual', () => { configListOutFixed.forEach(config => makeTest({ config, title: `should remove fix-sized items out of buffer (${config.custom.text})`, it: shouldRemoveVirtual(config) }) ); }); describe('Dynamic size', () => { configListDynamicBuffer.forEach(config => makeTest({ config, title: 'should remove dynamic-sized items from buffer' + (config.custom.increase ? ' (increase)' : ''), it: shouldRemoveDynamicSize(config) }) ); configListDynamicVirtual.forEach(config => makeTest({ config, title: 'should remove dynamic-sized items out of buffer', it: shouldRemoveDynamicSize(config) }) ); }); describe('Flush', () => { configListFlush.forEach(config => makeTest({ config, title: `should continue the Workflow if ${config.custom.text}${config.custom.fixRight ? ' (increase)' : ''}`, it: shouldFlush(config) }) ); }); describe('Buffer and Virtual', () => { configListBufferAndVirtual.forEach(config => makeTest({ config, title: `should remove in-buffer and virtual items when ${config.custom.text}`, it: shouldRemoveInBufferAndVirtual(config) }) ); }); });
the_stack
export default { // Number formatting options. // // Please check with the local standards which separator is accepted to be // used for separating decimals, and which for thousands. "_decimalSeparator": ",", "_thousandSeparator": ".", // Suffixes for numbers // When formatting numbers, big or small numers might be reformatted to // shorter version, by applying a suffix. // // For example, 1000000 might become "1m". // Or 1024 might become "1KB" if we're formatting byte numbers. // // This section defines such suffixes for all such cases. "_big_number_suffix_3": "k", "_big_number_suffix_6": "M", "_big_number_suffix_9": "G", "_big_number_suffix_12": "T", "_big_number_suffix_15": "P", "_big_number_suffix_18": "E", "_big_number_suffix_21": "Z", "_big_number_suffix_24": "Y", "_small_number_suffix_3": "m", "_small_number_suffix_6": "μ", "_small_number_suffix_9": "n", "_small_number_suffix_12": "p", "_small_number_suffix_15": "f", "_small_number_suffix_18": "a", "_small_number_suffix_21": "z", "_small_number_suffix_24": "y", "_byte_suffix_B": "B", "_byte_suffix_KB": "KB", "_byte_suffix_MB": "MB", "_byte_suffix_GB": "GB", "_byte_suffix_TB": "TB", "_byte_suffix_PB": "PB", // Default date formats for various periods. // // This should reflect official or de facto formatting universally accepted // in the country translation is being made for // Available format codes here: // https://www.amcharts.com/docs/v5/concepts/formatters/formatting-dates/#Format_codes // // This will be used when formatting date/time for particular granularity, // e.g. "_date_hour" will be shown whenever we need to show time as hours. "_date_millisecond": "mm:ss SSS", "_date_second": "HH:mm:ss", "_date_minute": "HH:mm", "_date_hour": "HH:mm", "_date_day": "MMM dd", "_date_week": "ww", "_date_month": "MMM", "_date_year": "yyyy", // Default duration formats for various base units. // // This will be used by DurationFormatter to format numeric values into // duration. // // Notice how each duration unit comes in several versions. This is to ensure // that each base unit is shown correctly. // // For example, if we have baseUnit set to "second", meaning our duration is // in seconds. // // If we pass in `50` to formatter, it will know that we have just 50 seconds // (less than a minute) so it will use format in `"_duration_second"` ("ss"), // and the formatted result will be in like `"50"`. // // If we pass in `70`, which is more than a minute, the formatter will switch // to `"_duration_second_minute"` ("mm:ss"), resulting in "01:10" formatted // text. "_duration_millisecond": "SSS", "_duration_millisecond_second": "ss.SSS", "_duration_millisecond_minute": "mm:ss SSS", "_duration_millisecond_hour": "hh:mm:ss SSS", "_duration_millisecond_day": "d'd' mm:ss SSS", "_duration_millisecond_week": "d'd' mm:ss SSS", "_duration_millisecond_month": "M'm' dd'd' mm:ss SSS", "_duration_millisecond_year": "y'y' MM'm' dd'd' mm:ss SSS", "_duration_second": "ss", "_duration_second_minute": "mm:ss", "_duration_second_hour": "hh:mm:ss", "_duration_second_day": "d'd' hh:mm:ss", "_duration_second_week": "d'd' hh:mm:ss", "_duration_second_month": "M'm' dd'd' hh:mm:ss", "_duration_second_year": "y'y' MM'm' dd'd' hh:mm:ss", "_duration_minute": "mm", "_duration_minute_hour": "hh:mm", "_duration_minute_day": "d'd' hh:mm", "_duration_minute_week": "d'd' hh:mm", "_duration_minute_month": "M'm' dd'd' hh:mm", "_duration_minute_year": "y'y' MM'm' dd'd' hh:mm", "_duration_hour": "hh'h'", "_duration_hour_day": "d'd' hh'h'", "_duration_hour_week": "d'd' hh'h'", "_duration_hour_month": "M'm' dd'd' hh'h'", "_duration_hour_year": "y'y' MM'm' dd'd' hh'h'", "_duration_day": "d'd'", "_duration_day_week": "d'd'", "_duration_day_month": "M'm' dd'd'", "_duration_day_year": "y'y' MM'm' dd'd'", "_duration_week": "w'w'", "_duration_week_month": "w'w'", "_duration_week_year": "w'w'", "_duration_month": "M'm'", "_duration_month_year": "y'y' MM'm'", "_duration_year": "y'y'", // Era translations "_era_ad": "dC", "_era_bc": "aC", // Day part, used in 12-hour formats, e.g. 5 P.M. // Please note that these come in 3 variants: // * one letter (e.g. "A") // * two letters (e.g. "AM") // * two letters with dots (e.g. "A.M.") // // All three need to to be translated even if they are all the same. Some // users might use one, some the other. "A": "a. m.", "P": "p. m.", "AM": "a. m.", "PM": "p. m.", "A.M.": "a. m.", "P.M.": "p. m.", // Date-related stuff. // // When translating months, if there's a difference, use the form which is // best for a full date, e.g. as you would use it in "2018 January 1". // // Note that May is listed twice. This is because in English May is the same // in both long and short forms, while in other languages it may not be the // case. Translate "May" to full word, while "May(short)" to shortened // version. // // Should month names and weekdays be capitalized or not? // // Rule of thumb is this: if the names should always be capitalized, // regardless of name position within date ("January", "21st January 2018", // etc.) use capitalized names. Otherwise enter all lowercase. // // The date formatter will automatically capitalize names if they are the // first (or only) word in resulting date. "January": "de gener", "February": "de febrer", "March": "de març", "April": "d’abril", "May": "de maig", "June": "de juny", "July": "de juliol", "August": "d’agost", "September": "de setembre", "October": "d’octubre", "November": "de novembre", "December": "de desembre", "Jan": "de gen.", "Feb": "de febr.", "Mar": "de març", "Apr": "d’abr.", "May(short)": "de maig", "Jun": "de juny", "Jul": "de jul.", "Aug": "d’ag.", "Sep": "de set.", "Oct": "d’oct.", "Nov": "de nov.", "Dec": "de des.", // Weekdays. "Sunday": "diumenge", "Monday": "dilluns", "Tuesday": "dimarts", "Wednesday": "dimecres", "Thursday": "dijous", "Friday": "divendres", "Saturday": "dissabte", "Sun": "dg.", "Mon": "dl.", "Tue": "dt.", "Wed": "dc.", "Thu": "dj.", "Fri": "dv.", "Sat": "ds.", // Date ordinal function. // // This is used when adding number ordinal when formatting days in dates. // // E.g. "January 1st", "February 2nd". // // The function accepts day number, and returns a string to be added to the // day, like in default English translation, if we pass in 2, we will receive // "nd" back. "_dateOrd": function(day: number): string { let res = "th"; if ((day < 11) || (day > 13)) { switch (day % 10) { case 1: res = "st"; break; case 2: res = "nd"; break; case 3: res = "rd" break; } } return res; }, // Various chart controls. // Shown as a tooltip on zoom out button. "Zoom Out": "Zoom", // Timeline buttons "Play": "Reprodueix", "Stop": "Parada", // Chart's Legend screen reader title. "Legend": "Llegenda", // Legend's item screen reader indicator. "Press ENTER to toggle": "", // Shown when the chart is busy loading something. "Loading": "S'està carregant", // Shown as the first button in the breadcrumb navigation, e.g.: // Home > First level > ... "Home": "Inici", // Chart types. // Those are used as default screen reader titles for the main chart element // unless developer has set some more descriptive title. "Chart": "", "Serial chart": "", "X/Y chart": "", "Pie chart": "", "Gauge chart": "", "Radar chart": "", "Sankey diagram": "", "Flow diagram": "", "Chord diagram": "", "TreeMap chart": "", "Sliced chart": "", // Series types. // Used to name series by type for screen readers if they do not have their // name set. "Series": "", "Candlestick Series": "", "OHLC Series": "", "Column Series": "", "Line Series": "", "Pie Slice Series": "", "Funnel Series": "", "Pyramid Series": "", "X/Y Series": "", // Map-related stuff. "Map": "", "Press ENTER to zoom in": "", "Press ENTER to zoom out": "", "Use arrow keys to zoom in and out": "", "Use plus and minus keys on your keyboard to zoom in and out": "", // Export-related stuff. // These prompts are used in Export menu labels. // // "Export" is the top-level menu item. // // "Image", "Data", "Print" as second-level indicating type of export // operation. // // Leave actual format untranslated, unless you absolutely know that they // would convey more meaning in some other way. "Export": "Imprimeix", "Image": "Imatge", "Data": "Dades", "Print": "Imprimeix", "Press ENTER to open": "", "Press ENTER to print.": "", "Press ENTER to export as %1.": "", "(Press ESC to close this message)": "", "Image Export Complete": "", "Export operation took longer than expected. Something might have gone wrong.": "", "Saved from": "", "PNG": "", "JPG": "", "GIF": "", "SVG": "", "PDF": "", "JSON": "", "CSV": "", "XLSX": "", "HTML": "", // Scrollbar-related stuff. // // Scrollbar is a control which can zoom and pan the axes on the chart. // // Each scrollbar has two grips: left or right (for horizontal scrollbar) or // upper and lower (for vertical one). // // Prompts change in relation to whether Scrollbar is vertical or horizontal. // // The final section is used to indicate the current range of selection. "Use TAB to select grip buttons or left and right arrows to change selection": "", "Use left and right arrows to move selection": "", "Use left and right arrows to move left selection": "", "Use left and right arrows to move right selection": "", "Use TAB select grip buttons or up and down arrows to change selection": "", "Use up and down arrows to move selection": "", "Use up and down arrows to move lower selection": "", "Use up and down arrows to move upper selection": "", "From %1 to %2": "De %1 a %2", "From %1": "De %1", "To %1": "A %1", // Data loader-related. "No parser available for file: %1": "", "Error parsing file: %1": "", "Unable to load file: %1": "", "Invalid date": "", };
the_stack
import { ObservableLike } from "observable-fns" import React from "react" import { Asset, Horizon, ServerApi } from "stellar-sdk" import { Account } from "~App/contexts/accounts" import { createEmptyAccountData, AccountData, BalanceLine } from "../lib/account" import { FixedOrderbookRecord } from "../lib/orderbook" import { stringifyAsset } from "../lib/stellar" import { mapSuspendables } from "../lib/suspense" import { CollectionPage } from "~Workers/net-worker/stellar-network" import { accountDataCache, accountOpenOrdersCache, accountTransactionsCache, orderbookCache, resetNetworkCaches, OfferHistory, TransactionHistory } from "./_caches" import { useHorizonURLs } from "./stellar" import { useDebouncedState, useForceRerender } from "./util" import { useNetWorker } from "./workers" function useDataSubscriptions<DataT, UpdateT>( reducer: (prev: DataT, update: UpdateT) => DataT, items: Array<{ get(): DataT; set(value: DataT): void; observe(): ObservableLike<UpdateT> }> ): DataT[] { const unfinishedFetches: Array<Promise<DataT>> = [] const [, setRefreshCounter] = useDebouncedState(0, 100) const currentDataSets = mapSuspendables(items, item => item.get()) if (unfinishedFetches.length > 0) { throw unfinishedFetches.length === 1 ? unfinishedFetches[0] : Promise.all(unfinishedFetches) } React.useEffect(() => { items.map(item => { return item.observe().subscribe({ next(update) { item.set(reducer(item.get(), update)) setRefreshCounter(counter => counter + 1) }, error(error) { // tslint:disable-next-line console.error(error) } }) }) return () => { // Don't unsubscribe to prevent missing updates (related to #1088) // subscriptions.forEach(subscription => unsubscribe(subscription)) } }, [reducer, items, setRefreshCounter]) return currentDataSets as DataT[] } function useDataSubscription<DataT, UpdateT>( reducer: (prev: DataT, update: UpdateT) => DataT, get: () => DataT, set: (value: DataT) => void, observe: () => ObservableLike<UpdateT> ): DataT { const items = React.useMemo(() => [{ get, set, observe }], [get, set, observe]) return useDataSubscriptions(reducer, items)[0] } function applyAccountDataUpdate(prev: AccountData, next: AccountData): AccountData { // We ignore `prev` here return next } export function useLiveAccountDataSet(accountIDs: string[], testnet: boolean): AccountData[] { const horizonURLs = useHorizonURLs(testnet) const netWorker = useNetWorker() const items = React.useMemo( () => accountIDs.map(accountID => { const selector = [horizonURLs, accountID] as const const prepare = (account: Horizon.AccountResponse | null) => { return account ? { ...account, balances: account.balances.filter( (balance): balance is BalanceLine => balance.asset_type !== "liquidity_pool_shares" ), data_attr: account.data } : createEmptyAccountData(accountID) } return { get() { return ( accountDataCache.get(selector) || accountDataCache.suspend(selector, () => netWorker.fetchAccountData(horizonURLs, accountID).then(prepare)) ) }, set(updated: AccountData) { accountDataCache.set(selector, updated) }, observe() { return accountDataCache.observe(selector, () => netWorker.subscribeToAccount(horizonURLs, accountID).map(prepare) ) } } }), [accountIDs, horizonURLs, netWorker] ) return useDataSubscriptions(applyAccountDataUpdate, items) } export function useLiveAccountData(accountID: string, testnet: boolean): AccountData { return useLiveAccountDataSet([accountID], testnet)[0] } function applyAccountOffersUpdate(prev: OfferHistory, next: ServerApi.OfferRecord[]): OfferHistory { // We ignore `prev` here return { olderOffersAvailable: prev.olderOffersAvailable, offers: next } } export function useLiveAccountOffers(accountID: string, testnet: boolean): OfferHistory { const horizonURLs = useHorizonURLs(testnet) const netWorker = useNetWorker() const { get, set, observe } = React.useMemo(() => { const selector = [horizonURLs, accountID] as const const limit = 10 return { get() { return ( accountOpenOrdersCache.get(selector) || accountOpenOrdersCache.suspend(selector, async () => { const page = await netWorker.fetchAccountOpenOrders(horizonURLs, accountID, { limit, order: "desc" }) const offers = page._embedded.records return { olderOffersAvailable: offers.length === limit, offers } }) ) }, set(updated: OfferHistory) { // reset olderOffersAvailable because updated history will only have the 10 most recent offers const olderOffersAvailable = updated.offers.length === limit accountOpenOrdersCache.set(selector, { ...updated, olderOffersAvailable }) }, observe() { return netWorker.subscribeToOpenOrders(horizonURLs, accountID) } } }, [accountID, horizonURLs, netWorker]) return useDataSubscription(applyAccountOffersUpdate, get, set, observe) } export function useOlderOffers(accountID: string, testnet: boolean) { const forceRerender = useForceRerender() const horizonURLs = useHorizonURLs(testnet) const netWorker = useNetWorker() const fetchMoreOffers = React.useCallback( async function fetchMoreOffers() { let fetched: CollectionPage<ServerApi.OfferRecord> const selector = [horizonURLs, accountID] as const const history = accountOpenOrdersCache.get(selector) const limit = 10 const prevOffers = history?.offers || [] if (prevOffers.length > 0) { fetched = await netWorker.fetchAccountOpenOrders(horizonURLs, accountID, { cursor: prevOffers[prevOffers.length - 1].paging_token, limit, order: "desc" }) } else { fetched = await netWorker.fetchAccountOpenOrders(horizonURLs, accountID, { limit, order: "desc" }) } const fetchedOffers: ServerApi.OfferRecord[] = fetched._embedded.records accountOpenOrdersCache.set( selector, { // not an accurate science right now… olderOffersAvailable: fetchedOffers.length === limit, offers: [...(accountOpenOrdersCache.get(selector)?.offers || []), ...fetchedOffers] }, true ) // hacky… forceRerender() }, [accountID, forceRerender, horizonURLs, netWorker] ) return fetchMoreOffers } type EffectHandler = (account: Account, effect: ServerApi.EffectRecord) => void export function useLiveAccountEffects(accounts: Account[], handler: EffectHandler) { const netWorker = useNetWorker() const mainnetHorizonURLs = useHorizonURLs(false) const testnetHorizonURLs = useHorizonURLs(true) React.useEffect(() => { const subscriptions = accounts.map(account => { const horizonURLs = account.testnet ? testnetHorizonURLs : mainnetHorizonURLs const observable = netWorker.subscribeToAccountEffects(horizonURLs, account.accountID) const subscription = observable.subscribe(effect => effect && handler(account, effect)) return subscription }) return () => subscriptions.forEach(subscription => subscription.unsubscribe()) }, [accounts, handler, mainnetHorizonURLs, netWorker, testnetHorizonURLs]) } function applyOrderbookUpdate(prev: FixedOrderbookRecord, next: FixedOrderbookRecord) { // Ignoring `prev` here return next } export function useLiveOrderbook(selling: Asset, buying: Asset, testnet: boolean): FixedOrderbookRecord { const horizonURLs = useHorizonURLs(testnet) const netWorker = useNetWorker() const { get, set, observe } = React.useMemo(() => { const selector = [horizonURLs, selling, buying] as const return { get() { return ( orderbookCache.get(selector) || orderbookCache.suspend(selector, () => netWorker.fetchOrderbookRecord(horizonURLs, stringifyAsset(selling), stringifyAsset(buying)) ) ) }, set(updated: FixedOrderbookRecord) { orderbookCache.set(selector, updated) }, observe() { return netWorker.subscribeToOrderbook(horizonURLs, stringifyAsset(selling), stringifyAsset(buying)) } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [stringifyAsset(buying), horizonURLs, netWorker, stringifyAsset(selling)]) return useDataSubscription(applyOrderbookUpdate, get, set, observe) } const txsMatch = (a: Horizon.TransactionResponse, b: Horizon.TransactionResponse): boolean => { return a.source_account === b.source_account && a.source_account_sequence === b.source_account_sequence } function applyAccountTransactionsUpdate( prev: TransactionHistory, update: Horizon.TransactionResponse ): TransactionHistory { if (prev.transactions.some(tx => txsMatch(tx, update))) { return prev } else { return { ...prev, transactions: [update, ...prev.transactions] } } } export function useLiveRecentTransactions(accountID: string, testnet: boolean): TransactionHistory { const horizonURLs = useHorizonURLs(testnet) const netWorker = useNetWorker() const { get, set, observe } = React.useMemo(() => { const limit = 15 const selector = [horizonURLs, accountID] as const return { get() { return ( accountTransactionsCache.get(selector) || accountTransactionsCache.suspend(selector, async () => { const page = await netWorker.fetchAccountTransactions(horizonURLs, accountID, { emptyOn404: true, limit, order: "desc" }) const transactions = page._embedded.records return { // not an accurate science right now… olderTransactionsAvailable: transactions.length === limit, transactions } }) ) }, set(updated: TransactionHistory) { accountTransactionsCache.set(selector, updated) }, observe() { return netWorker.subscribeToAccountTransactions(horizonURLs, accountID) } } }, [accountID, horizonURLs, netWorker]) return useDataSubscription(applyAccountTransactionsUpdate, get, set, observe) } export function useOlderTransactions(accountID: string, testnet: boolean) { const forceRerender = useForceRerender() const horizonURLs = useHorizonURLs(testnet) const netWorker = useNetWorker() const fetchMoreTransactions = React.useCallback( async function fetchMoreTransactions() { let fetched: CollectionPage<Horizon.TransactionResponse> const selector = [horizonURLs, accountID] as const const history = accountTransactionsCache.get(selector) const limit = 15 const prevTransactions = history?.transactions || [] if (prevTransactions.length > 0) { fetched = await netWorker.fetchAccountTransactions(horizonURLs, accountID, { emptyOn404: true, cursor: prevTransactions[prevTransactions.length - 1].paging_token, limit: 15, order: "desc" }) } else { fetched = await netWorker.fetchAccountTransactions(horizonURLs, accountID, { emptyOn404: true, limit, order: "desc" }) } const fetchedTransactions: Horizon.TransactionResponse[] = fetched._embedded.records accountTransactionsCache.set( selector, { // not an accurate science right now… olderTransactionsAvailable: fetchedTransactions.length === limit, transactions: [ ...(accountTransactionsCache.get(selector)?.transactions || []), ...fetchedTransactions.filter(record => !prevTransactions.some(prevTx => txsMatch(prevTx, record))) ] }, true ) // hacky… forceRerender() }, [accountID, forceRerender, horizonURLs, netWorker] ) return fetchMoreTransactions } export function useNetworkCacheReset() { return resetNetworkCaches }
the_stack
import util from 'util'; import _ from 'lodash'; import * as common from './common'; import { wrapError } from '../utils'; import { TeamMember } from './teamMember'; import { TeamRepositoryPermission } from './teamRepositoryPermission'; import { IApprovalProvider } from '../entities/teamJoinApproval/approvalProvider'; import { TeamJoinApprovalEntity } from '../entities/teamJoinApproval/teamJoinApproval'; import { AppPurpose } from '../github'; import { CacheDefault, getMaxAgeSeconds, getPageSize, Organization } from '.'; import { IOperationsInstance, IPurposefulGetAuthorizationHeader, TeamJsonFormat, throwIfNotCapable, IOperationsUrls, CoreCapability, ICacheOptions, throwIfNotGitHubCapable, IPagedCacheOptions, IGetAuthorizationHeader, IUpdateTeamMembershipOptions, GitHubTeamRole, ITeamMembershipRoleState, IIsMemberOptions, OrganizationMembershipState, IGetMembersOptions, ICacheOptionsPageLimiter, IGetTeamRepositoriesOptions, GitHubRepositoryType, IOperationsProviders } from '../interfaces'; import { validateGitHubLogin, ErrorHelper } from '../transitional'; const teamPrimaryProperties = [ 'id', 'name', 'slug', 'description', 'members_count', 'repos_count', 'created_at', 'updated_at', ]; const teamSecondaryProperties = [ 'privacy', 'permission', 'organization', 'url', 'members_url', 'repositories_url', ]; interface IGetMembersParameters { team_slug: string; org: string; per_page: number; role?: string; pageLimit?: any; } interface IGetRepositoriesParameters { org: string; team_slug: string; per_page: number; pageLimit?: any; } // TODO: cleanup intentional memory leak // MEMORY_LEAK: INTENTIONAL: keep a cache going from ID to slug const memoryIdToSlugStore = new Map<number, string>(); export class Team { public static PrimaryProperties = teamPrimaryProperties; private _organization: Organization; private _operations: IOperationsInstance; private _getAuthorizationHeader: IPurposefulGetAuthorizationHeader; private _id: number; private _slug?: string; private _name?: string; private _created_at?: any; private _updated_at?: any; private _description: string; private _repos_count: any; private _members_count: any; private _detailsEntity?: any; private _ctorEntity?: any; // temp get id(): number { return this._id; } get name(): string { return this._name; } get slug(): string { return this._slug; } get description(): string { return this._description; } get repos_count(): any { return this._repos_count; } get members_count(): any { return this._members_count; } get created_at(): any { return this._created_at; } get updated_at(): any { return this._updated_at; } get organization(): Organization { return this._organization; } constructor(organization: Organization, entity, getAuthorizationHeader: IPurposefulGetAuthorizationHeader, operations: IOperationsInstance) { if (!entity || !entity.id) { throw new Error('Team instantiation requires an incoming entity, or minimum-set entity containing an id property.'); } if (typeof(entity.id) !== 'number') { throw new Error('Team constructor entity.id must be a Number'); } this._organization = organization; // TODO: remove assignKnownFieldsPrefixed concept, use newer field definitions instead? common.assignKnownFieldsPrefixed(this, entity, 'team', teamPrimaryProperties, teamSecondaryProperties); this._getAuthorizationHeader = getAuthorizationHeader; this._operations = operations; this._ctorEntity = entity; } [util.inspect.custom](depth, options) { return `GitHub Team: slug=${this._slug} id=${this.id} org=${this._organization?.name}`; } asJson(format?: TeamJsonFormat) { if (format === TeamJsonFormat.Detailed || format === TeamJsonFormat.Augmented) { const clone = {...this._ctorEntity, ...this._detailsEntity}; // technically will also include `.parent` clone.organization = { login: clone.organization?.login || this.organization.name, id: clone.organization?.id || this.organization.id, }; delete clone.members_url; delete clone.repositories_url; delete clone.cost; delete clone.headers; if (format === TeamJsonFormat.Detailed) { return clone; } // Augment with corporate information clone.corporateMetadata = { isSystemTeam: this.isSystemTeam, isBroadAccessTeam: this.isBroadAccessTeam, }; return clone; } return { id: this.id, slug: this.slug, name: this.name, description: this.description, }; } get baseUrl() { const operations = throwIfNotCapable<IOperationsUrls>(this._operations, CoreCapability.Urls); if (this._organization && (this._slug || this._name)) { return this._organization.baseUrl + 'teams/' + (this._slug || this._name) + '/'; } return operations.baseUrl + 'teams?q=' + this._id; } get absoluteBaseUrl(): string { return `${this._organization.absoluteBaseUrl}teams/${this._slug || this._name}/`; } get nativeUrl() { if (this._organization && this._slug) { return this._organization.nativeManagementUrl + `teams/${this._slug}/`; } // Less ideal fallback return this._organization.nativeManagementUrl + `teams/`; } async ensureName(): Promise<void> { if (this._name && this._slug) { return; } return await this.getDetails(); } async isDeleted(options?: ICacheOptions): Promise<boolean> { try { await this.getDetails(options); } catch (maybeDeletedError) { if (maybeDeletedError && maybeDeletedError.status && maybeDeletedError.status === 404) { return true; } } return false; } async getDetails(options?: ICacheOptions): Promise<any> { options = options || {}; const operations = throwIfNotGitHubCapable(this._operations); const cacheOptions = { maxAgeSeconds: getMaxAgeSeconds(operations, CacheDefault.orgTeamDetailsStaleSeconds, options, 60), backgroundRefresh: false, }; if (options.backgroundRefresh !== undefined) { cacheOptions.backgroundRefresh = options.backgroundRefresh; } const id = this._id; if (!id) { throw new Error('team.id required to retrieve team details'); } // If the details already have been loaded, move along without refreshing // CONSIDER: Either a time-based cache or ability to override the local cached behavior if (this._detailsEntity) { return this._detailsEntity; } const parameters = { org_id: this.organization.id, team_id: id, }; try { const entity = await operations.github.request( this.authorize(AppPurpose.Data), 'GET /organizations/:org_id/team/:team_id', parameters, cacheOptions); this._detailsEntity = entity; // TODO: move beyond setting with this approach common.assignKnownFieldsPrefixed(this, entity, 'team', teamPrimaryProperties, teamSecondaryProperties); return entity; } catch (error) { if (error?.status === 403) { error = new Error(`Error retrieving team details: ${error}`); error.status = 403; throw error; } if (error.status && error.status === 404) { error = new Error(`The GitHub team ID ${id} could not be found`); error.status = 404; throw error; } throw wrapError(error, `Could not get details about team ID ${this._id} in the GitHub organization ${this.organization.name}: ${error.message}`); } } async getChildTeams(options?: IPagedCacheOptions): Promise<Team[]> { options = options || {}; const operations = throwIfNotGitHubCapable(this._operations); const github = operations.github; if (!this.slug) { await this.getDetails(); } const parameters = { org: this.organization.name, per_page: getPageSize(operations), team_slug: this.slug, }; const caching: IPagedCacheOptions = { maxAgeSeconds: getMaxAgeSeconds(operations, CacheDefault.orgTeamsStaleSeconds, options), backgroundRefresh: true, pageRequestDelay: options.pageRequestDelay || null, }; caching.backgroundRefresh = options.backgroundRefresh; const getAuthorizationHeader = this._getAuthorizationHeader.bind(this, AppPurpose.Data) as IGetAuthorizationHeader; const teamEntities = await github.collections.getTeamChildTeams(getAuthorizationHeader, parameters, caching); const teams = common.createInstances<Team>(this, this.organization.teamFromEntity, teamEntities); return teams; } get isBroadAccessTeam(): boolean { const teams = this._organization.broadAccessTeams; // TODO: validating typing here - number or int? if (typeof(this._id) !== 'number') { throw new Error('Team.id must be a number'); } const res = teams.indexOf(this._id); return res >= 0; } get isSystemTeam(): boolean { const systemTeams = this._organization.systemTeamIds; const res = systemTeams.indexOf(this._id); return res >= 0; } delete(): Promise<void> { const operations = throwIfNotGitHubCapable(this._operations); const github = operations.github; const parameters = { org_id: this.organization.id, team_id: this._id, }; // alternate of teams.deleteInOrg return github.requestAsPost(this.authorize(AppPurpose.Operations), 'DELETE /organizations/:org_id/team/:team_id', parameters); } edit(patch: unknown): Promise<void> { const operations = throwIfNotGitHubCapable(this._operations); const github = operations.github; const parameters = { org_id: this.organization.id, team_id: this._id, }; Object.assign({}, patch, parameters); // alternate of teams.editInOrg return github.requestAsPost(this.authorize(AppPurpose.Operations), 'PATCH /organizations/:org_id/team/:team_id', parameters); } removeMembership(username: string): Promise<void> { const operations = throwIfNotGitHubCapable(this._operations); const github = operations.github; const parameters = { org_id: this.organization.id, team_id: this._id, username: validateGitHubLogin(username), }; return github.requestAsPost(this.authorize(AppPurpose.Operations), 'DELETE /organizations/:org_id/team/:team_id/memberships/:username', parameters); } async addMembership(username: string, options?: IUpdateTeamMembershipOptions): Promise<ITeamMembershipRoleState> { const operations = throwIfNotGitHubCapable(this._operations); const github = operations.github; options = options || {}; const role = options.role || GitHubTeamRole.Member; if (!this.slug) { await this.getDetails(); } const parameters = { org: this.organization.name, team_slug: this.slug, username: validateGitHubLogin(username), role, }; const ok = await github.post(this.authorize(AppPurpose.CustomerFacing), 'teams.addOrUpdateMembershipForUserInOrg', parameters); return ok as ITeamMembershipRoleState; } addMaintainer(username: string): Promise<ITeamMembershipRoleState> { return this.addMembership(username, { role: GitHubTeamRole.Maintainer }); } async getMembership(username: string, options: ICacheOptions): Promise<ITeamMembershipRoleState | boolean> { const operations = throwIfNotGitHubCapable(this._operations); options = options || {}; if (!options.maxAgeSeconds) { options.maxAgeSeconds = getMaxAgeSeconds(operations, CacheDefault.orgMembershipDirectStaleSeconds); } // If a background refresh setting is not present, perform a live // lookup with this call. This is the opposite of most of the library's // general behavior. if (options.backgroundRefresh === undefined) { options.backgroundRefresh = false; } const parameters = { org_id: this.organization.id, team_id: this._id, username: validateGitHubLogin(username), }; try { const result = await operations.github.request( this.authorize(AppPurpose.CustomerFacing), 'GET /organizations/:org_id/team/:team_id/memberships/:username', parameters, options); return result; } catch (error) { if (error.status == /* loose */ 404) { return false; } let reason = error.message; if (error.status) { reason += ' ' + error.status; } const wrappedError = wrapError(error, `Trouble retrieving the membership for ${username} in team ${this._id}.`); if (error.status) { wrappedError['status'] = error.status; } throw wrappedError; } } async getMembershipEfficiently(username: string, options?: IIsMemberOptions): Promise<ITeamMembershipRoleState | boolean> { // Hybrid calls are used to check for membership. Since there is // often a relatively fresh cache available of all of the members // of a team, that data source is used first to avoid a unique // GitHub API call. const operations = throwIfNotGitHubCapable(this._operations); // A background cache is used that is slightly more aggressive // than the standard org members list to at least frontload a // refresh of the data. options = options || {}; if (!options.maxAgeSeconds) { options.maxAgeSeconds = getMaxAgeSeconds(operations, CacheDefault.orgMembershipStaleSeconds, null, 60); } const isMaintainer = await this.isMaintainer(username, options); if (isMaintainer) { return { role: GitHubTeamRole.Maintainer, state: OrganizationMembershipState.Active, }; } const isMember = await this.isMember(username); if (isMember) { return { role: GitHubTeamRole.Member, state: OrganizationMembershipState.Active, }; } // Fallback to the standard membership lookup const membershipOptions = { maxAgeSeconds: getMaxAgeSeconds(operations, CacheDefault.orgMembershipDirectStaleSeconds), }; const result = await this.getMembership(username, membershipOptions); if (result === false || (result as ITeamMembershipRoleState).role) { return false; } return result; } async isMaintainer(username: string, options?: ICacheOptions): Promise<boolean> { const isOptions: IIsMemberOptions = Object.assign({}, options); isOptions.role = GitHubTeamRole.Maintainer; const maintainer = await this.isMember(username, isOptions) as GitHubTeamRole; return maintainer === GitHubTeamRole.Maintainer ? true : false; } async isMember(username: string, options?: IIsMemberOptions): Promise<GitHubTeamRole | boolean> { const operations = throwIfNotGitHubCapable(this._operations); options = options || {}; if (!options.maxAgeSeconds) { options.maxAgeSeconds = getMaxAgeSeconds(operations, CacheDefault.orgMembershipStaleSeconds); } const getMembersOptions: IGetMembersOptions = Object.assign({}, options); if (!options.role) { getMembersOptions.role = GitHubTeamRole.Member; } const members = await this.getMembers(getMembersOptions); const expected = username.toLowerCase(); for (let i = 0; i < members.length; i++) { const member = members[i]; if (member.login.toLowerCase() === expected) { return getMembersOptions.role; } } return false; } getMaintainers(options?: ICacheOptionsPageLimiter): Promise<TeamMember[]> { options = options || {}; const operations = throwIfNotGitHubCapable(this._operations); if (!options.maxAgeSeconds) { options.maxAgeSeconds = getMaxAgeSeconds(operations, CacheDefault.teamMaintainersStaleSeconds); } const getMemberOptions: IGetMembersOptions = Object.assign({}, options || {}); getMemberOptions.role = GitHubTeamRole.Maintainer; return this.getMembers(getMemberOptions); } async getMembers(options?: IGetMembersOptions): Promise<TeamMember[]> { options = options || {}; const operations = throwIfNotGitHubCapable(this._operations); const github = operations.github; if (!this.slug) { const cachedSlug = memoryIdToSlugStore.get(Number(this.id)); if (cachedSlug) { this._slug = cachedSlug; } else { console.log('WARN: team.getMembers had to slowly retrieve a slug to perform the call'); await this.getDetails(); // octokit rest v17 requires slug or custom endpoint requests if (this._slug) { memoryIdToSlugStore.set(Number(this.id), this._slug); } } } const parameters: IGetMembersParameters = { team_slug: this.slug, org: this.organization.name, per_page: getPageSize(operations), }; const caching: IPagedCacheOptions = { maxAgeSeconds: getMaxAgeSeconds(operations, CacheDefault.orgMembersStaleSeconds, options), backgroundRefresh: true, }; if (options && options.backgroundRefresh === false) { caching.backgroundRefresh = false; } if (options.role) { parameters.role = options.role; } if (options.pageLimit) { parameters.pageLimit = options.pageLimit; } // CONSIDER: Check the error object, if present, for error.status == /* loose */ 404 to alert/store telemetry on deleted teams try { const teamMembersEntities = await github.collections.getTeamMembers(this.authorize(AppPurpose.Data), parameters, caching); const teamMembers = common.createInstances<TeamMember>(this, this.memberFromEntity, teamMembersEntities); return teamMembers; } catch (error) { if (ErrorHelper.IsNotFound(error)) { // If a previously cached slug is no longer good, remove from the leaky store memoryIdToSlugStore.delete(Number(this.id)); } throw error; } } async getRepositories(options?: IGetTeamRepositoriesOptions): Promise<TeamRepositoryPermission[]> { options = options || {}; const operations = throwIfNotGitHubCapable(this._operations); const github = operations.github; // GitHub does not have a concept of filtering this out so we add it const customTypeFilteringParameter = options.type; if (customTypeFilteringParameter && customTypeFilteringParameter !== GitHubRepositoryType.Sources) { throw new Error(`Custom \'type\' parameter is specified, but at this time only \'sources\' is a valid enum value. Value: ${customTypeFilteringParameter}`); } if (!this.slug) { console.log('WARN: had to request team.slug slowly'); await this.getDetails(); } const parameters: IGetRepositoriesParameters = { org: this.organization.name, team_slug: this.slug, per_page: getPageSize(operations), }; const caching: IPagedCacheOptions = { maxAgeSeconds: getMaxAgeSeconds(operations, CacheDefault.orgMembersStaleSeconds, options), backgroundRefresh: true, }; if (options && options.backgroundRefresh === false) { caching.backgroundRefresh = false; } if (options.pageLimit) { parameters.pageLimit = options.pageLimit; } const entities = await github.collections.getTeamRepos(this.authorize(AppPurpose.Data), parameters, caching); if (customTypeFilteringParameter === 'sources') { // Remove forks (non-sources) _.remove(entities, (repo: any) => { return repo.fork; }); } return common.createInstances<TeamRepositoryPermission>(this, teamRepositoryPermissionsFromEntity, entities); } async getOfficialMaintainers(): Promise<TeamMember[]> { await this.getDetails(); const maintainers = await this.getMaintainers(); if (maintainers.length > 0) { return resolveDirectLinks(maintainers); } const members = await this.organization.sudoersTeam.getMembers(); return resolveDirectLinks(members); } member(id, optionalEntity?) { let entity = optionalEntity || {}; if (!optionalEntity) { entity.id = id; } const member = new TeamMember( this, entity, this._operations); // CONSIDER: Cache any members in the local instance return member; } memberFromEntity(entity) { return this.member(entity.id, entity); } async getApprovals(): Promise<TeamJoinApprovalEntity[]> { const operations = throwIfNotCapable<IOperationsProviders>(this._operations, CoreCapability.Providers); const approvalProvider = operations.providers.approvalProvider as IApprovalProvider; if (!approvalProvider) { throw new Error('No approval provider instance available'); } let pendingApprovals: TeamJoinApprovalEntity[] = null; try { pendingApprovals = await approvalProvider.queryPendingApprovalsForTeam(this.id.toString()); } catch(error) { throw wrapError(error, 'We were unable to retrieve the pending approvals list for this team. There may be a data store problem or temporary outage.'); } return pendingApprovals; } toSimpleJsonObject() { return { id: typeof(this.id) === 'number' ? this.id : parseInt(this.id, 10), name: this.name, slug: this.slug, description: this.description, repos_count: this.repos_count, members_count: this.members_count, created_at: this.created_at, updated_at: this.updated_at, }; } private authorize(purpose: AppPurpose): IGetAuthorizationHeader | string { const getAuthorizationHeader = this._getAuthorizationHeader.bind(this, purpose) as IGetAuthorizationHeader; return getAuthorizationHeader; } } async function resolveDirectLinks(people: TeamMember[]): Promise<TeamMember[]> { for (let i = 0; i < people.length; i++) { const member = people[i]; await member.getMailAddress(); } return people; } function teamRepositoryPermissionsFromEntity(entity) { // private, remapped "this" const instance = new TeamRepositoryPermission( this, entity, this._operations); return instance; }
the_stack
import * as clipperLib from "../src"; import { hiRange } from "../src/constants"; import { pathsToPureJs, pathToPureJs, pureJsClipperLib, pureJsTestOffset, pureJsTestPolyOperation } from "./pureJs"; import { circlePath } from "./utils"; // tslint:disable-next-line:no-console window.alert = (msg) => console.error("window alert: ", msg); let clipperWasm: clipperLib.ClipperLibWrapper; let clipperAsmJs: clipperLib.ClipperLibWrapper; beforeAll(async () => { clipperWasm = await clipperLib.loadNativeClipperLibInstanceAsync( clipperLib.NativeClipperLibRequestedFormat.WasmOnly ); clipperAsmJs = await clipperLib.loadNativeClipperLibInstanceAsync( clipperLib.NativeClipperLibRequestedFormat.AsmJsOnly ); }, 60000); describe("unit tests", () => { test("wasm instance must be loaded", () => { expect(clipperWasm).toBeDefined(); expect(clipperWasm.instance).toBeDefined(); expect(clipperWasm.format).toEqual(clipperLib.NativeClipperLibLoadedFormat.Wasm); }); test("asmjs instance must be loaded", () => { expect(clipperAsmJs).toBeDefined(); expect(clipperAsmJs.instance).toBeDefined(); expect(clipperAsmJs.format).toEqual(clipperLib.NativeClipperLibLoadedFormat.AsmJs); }); test("pureJs instance must be loaded", () => { expect(pureJsClipperLib).toBeDefined(); expect(new pureJsClipperLib.Clipper()).toBeDefined(); }); describe("simple polygons", () => { // create some polygons (note that they MUST be integer coordinates) const poly1 = [ { x: 0, y: 10 }, { x: Math.trunc(hiRange / 3), y: 10 }, { x: Math.trunc(hiRange / 3), y: 20 }, { x: 0, y: 20 } ]; const pureJsPoly1 = pathToPureJs(poly1); const poly2 = [ { x: 10, y: 0 }, { x: Math.trunc(hiRange / 4), y: 0 }, { x: Math.trunc(hiRange / 4), y: 30 }, { x: 10, y: 30 } ]; const pureJsPoly2 = pathToPureJs(poly2); describe("boolean operations", () => { for (const clipType of [ clipperLib.ClipType.Intersection, clipperLib.ClipType.Union, clipperLib.ClipType.Difference, clipperLib.ClipType.Xor ]) { for (const polyFillType of [ clipperLib.PolyFillType.EvenOdd, clipperLib.PolyFillType.NonZero, clipperLib.PolyFillType.Negative, clipperLib.PolyFillType.Positive ]) { test(`clipType: ${clipType}, fillType: ${polyFillType}`, () => { const res = testPolyOperation(clipType, polyFillType, poly1, poly2, { wasm: true, asm: true }); const pureJsRes = pureJsTestPolyOperation( clipType, polyFillType, pureJsPoly1, pureJsPoly2 ); expect(res.asmResult).toEqual(res.wasmResult); expect(pureJsRes).toEqual(pathsToPureJs(res.wasmResult!)); expect(res.wasmResult).toMatchSnapshot(); }); } } }); describe("offset", () => { for (const joinType of [ clipperLib.JoinType.Miter, clipperLib.JoinType.Round, clipperLib.JoinType.Square ]) { for (const endType of [ clipperLib.EndType.ClosedPolygon, clipperLib.EndType.ClosedLine, clipperLib.EndType.OpenButt, clipperLib.EndType.OpenRound, clipperLib.EndType.OpenSquare ]) { for (const delta of [5, 0, -5]) { test(`joinType: ${joinType}, endType: ${endType}, delta: ${delta}`, () => { const res = testOffset(poly1, joinType, endType, delta, { wasm: true, asm: true }); const pureJsRes = pureJsTestOffset(pureJsPoly1, joinType, endType, delta); expect(res.asmResult).toEqual(res.wasmResult); expect(pureJsRes).toEqual(pathsToPureJs(res.wasmResult!)); expect(res.wasmResult).toMatchSnapshot(); }); } } } }); }); test("using clipToPaths with open paths should throw", () => { const clipType = clipperLib.ClipType.Intersection; const polyFillType = clipperLib.PolyFillType.Positive; const poly1 = [ { x: 10, y: 10 }, { x: 90, y: 10 }, { x: 90, y: 90 } ]; const poly2 = [ { x: 0, y: 0 }, { x: 50, y: 0 }, { x: 50, y: 50 }, { x: 0, y: 50 } ]; function testShouldThrow(wasm: boolean) { expect(() => { testPolyOperation( clipType, polyFillType, poly1, poly2, { wasm: wasm, asm: !wasm }, false, false ); }).toThrow("clip to a PolyTree (not to a Path) when using open paths"); } testShouldThrow(true); testShouldThrow(false); }); describe("issue #4", () => { for (const subjectClosed of [true, false]) { test(`subjectClosed: ${subjectClosed}`, () => { const clipType = clipperLib.ClipType.Intersection; const polyFillType = clipperLib.PolyFillType.Positive; const poly1 = [ { x: 10, y: 10 }, { x: 90, y: 10 }, { x: 90, y: 90 } ]; const pureJsPoly1 = pathToPureJs(poly1); const poly2 = [ { x: 0, y: 0 }, { x: 50, y: 0 }, { x: 50, y: 50 }, { x: 0, y: 50 } ]; const pureJsPoly2 = pathToPureJs(poly2); const pureJsRes = pureJsTestPolyOperation( clipType, polyFillType, pureJsPoly1, pureJsPoly2, subjectClosed ); const res = testPolyOperation( clipType, polyFillType, poly1, poly2, { wasm: true, asm: true }, subjectClosed, true ); expect(res.ptAsmResult).toEqual(res.ptWasmResult); const open = clipperWasm.openPathsFromPolyTree(res.ptWasmResult!); const closed = clipperWasm.closedPathsFromPolyTree(res.ptWasmResult!); if (subjectClosed) { expect(pureJsRes).toEqual(pathsToPureJs(closed)); expect(open.length).toBe(0); } else { expect(pureJsRes).toEqual(pathsToPureJs(open)); expect(closed.length).toBe(0); } expect(res.ptWasmResult).toMatchSnapshot(); }); } }); test("issue #9", () => { const clipper = clipperWasm; const request = { clipType: clipperLib.ClipType.Union, subjectInputs: [ { data: [ { x: 50, y: 50 }, { x: -50, y: 50 }, { x: -50, y: -50 }, { x: 50, y: -50 } ], closed: true }, { data: [ { x: -5, y: -5 }, { x: -5, y: 5 }, { x: 5, y: 5 }, { x: 5, y: -5 } ], closed: true } ], subjectFillType: clipperLib.PolyFillType.NonZero, strictlySimple: true }; const result = clipper.clipToPolyTree(request); expect(result).toMatchSnapshot(); }); }); describe("benchmarks", () => { const oldNodeEnv = process.env.NODE_ENV; beforeAll(() => { process.env.NODE_ENV = "production"; }); afterAll(() => { process.env.NODE_ENV = oldNodeEnv; }); for (const benchmark of [ { ops: 500, points: 5000 }, { ops: 10000, points: 100 } ]) { describe(`${benchmark.ops} boolean operations over two circles of ${benchmark.points} points each`, () => { const poly1 = circlePath({ x: 1000, y: 1000 }, 1000, benchmark.points); const poly2 = circlePath({ x: 2500, y: 1000 }, 1000, benchmark.points); const pureJsPoly1 = pathToPureJs(poly1); const pureJsPoly2 = pathToPureJs(poly2); const scale = 100; pureJsClipperLib.JS.ScaleUpPaths(pureJsPoly1, scale); pureJsClipperLib.JS.ScaleUpPaths(pureJsPoly2, scale); for (const clipType of [ clipperLib.ClipType.Intersection, clipperLib.ClipType.Union, clipperLib.ClipType.Difference, clipperLib.ClipType.Xor ]) { for (const polyFillType of [ clipperLib.PolyFillType.EvenOdd // clipperLib.PolyFillType.NonZero, // clipperLib.PolyFillType.Negative, // clipperLib.PolyFillType.Positive, ]) { describe(`clipType: ${clipType}, subjectFillType: ${polyFillType}`, () => { for (const mode of ["wasm", "asmJs", "pureJs"]) { test(`${mode}`, () => { for (let i = 0; i < benchmark.ops; i++) { if (mode === "wasm" || mode === "asmJs") { testPolyOperation(clipType, polyFillType, poly1, poly2, { wasm: mode === "wasm", asm: mode === "asmJs" }); } else if (mode === "pureJs") { pureJsTestPolyOperation(clipType, polyFillType, pureJsPoly1, pureJsPoly2); } } }); } }); } } }); } for (const benchmark of [ { ops: 100, points: 5000 }, { ops: 5000, points: 100 } ]) { describe(`${benchmark.ops} offset operations over a circle of ${benchmark.points} points`, () => { const poly1 = circlePath({ x: 1000, y: 1000 }, 1000, benchmark.points); const pureJsPoly1 = pathToPureJs(poly1); const scale = 100; pureJsClipperLib.JS.ScaleUpPaths(pureJsPoly1, scale); for (const joinType of [ clipperLib.JoinType.Miter // clipperLib.JoinType.Round, // clipperLib.JoinType.Square ]) { for (const endType of [ clipperLib.EndType.ClosedPolygon // clipperLib.EndType.ClosedLine, // clipperLib.EndType.OpenButt, // clipperLib.EndType.OpenRound, // clipperLib.EndType.OpenSquare, ]) { for (const delta of [5, 0, -5]) { describe(`joinType: ${joinType}, endType: ${endType}, delta: ${delta}`, () => { for (const mode of ["wasm", "asmJs", "pureJs"]) { test(`${mode}`, () => { for (let i = 0; i < benchmark.ops; i++) { if (mode === "wasm" || mode === "asmJs") { testOffset(poly1, joinType, endType, delta, { wasm: mode === "wasm", asm: mode === "asmJs" }); } else if (mode === "pureJs") { pureJsTestOffset(pureJsPoly1, joinType, endType, delta); } } }); } }); } } } }); } }); function testPolyOperation( clipType: clipperLib.ClipType, subjectFillType: clipperLib.PolyFillType, subjectInput: clipperLib.Path | clipperLib.Paths, clipInput: clipperLib.Path | clipperLib.Paths, format: { wasm: boolean; asm: boolean }, subjectInputClosed = true, clipToPolyTrees = false ) { const data = { clipType: clipType, subjectInputs: [{ data: subjectInput, closed: subjectInputClosed }], clipInputs: [{ data: clipInput }], subjectFillType: subjectFillType }; const pathResults = !clipToPolyTrees ? { asmResult: format.asm ? clipperAsmJs.clipToPaths(data) : undefined, wasmResult: format.wasm ? clipperWasm.clipToPaths(data) : undefined } : {}; const polyTreeResults = clipToPolyTrees ? { ptAsmResult: format.asm ? clipperAsmJs.clipToPolyTree(data) : undefined, ptWasmResult: format.wasm ? clipperWasm.clipToPolyTree(data) : undefined } : {}; return { ...pathResults, ...polyTreeResults }; } function testOffset( input: clipperLib.Path | clipperLib.Paths, joinType: clipperLib.JoinType, endType: clipperLib.EndType, delta: number, format: { wasm: boolean; asm: boolean } ) { const data: clipperLib.OffsetParams = { delta: delta, offsetInputs: [ { joinType: joinType, endType: endType, data: input } ] }; return { wasmResult: format.wasm ? clipperWasm.offsetToPaths(data) : undefined, asmResult: format.asm ? clipperAsmJs.offsetToPaths(data) : undefined }; }
the_stack
import { PubSub, PubSubEngine } from "apollo-server"; import { Context, SubscriptionServerOptions } from "apollo-server-core"; import { ExpressContext } from "apollo-server-express/dist/ApolloServer"; import { filter } from "axax/es5/filter"; import { map } from "axax/es5/map"; import { pipe } from "axax/es5/pipe"; import "core-js/es/symbol/async-iterator"; import { getQueryArgumentValue, interpolateValueNodeWithVariables, IStoredConnection, } from "fanout-graphql-tools"; import { ISimpleTable } from "fanout-graphql-tools"; import { getSubscriptionOperationFieldName, IGraphqlWsStartMessage, } from "fanout-graphql-tools"; import { WebSocketOverHttpContextFunction } from "fanout-graphql-tools"; import { IStoredPubSubSubscription } from "fanout-graphql-tools"; import { WebSocketOverHttpPubSubMixin } from "fanout-graphql-tools"; import { withFilter } from "graphql-subscriptions"; import gql from "graphql-tag"; import { IResolvers, makeExecutableSchema } from "graphql-tools"; import { $$asyncIterator } from "iterall"; import * as querystring from "querystring"; import * as uuidv4 from "uuid/v4"; /** Common queries for this API */ export const FanoutGraphqlSubscriptionQueries = { noteAdded() { return { query: gql` subscription { noteAdded { content id } } `, variables: {}, }; }, noteAddedToCollection(collection: string) { return { query: gql` subscription NoteAddedToCollection($collection: String!) { noteAddedToCollection(collection: $collection) { content id } } `, variables: { collection }, }; }, }; enum SubscriptionEventNames { noteAdded = "noteAdded", noteAddedToCollection = "noteAddedToCollection", } export interface INote { /** unique identifier for the note */ id: string; /** collection id that the note is in */ collection: string; /** main body content of the Note */ content: string; } export interface IFanoutGraphqlTables { /** WebSocket-Over-Http Connections */ connections: ISimpleTable<IStoredConnection>; /** Notes table */ notes: ISimpleTable<INote>; /** PubSub Subscriptions */ pubSubSubscriptions: ISimpleTable<IStoredPubSubSubscription>; } interface IFanoutGraphqlAppContext { /** Authorization token, if present */ authorization: string | undefined; } /** * Create a graphql typeDefs string for the FanoutGraphql App */ export const FanoutGraphqlTypeDefs = (subscriptions: boolean) => ` type Note { collection: String! content: String! id: String! } input NotesQueryInput { collection: String } type Query { notes: [Note!]! getNotesByCollection(collection: String!): [Note!]! } input AddNoteInput { "Collection to add note to" collection: String! "The main body content of the Note" content: String! } type Mutation { addNote(note: AddNoteInput!): Note } ${ subscriptions ? ` type Subscription { noteAdded: Note noteAddedToCollection(collection: String!): Note } ` : "" } `; /** * given an object, return the same, ensuring that the object keys were inserted in alphabetical order * https://github.com/nodejs/node/issues/6594#issuecomment-217120402 */ function sorted(o: any) { const p = Object.create(null); for (const k of Object.keys(o).sort()) { p[k] = o[k]; } return p; } const gripChannelNames = { noteAdded(operationId: string) { return `${SubscriptionEventNames.noteAdded}?${querystring.stringify( sorted({ "subscription.operation.id": operationId, }), )}`; }, noteAddedToCollection(operationId: string, collection: string) { return `${ SubscriptionEventNames.noteAddedToCollection }?${querystring.stringify( sorted({ collection, "subscription.operation.id": operationId, }), )}`; }, }; /** Given a subscription operation, return the Grip channel name that should be subscribed to by that WebSocket client */ export const FanoutGraphqlGripChannelsForSubscription = ( gqlStartMessage: IGraphqlWsStartMessage, ): string => { const subscriptionFieldName = getSubscriptionOperationFieldName( gqlStartMessage.payload, ); switch (subscriptionFieldName) { case "noteAdded": return gripChannelNames.noteAdded(gqlStartMessage.id); case "noteAddedToCollection": const collection = interpolateValueNodeWithVariables( getQueryArgumentValue(gqlStartMessage.payload.query, "collection"), gqlStartMessage.payload.variables, ); if (typeof collection !== "string") { throw new Error( `Expected collection argument value to be a string, but got ${collection}`, ); } return gripChannelNames.noteAddedToCollection(gqlStartMessage.id, collection); } throw new Error( `FanoutGraphqlGripChannelsForSubscription got unexpected subscription field name: ${subscriptionFieldName}`, ); }; /** Return items in an ISimpleTable that match the provided filter function */ export const filterTable = async <ItemType extends object>( table: ISimpleTable<ItemType>, itemFilter: (item: ItemType) => boolean, ): Promise<ItemType[]> => { const filteredItems: ItemType[] = []; await table.scan(async items => { filteredItems.push(...items.filter(itemFilter)); return true; }); return filteredItems; }; interface IFanoutGraphqlApolloOptions { /** grip uri */ grip: | false | { /** GRIP URI for EPCP Gateway */ url: string; /** Given a graphql-ws GQL_START message, return a string that is the Grip-Channel that the GRIP server should subscribe to for updates */ getGripChannel?(gqlStartMessage: IGraphqlWsStartMessage): string; }; /** PubSubEngine to use to publish/subscribe mutations/subscriptions */ pubsub?: PubSubEngine; /** Whether subscriptions are enabled in the schema */ subscriptions: boolean; /** Tables to store data */ tables: IFanoutGraphqlTables; } /** * ApolloServer.Config that will configure an ApolloServer to serve the FanoutGraphql graphql API. * @param pubsub - If not provided, subscriptions will not be enabled */ export const FanoutGraphqlApolloConfig = ( options: IFanoutGraphqlApolloOptions, ) => { if (!options.subscriptions) { console.debug("FanoutGraphqlApolloConfig: subscriptions will be disabled."); } const { tables } = options; const pubsub = options.pubsub || new PubSub(); // Construct a schema, using GraphQL schema language const typeDefs = FanoutGraphqlTypeDefs(options.subscriptions); interface INoteAddedEvent { /** Event payload */ noteAdded: INote; } interface INoteAddedToCollectionEvent { /** Event payload */ noteAddedToCollection: INote; } const isNoteAddedEvent = (o: any): o is INoteAddedEvent => "noteAdded" in o; type SubscriptionEvent = INoteAddedEvent; // Provide resolver functions for your schema fields const resolvers: IResolvers = { Mutation: { async addNote(root, args, context) { const { note } = args; const noteId = uuidv4(); const noteToInsert: INote = { ...note, id: noteId, }; await options.tables.notes.insert(noteToInsert); if (pubsub) { await WebSocketOverHttpPubSubMixin(context)(pubsub).publish( SubscriptionEventNames.noteAdded, { noteAdded: noteToInsert, }, ); } return noteToInsert; }, }, Query: { getNotesByCollection: async (obj, args, context, info): Promise<INote[]> => { const notes: INote[] = []; await tables.notes.scan(async notesBatch => { notes.push( ...notesBatch.filter(note => note.collection === args.collection), ); return true; }); return notes; }, notes: async (obj, args, context, info): Promise<INote[]> => { const notes = await tables.notes.scan(); return notes; }, }, ...(options.subscriptions ? { Subscription: { noteAdded: { subscribe( source, args, context, info, ): AsyncIterator<INoteAddedEvent> { const noteAddedEvents = withFilter( () => WebSocketOverHttpPubSubMixin(context)(pubsub).asyncIterator< unknown >([SubscriptionEventNames.noteAdded]), (payload, variables) => { return isNoteAddedEvent(payload); }, )(source, args, context, info); return noteAddedEvents; }, }, noteAddedToCollection: { subscribe(source, args, context, info) { const eventFilter = (event: object) => isNoteAddedEvent(event) && event.noteAdded.collection === args.collection; const noteAddedIterator = WebSocketOverHttpPubSubMixin(context)( pubsub, ).asyncIterator([SubscriptionEventNames.noteAdded]); const iterable = { [Symbol.asyncIterator]() { return noteAddedIterator; }, }; const notesAddedToCollection = pipe( filter(eventFilter), map(event => { return { noteAddedToCollection: event.noteAdded, }; }), )(iterable); // Have to use this $$asyncIterator from iterall so that graphql/subscription will recognize this as an AsyncIterable // even when compiled for node version 8, which doesn't have Symbol.asyncIterator return { [$$asyncIterator]() { return notesAddedToCollection[Symbol.asyncIterator](); }, }; }, }, }, } : {}), }; const subscriptions: Partial<SubscriptionServerOptions> = { path: "/", onConnect(connectionParams, websocket, context) { console.log("FanoutGraphqlApolloConfig subscription onConnect"); }, onDisconnect() { console.log("FanoutGraphqlApolloConfig subscription onDisconnect"); }, }; const schema = makeExecutableSchema({ typeDefs, resolvers }); const createContext = async ( contextOptions: ExpressContext | { /** graphql context to use for subscription */ context: Context; }, ): Promise<IFanoutGraphqlAppContext> => { // console.log("FanoutGraphqlApolloConfig createContext with contextOptions"); const connectionContext = "context" in contextOptions ? contextOptions.context : {}; const contextFromExpress = "req" in contextOptions ? { authorization: contextOptions.req.headers.authorization } : {}; const context: IFanoutGraphqlAppContext = { authorization: undefined, ...connectionContext, ...contextFromExpress, ...(options.grip ? WebSocketOverHttpContextFunction({ grip: options.grip, pubSubSubscriptionStorage: options.tables.pubSubSubscriptions, schema, }) : {}), }; return context; }; // const DebugApolloServerPlugin = (): ApolloServerPlugin => ({ // requestDidStart(requestContext) { // console.log("requestDidStart"); // }, // }); return { context: createContext, plugins: [ // DebugApolloServerPlugin(), ], schema, subscriptions: pubsub && subscriptions, }; }; export default FanoutGraphqlApolloConfig;
the_stack
import { property } from "./jsonobject"; import { Question } from "./question"; import { Base } from "./base"; import { ItemValue } from "./itemvalue"; import { surveyLocalization } from "./surveyStrings"; import { LocalizableString } from "./localizablestring"; import { PanelModel } from "./panel"; import { Action, IAction } from "./actions/action"; import { AdaptiveActionContainer } from "./actions/adaptive-container"; import { CssClassBuilder } from "./utils/cssClassBuilder"; import { MatrixDropdownColumn } from "./question_matrixdropdowncolumn"; import { MatrixDropdownCell, MatrixDropdownRowModelBase, QuestionMatrixDropdownModelBase } from "./question_matrixdropdownbase"; import { ActionContainer } from "./actions/container"; export class QuestionMatrixDropdownRenderedCell { private static counter = 1; private idValue: number; private itemValue: ItemValue; public minWidth: string = ""; public width: string = ""; public locTitle: LocalizableString; public cell: MatrixDropdownCell; public column: MatrixDropdownColumn; public row: MatrixDropdownRowModelBase; public question: Question; public isRemoveRow: boolean; public choiceIndex: number; public matrix: QuestionMatrixDropdownModelBase; public requiredText: string; public isEmpty: boolean; public colSpans: number = 1; public panel: PanelModel; public isShowHideDetail: boolean; public isActionsCell: boolean = false; public isDragHandlerCell: boolean = false; private classNameValue: string = ""; public constructor() { this.idValue = QuestionMatrixDropdownRenderedCell.counter++; } public get hasQuestion(): boolean { return !!this.question; } public get hasTitle(): boolean { return !!this.locTitle; } public get hasPanel(): boolean { return !!this.panel; } public get id(): number { return this.idValue; } public get showErrorOnTop(): boolean { return this.showErrorOnCore("top"); } public get showErrorOnBottom(): boolean { return this.showErrorOnCore("bottom"); } private showErrorOnCore(location: string): boolean { return ( this.getShowErrorLocation() == location && (!this.isChoice || this.isFirstChoice) ); } private getShowErrorLocation(): string { return this.hasQuestion ? this.question.survey.questionErrorLocation : ""; } public get item(): ItemValue { return this.itemValue; } public set item(val: ItemValue) { this.itemValue = val; if (!!val) { val.hideCaption = true; } } public get isChoice(): boolean { return !!this.item; } public get choiceValue(): any { return this.isChoice ? this.item.value : null; } public get isCheckbox(): boolean { return this.isChoice && this.question.getType() == "checkbox"; } public get isFirstChoice(): boolean { return this.choiceIndex === 0; } public set className(val: string) { this.classNameValue = val; } public get className(): string { const builder = new CssClassBuilder().append(this.classNameValue); if(this.hasQuestion) { builder .append(this.question.cssError, this.question.errors.length > 0) .append(this.question.cssClasses.answered, this.question.isAnswered); } return builder.toString(); } public get headers(): string { if ( this.cell && this.cell.column && this.cell.column.isShowInMultipleColumns ) { return this.item.locText.renderedHtml; } if (this.question && this.question.isVisible) { return this.question.locTitle.renderedHtml; } if (this.hasTitle) { return this.locTitle.renderedHtml || ""; } return ""; } public calculateFinalClassName(matrixCssClasses: any): string { const questionCss = this.cell.question.cssClasses; // 'text-align': $data.isChoice ? 'center': const builder = new CssClassBuilder() .append(questionCss.itemValue, !!questionCss) .append(questionCss.asCell, !!questionCss); return builder.append(matrixCssClasses.cell, builder.isEmpty() && !!matrixCssClasses) .append(matrixCssClasses.choiceCell, this.isChoice) .toString(); } } export class QuestionMatrixDropdownRenderedRow extends Base { @property({ defaultValue: null }) ghostPosition: string; @property({ defaultValue: false }) isAdditionalClasses: boolean; public row: MatrixDropdownRowModelBase; private static counter = 1; private idValue: number; public cells: Array<QuestionMatrixDropdownRenderedCell> = []; public constructor(public cssClasses: any, public isDetailRow: boolean = false) { super(); this.onCreating(); this.idValue = QuestionMatrixDropdownRenderedRow.counter++; } public onCreating() { } // need for knockout binding see QuestionMatrixDropdownRenderedRow.prototype["onCreating"] public get id(): number { return this.idValue; } public get attributes() { if (!this.row) return {}; return { "data-sv-drop-target-matrix-row": this.row.id }; } public get className(): string { return new CssClassBuilder() .append(this.cssClasses.row) .append(this.cssClasses.detailRow, this.isDetailRow) .append(this.cssClasses.dragDropGhostPositionTop, this.ghostPosition === "top") .append(this.cssClasses.dragDropGhostPositionBottom, this.ghostPosition === "bottom") .append(this.cssClasses.rowAdditional, this.isAdditionalClasses) .toString(); } } export class QuestionMatrixDropdownRenderedTable extends Base { private headerRowValue: QuestionMatrixDropdownRenderedRow; private footerRowValue: QuestionMatrixDropdownRenderedRow; private hasRemoveRowsValue: boolean; private rowsActions: Array<Array<IAction>>; private cssClasses: any; public constructor(public matrix: QuestionMatrixDropdownModelBase) { super(); this.createNewArray("rows"); this.build(); } public get showTable(): boolean { return this.getPropertyValue("showTable", true); } public get showHeader(): boolean { return this.getPropertyValue("showHeader"); } public get showAddRowOnTop(): boolean { return this.getPropertyValue("showAddRowOnTop", false); } public get showAddRowOnBottom(): boolean { return this.getPropertyValue("showAddRowOnBottom", false); } public get showFooter(): boolean { return this.matrix.hasFooter && this.matrix.isColumnLayoutHorizontal; } public get hasFooter(): boolean { return !!this.footerRow; } public get hasRemoveRows(): boolean { return this.hasRemoveRowsValue; } public isRequireReset(): boolean { return ( this.hasRemoveRows != this.matrix.canRemoveRows || !this.matrix.isColumnLayoutHorizontal ); } public get headerRow(): QuestionMatrixDropdownRenderedRow { return this.headerRowValue; } public get footerRow(): QuestionMatrixDropdownRenderedRow { return this.footerRowValue; } public get rows(): Array<QuestionMatrixDropdownRenderedRow> { return this.getPropertyValue("rows"); } protected build() { this.hasRemoveRowsValue = this.matrix.canRemoveRows; //build rows now var rows = this.matrix.visibleRows; this.cssClasses = this.matrix.cssClasses; this.buildRowsActions(); this.buildHeader(); this.buildRows(); this.buildFooter(); this.updateShowTableAndAddRow(); } public updateShowTableAndAddRow() { var showTable = this.rows.length > 0 || this.matrix.isDesignMode || !this.matrix.getShowColumnsIfEmpty(); this.setPropertyValue("showTable", showTable); var showAddRow = this.matrix.canAddRow && showTable; var showAddRowOnTop = showAddRow; var showAddRowOnBottom = showAddRow; if (showAddRowOnTop) { if (this.matrix.getAddRowLocation() === "default") { showAddRowOnTop = this.matrix.columnLayout === "vertical"; } else { showAddRowOnTop = this.matrix.getAddRowLocation() !== "bottom"; } } if (showAddRowOnBottom && this.matrix.getAddRowLocation() !== "topBottom") { showAddRowOnBottom = !showAddRowOnTop; } this.setPropertyValue("showAddRowOnTop", showAddRowOnTop); this.setPropertyValue("showAddRowOnBottom", showAddRowOnBottom); } public onAddedRow() { if (this.getRenderedDataRowCount() >= this.matrix.visibleRows.length) return; var row = this.matrix.visibleRows[this.matrix.visibleRows.length - 1]; this.rowsActions.push(this.buildRowActions(row)); this.addHorizontalRow( this.rows, row, this.matrix.visibleRows.length == 1 && !this.matrix.showHeader ); this.updateShowTableAndAddRow(); } private getRenderedDataRowCount(): number { var res = 0; for (var i = 0; i < this.rows.length; i++) { if (!this.rows[i].isDetailRow) res++; } return res; } public onRemovedRow(row: MatrixDropdownRowModelBase) { var rowIndex = this.getRenderedRowIndex(row); if (rowIndex < 0) return; this.rowsActions.splice(rowIndex, 1); var removeCount = 1; if ( rowIndex < this.rows.length - 1 && this.rows[rowIndex + 1].isDetailRow ) { removeCount++; } this.rows.splice(rowIndex, removeCount); this.updateShowTableAndAddRow(); } public onDetailPanelChangeVisibility( row: MatrixDropdownRowModelBase, isShowing: boolean ) { var rowIndex = this.getRenderedRowIndex(row); if (rowIndex < 0) return; var panelRowIndex = rowIndex < this.rows.length - 1 && this.rows[rowIndex + 1].isDetailRow ? rowIndex + 1 : -1; if ((isShowing && panelRowIndex > -1) || (!isShowing && panelRowIndex < 0)) return; if (isShowing) { var detailRow = this.createDetailPanelRow(row, this.rows[rowIndex]); this.rows.splice(rowIndex + 1, 0, detailRow); } else { this.rows.splice(panelRowIndex, 1); } } private getRenderedRowIndex(row: MatrixDropdownRowModelBase): number { for (var i = 0; i < this.rows.length; i++) { if (this.rows[i].row == row) return i; } return -1; } protected buildRowsActions() { this.rowsActions = []; var rows = this.matrix.visibleRows; for (var i = 0; i < rows.length; i++) { this.rowsActions.push(this.buildRowActions(rows[i])); } } protected buildHeader() { var colHeaders = this.matrix.isColumnLayoutHorizontal && this.matrix.showHeader; var isShown = colHeaders || (this.matrix.hasRowText && !this.matrix.isColumnLayoutHorizontal); this.setPropertyValue("showHeader", isShown); if (!isShown) return; this.headerRowValue = new QuestionMatrixDropdownRenderedRow( this.cssClasses ); if (this.matrix.allowRowsDragAndDrop) { this.headerRow.cells.push(this.createHeaderCell(null)); } if (this.hasActionCellInRows("start")) { this.headerRow.cells.push(this.createHeaderCell(null)); } if (this.matrix.hasRowText && this.matrix.showHeader) { this.headerRow.cells.push(this.createHeaderCell(null)); } if (this.matrix.isColumnLayoutHorizontal) { for (var i = 0; i < this.matrix.visibleColumns.length; i++) { var column = this.matrix.visibleColumns[i]; if (!column.hasVisibleCell) continue; if (column.isShowInMultipleColumns) { this.createMutlipleColumnsHeader(column); } else { this.headerRow.cells.push(this.createHeaderCell(column)); } } } else { var rows = this.matrix.visibleRows; for (var i = 0; i < rows.length; i++) { this.headerRow.cells.push(this.createTextCell(rows[i].locText)); } if (this.matrix.hasFooter) { this.headerRow.cells.push( this.createTextCell(this.matrix.getFooterText()) ); } } if (this.hasActionCellInRows("end")) { this.headerRow.cells.push(this.createHeaderCell(null)); } } protected buildFooter() { if (!this.showFooter) return; this.footerRowValue = new QuestionMatrixDropdownRenderedRow( this.cssClasses ); if (this.matrix.allowRowsDragAndDrop) { this.footerRow.cells.push(this.createHeaderCell(null)); } if (this.hasActionCellInRows("start")) { this.footerRow.cells.push(this.createHeaderCell(null)); } if (this.matrix.hasRowText) { this.footerRow.cells.push( this.createTextCell(this.matrix.getFooterText()) ); } var cells = this.matrix.visibleTotalRow.cells; for (var i = 0; i < cells.length; i++) { var cell = cells[i]; if (!cell.column.hasVisibleCell) continue; if (cell.column.isShowInMultipleColumns) { this.createMutlipleColumnsFooter(this.footerRow, cell); } else { this.footerRow.cells.push(this.createEditCell(cell)); } } if (this.hasActionCellInRows("end")) { this.footerRow.cells.push(this.createHeaderCell(null)); } } protected buildRows() { var rows = this.matrix.isColumnLayoutHorizontal ? this.buildHorizontalRows() : this.buildVerticalRows(); this.setPropertyValue("rows", rows); } private hasActionCellInRowsValues: any = {}; private hasActionCellInRows(location: "start" | "end"): boolean { if (this.hasActionCellInRowsValues[location] === undefined) { var rows = this.matrix.visibleRows; this.hasActionCellInRowsValues[location] = false; for (var i = 0; i < rows.length; i++) { if (!this.isValueEmpty(this.getRowActions(i, location))) { this.hasActionCellInRowsValues[location] = true; break; } } } return this.hasActionCellInRowsValues[location]; } private canRemoveRow(row: MatrixDropdownRowModelBase): boolean { return this.matrix.canRemoveRow(row); } private buildHorizontalRows(): Array<QuestionMatrixDropdownRenderedRow> { var rows = this.matrix.visibleRows; var renderedRows: Array<QuestionMatrixDropdownRenderedRow> = []; for (var i = 0; i < rows.length; i++) { this.addHorizontalRow( renderedRows, rows[i], i == 0 && !this.matrix.showHeader ); } return renderedRows; } private addHorizontalRow( renderedRows: Array<QuestionMatrixDropdownRenderedRow>, row: MatrixDropdownRowModelBase, useAsHeader: boolean ) { var renderedRow = this.createHorizontalRow(row, useAsHeader); renderedRow.row = row; renderedRows.push(renderedRow); if (row.isDetailPanelShowing) { renderedRows.push(this.createDetailPanelRow(row, renderedRow)); } } private getRowDragCell(rowIndex: number) { const cell = new QuestionMatrixDropdownRenderedCell(); cell.isDragHandlerCell = true; cell.className = this.cssClasses.actionsCell; cell.row = this.matrix.visibleRows[rowIndex]; return cell; } private getRowActionsCell(rowIndex: number, location: "start" | "end") { const rowActions = this.getRowActions(rowIndex, location); if (!this.isValueEmpty(rowActions)) { const cell = new QuestionMatrixDropdownRenderedCell(); const actionContainer = this.matrix.allowAdaptiveActions ? new AdaptiveActionContainer() : new ActionContainer(); actionContainer.setItems(rowActions); const itemValue = new ItemValue(actionContainer); cell.item = itemValue; cell.isActionsCell = true; cell.className = this.cssClasses.actionsCell; cell.row = this.matrix.visibleRows[rowIndex]; return cell; } return null; } private getRowActions(rowIndex: number, location: "start" | "end") { var actions = this.rowsActions[rowIndex]; if (!Array.isArray(actions)) return []; return actions.filter((action) => { if (!action.location) { action.location = "start"; } return action.location === location; }); } private buildRowActions(row: MatrixDropdownRowModelBase): Array<IAction> { var actions: Array<IAction> = []; this.setDefaultRowActions(row, actions); if (!!this.matrix.survey) { actions = this.matrix.survey.getUpdatedMatrixRowActions( this.matrix, row, actions ); } return actions; } protected setDefaultRowActions( row: MatrixDropdownRowModelBase, actions: Array<IAction> ) { if (this.hasRemoveRows && this.canRemoveRow(row)) { actions.push( new Action({ id: "remove-row", location: "end", enabled: !this.matrix.isInputReadOnly, component: "sv-matrix-remove-button", data: { row: row, question: this.matrix }, }) ); } if (row.hasPanel) { actions.push( new Action({ id: "show-detail", title: surveyLocalization.getString("editText"), showTitle: false, location: "start", component: "sv-matrix-detail-button", data: { row: row, question: this.matrix }, }) ); } } private createHorizontalRow( row: MatrixDropdownRowModelBase, useAsHeader: boolean ): QuestionMatrixDropdownRenderedRow { var res = new QuestionMatrixDropdownRenderedRow(this.cssClasses); if (this.matrix.allowRowsDragAndDrop) { var rowIndex = this.matrix.visibleRows.indexOf(row); res.cells.push(this.getRowDragCell(rowIndex)); } this.addRowActionsCell(row, res, "start"); if (this.matrix.hasRowText) { var renderedCell = this.createTextCell(row.locText); renderedCell.row = row; res.cells.push(renderedCell); if (useAsHeader) { this.setHeaderCellWidth(null, renderedCell); } renderedCell.className = new CssClassBuilder() .append(renderedCell.className) .append(this.cssClasses.detailRowText, row.hasPanel) .toString(); } for (var i = 0; i < row.cells.length; i++) { let cell = row.cells[i]; if (!cell.column.hasVisibleCell) continue; if (cell.column.isShowInMultipleColumns) { this.createMutlipleEditCells(res, cell); } else { var renderedCell = this.createEditCell(cell); res.cells.push(renderedCell); if (useAsHeader) { this.setHeaderCellWidth(cell.column, renderedCell); } } } this.addRowActionsCell(row, res, "end"); return res; } private addRowActionsCell( row: MatrixDropdownRowModelBase, renderedRow: QuestionMatrixDropdownRenderedRow, location: "start" | "end" ) { var rowIndex = this.matrix.visibleRows.indexOf(row); if (this.hasActionCellInRows(location)) { const actions = this.getRowActionsCell(rowIndex, location); if (!!actions) { renderedRow.cells.push(actions); } else { var cell = new QuestionMatrixDropdownRenderedCell(); cell.isEmpty = true; renderedRow.cells.push(cell); } } } private createDetailPanelRow( row: MatrixDropdownRowModelBase, renderedRow: QuestionMatrixDropdownRenderedRow ): QuestionMatrixDropdownRenderedRow { var res = new QuestionMatrixDropdownRenderedRow(this.cssClasses, true); res.row = row; var buttonCell = new QuestionMatrixDropdownRenderedCell(); if (this.matrix.hasRowText) { buttonCell.colSpans = 2; } buttonCell.isEmpty = true; res.cells.push(buttonCell); var actionsCell = null; if (this.hasActionCellInRows("end")) { actionsCell = new QuestionMatrixDropdownRenderedCell(); actionsCell.isEmpty = true; } var cell = new QuestionMatrixDropdownRenderedCell(); cell.panel = row.detailPanel; cell.colSpans = renderedRow.cells.length - buttonCell.colSpans - (!!actionsCell ? actionsCell.colSpans : 0); cell.className = this.cssClasses.detailPanelCell; res.cells.push(cell); if (!!actionsCell) { res.cells.push(actionsCell); } if ( typeof this.matrix.onCreateDetailPanelRenderedRowCallback === "function" ) { this.matrix.onCreateDetailPanelRenderedRowCallback(res); } return res; } private buildVerticalRows(): Array<QuestionMatrixDropdownRenderedRow> { var columns = this.matrix.columns; var renderedRows = []; for (var i = 0; i < columns.length; i++) { var col = columns[i]; if (col.isVisible && col.hasVisibleCell) { if (col.isShowInMultipleColumns) { this.createMutlipleVerticalRows(renderedRows, col, i); } else { renderedRows.push(this.createVerticalRow(col, i)); } } } if (this.hasActionCellInRows("end")) { renderedRows.push(this.createEndVerticalActionRow()); } return renderedRows; } private createMutlipleVerticalRows( renderedRows: Array<QuestionMatrixDropdownRenderedRow>, column: MatrixDropdownColumn, index: number ) { var choices = this.getMultipleColumnChoices(column); if (!choices) return; for (var i = 0; i < choices.length; i++) { renderedRows.push(this.createVerticalRow(column, index, choices[i], i)); } } private createVerticalRow( column: MatrixDropdownColumn, index: number, choice: ItemValue = null, choiceIndex: number = -1 ): QuestionMatrixDropdownRenderedRow { var res = new QuestionMatrixDropdownRenderedRow(this.cssClasses); if (this.matrix.showHeader) { var lTitle = !!choice ? choice.locText : column.locTitle; var hCell = this.createTextCell(lTitle); hCell.column = column; if (!choice) { this.setRequriedToHeaderCell(column, hCell); } res.cells.push(hCell); } var rows = this.matrix.visibleRows; for (var i = 0; i < rows.length; i++) { var rChoice = choice; var rChoiceIndex = choiceIndex >= 0 ? choiceIndex : i; var cell = rows[i].cells[index]; var visChoices = !!choice ? cell.question.visibleChoices : undefined; if (!!visChoices && rChoiceIndex < visChoices.length) { rChoice = visChoices[rChoiceIndex]; } var rCell = this.createEditCell(cell, rChoice); rCell.item = rChoice; rCell.choiceIndex = rChoiceIndex; res.cells.push(rCell); } if (this.matrix.hasTotal) { res.cells.push( this.createEditCell(this.matrix.visibleTotalRow.cells[index]) ); } return res; } private createEndVerticalActionRow(): QuestionMatrixDropdownRenderedRow { var res = new QuestionMatrixDropdownRenderedRow(this.cssClasses); if (this.matrix.showHeader) { res.cells.push(this.createEmptyCell()); } var rows = this.matrix.visibleRows; for (var i = 0; i < rows.length; i++) { res.cells.push(this.getRowActionsCell(i, "end")); } if (this.matrix.hasTotal) { res.cells.push(this.createEmptyCell()); } return res; } private createMutlipleEditCells( rRow: QuestionMatrixDropdownRenderedRow, cell: MatrixDropdownCell, isFooter: boolean = false ) { var choices = isFooter ? this.getMultipleColumnChoices(cell.column) : cell.question.visibleChoices; if (!choices) return; for (var i = 0; i < choices.length; i++) { var rCell = this.createEditCell(cell, !isFooter ? choices[i] : undefined); if (!isFooter) { //rCell.item = choices[i]; rCell.choiceIndex = i; } rRow.cells.push(rCell); } } private createEditCell( cell: MatrixDropdownCell, choiceItem: any = undefined ): QuestionMatrixDropdownRenderedCell { var res = new QuestionMatrixDropdownRenderedCell(); res.cell = cell; res.row = cell.row; res.question = cell.question; res.matrix = this.matrix; res.item = choiceItem; res.className = res.calculateFinalClassName(this.cssClasses); //res.css = res.calcCss(this.cssClasses.cell); // var questionCss = cell.question.cssClasses; // var className = ""; // if (!!questionCss) { // className = ""; // if (!!questionCss.itemValue) { // className += " " + questionCss.itemValue; // } // if (!!questionCss.asCell) { // if (!!className) className += ""; // className += questionCss.asCell; // } // } // if (!className && !!this.cssClasses.cell) { // className = this.cssClasses.cell; // } //res.className = className; return res; } private createMutlipleColumnsFooter( rRow: QuestionMatrixDropdownRenderedRow, cell: MatrixDropdownCell ) { this.createMutlipleEditCells(rRow, cell, true); } private createMutlipleColumnsHeader(column: MatrixDropdownColumn) { var choices = this.getMultipleColumnChoices(column); if (!choices) return; for (var i = 0; i < choices.length; i++) { var cell = this.createTextCell(choices[i].locText); this.setHeaderCell(column, cell); this.headerRow.cells.push(cell); } } private getMultipleColumnChoices(column: MatrixDropdownColumn): any { var choices = column.templateQuestion.choices; if (!!choices && Array.isArray(choices) && choices.length == 0) return this.matrix.choices; choices = column.templateQuestion.visibleChoices; if (!choices || !Array.isArray(choices)) return null; return choices; } private createHeaderCell( column: MatrixDropdownColumn ): QuestionMatrixDropdownRenderedCell { var cell = this.createTextCell(!!column ? column.locTitle : null); cell.column = column; this.setHeaderCell(column, cell); if (this.cssClasses.headerCell) { cell.className = this.cssClasses.headerCell; } return cell; } private setHeaderCell( column: MatrixDropdownColumn, cell: QuestionMatrixDropdownRenderedCell ) { this.setHeaderCellWidth(column, cell); this.setRequriedToHeaderCell(column, cell); } private setHeaderCellWidth( column: MatrixDropdownColumn, cell: QuestionMatrixDropdownRenderedCell ) { cell.minWidth = column != null ? this.matrix.getColumnWidth(column) : ""; cell.width = column != null ? column.width : this.matrix.getRowTitleWidth(); } private setRequriedToHeaderCell( column: MatrixDropdownColumn, cell: QuestionMatrixDropdownRenderedCell ) { if (!!column && column.isRequired && this.matrix.survey) { cell.requiredText = this.matrix.survey.requiredText; } } private createRemoveRowCell( row: MatrixDropdownRowModelBase ): QuestionMatrixDropdownRenderedCell { var res = new QuestionMatrixDropdownRenderedCell(); res.row = row; res.isRemoveRow = this.canRemoveRow(row); if (!!this.cssClasses.cell) { res.className = this.cssClasses.cell; } return res; } private createTextCell( locTitle: LocalizableString ): QuestionMatrixDropdownRenderedCell { var cell = new QuestionMatrixDropdownRenderedCell(); cell.locTitle = locTitle; if (!!this.cssClasses.cell) { cell.className = this.cssClasses.cell; } return cell; } private createEmptyCell(): QuestionMatrixDropdownRenderedCell { const res = this.createTextCell(null); res.isEmpty = true; return res; } }
the_stack
import IdentitiesInterfaces = require("../interfaces/IdentitiesInterfaces"); import VSSInterfaces = require("../interfaces/common/VSSInterfaces"); export declare enum ConnectedServiceKind { /** * Custom or unknown service */ Custom = 0, /** * Azure Subscription */ AzureSubscription = 1, /** * Chef Connection */ Chef = 2, /** * Generic Connection */ Generic = 3, } export interface IdentityData { identityIds?: string[]; } export interface Process extends ProcessReference { _links?: any; description?: string; id?: string; isDefault?: boolean; type?: ProcessType; } export interface ProcessReference { name?: string; url?: string; } export declare enum ProcessType { System = 0, Custom = 1, Inherited = 2, } export declare enum ProjectChangeType { Modified = 0, Deleted = 1, Added = 2, } /** * Contains information of the project */ export interface ProjectInfo { abbreviation?: string; description?: string; id?: string; lastUpdateTime?: Date; name?: string; properties?: ProjectProperty[]; /** * Current revision of the project */ revision?: number; state?: any; uri?: string; version?: number; visibility?: ProjectVisibility; } export interface ProjectMessage { project?: ProjectInfo; projectChangeType?: ProjectChangeType; shouldInvalidateSystemStore?: boolean; } export interface ProjectProperty { name?: string; value?: any; } export declare enum ProjectVisibility { Unchanged = -1, Private = 0, Organization = 1, Public = 2, SystemPrivate = 3, } export interface Proxy { authorization?: ProxyAuthorization; /** * This is a description string */ description?: string; /** * The friendly name of the server */ friendlyName?: string; globalDefault?: boolean; /** * This is a string representation of the site that the proxy server is located in (e.g. "NA-WA-RED") */ site?: string; siteDefault?: boolean; /** * The URL of the proxy server */ url?: string; } export interface ProxyAuthorization { /** * Gets or sets the endpoint used to obtain access tokens from the configured token service. */ authorizationUrl?: string; /** * Gets or sets the client identifier for this proxy. */ clientId?: string; /** * Gets or sets the user identity to authorize for on-prem. */ identity?: IdentitiesInterfaces.IdentityDescriptor; /** * Gets or sets the public key used to verify the identity of this proxy. Only specify on hosted. */ publicKey?: VSSInterfaces.PublicKey; } export declare enum SourceControlTypes { Tfvc = 1, Git = 2, } /** * The Team Context for an operation. */ export interface TeamContext { /** * The team project Id or name. Ignored if ProjectId is set. */ project?: string; /** * The Team Project ID. Required if Project is not set. */ projectId?: string; /** * The Team Id or name. Ignored if TeamId is set. */ team?: string; /** * The Team Id */ teamId?: string; } /** * Represents a Team Project object. */ export interface TeamProject extends TeamProjectReference { /** * The links to other objects related to this object. */ _links?: any; /** * Set of capabilities this project has (such as process template & version control). */ capabilities?: { [key: string]: { [key: string]: string; }; }; /** * The shallow ref to the default team. */ defaultTeam?: WebApiTeamRef; } /** * Data contract for a TeamProjectCollection. */ export interface TeamProjectCollection extends TeamProjectCollectionReference { /** * The links to other objects related to this object. */ _links?: any; /** * Project collection description. */ description?: string; /** * True if collection supports inherited process customization model. */ enableInheritedProcessCustomization?: boolean; /** * Project collection state. */ state?: string; } /** * Reference object for a TeamProjectCollection. */ export interface TeamProjectCollectionReference { /** * Collection Id. */ id?: string; /** * Collection Name. */ name?: string; /** * Collection REST Url. */ url?: string; } /** * Represents a shallow reference to a TeamProject. */ export interface TeamProjectReference { /** * Project abbreviation. */ abbreviation?: string; /** * The project's description (if any). */ description?: string; /** * Project identifier. */ id?: string; /** * Project name. */ name?: string; /** * Project revision. */ revision?: number; /** * Project state. */ state?: any; /** * Url to the full version of the object. */ url?: string; /** * Project visibility. */ visibility?: ProjectVisibility; } /** * A data transfer object that stores the metadata associated with the creation of temporary data. */ export interface TemporaryDataCreatedDTO extends TemporaryDataDTO { expirationDate?: Date; id?: string; url?: string; } /** * A data transfer object that stores the metadata associated with the temporary data. */ export interface TemporaryDataDTO { expirationSeconds?: number; origin?: string; value?: any; } export interface WebApiConnectedService extends WebApiConnectedServiceRef { /** * The user who did the OAuth authentication to created this service */ authenticatedBy?: VSSInterfaces.IdentityRef; /** * Extra description on the service. */ description?: string; /** * Friendly Name of service connection */ friendlyName?: string; /** * Id/Name of the connection service. For Ex: Subscription Id for Azure Connection */ id?: string; /** * The kind of service. */ kind?: string; /** * The project associated with this service */ project?: TeamProjectReference; /** * Optional uri to connect directly to the service such as https://windows.azure.com */ serviceUri?: string; } export interface WebApiConnectedServiceDetails extends WebApiConnectedServiceRef { /** * Meta data for service connection */ connectedServiceMetaData?: WebApiConnectedService; /** * Credential info */ credentialsXml?: string; /** * Optional uri to connect directly to the service such as https://windows.azure.com */ endPoint?: string; } export interface WebApiConnectedServiceRef { id?: string; url?: string; } /** * The representation of data needed to create a tag definition which is sent across the wire. */ export interface WebApiCreateTagRequestData { /** * Name of the tag definition that will be created. */ name: string; } export interface WebApiProject extends TeamProjectReference { /** * Set of capabilities this project has */ capabilities?: { [key: string]: { [key: string]: string; }; }; /** * Reference to collection which contains this project */ collection?: WebApiProjectCollectionRef; /** * Default team for this project */ defaultTeam?: WebApiTeamRef; } export interface WebApiProjectCollection extends WebApiProjectCollectionRef { /** * Project collection description */ description?: string; /** * Project collection state */ state?: string; } export interface WebApiProjectCollectionRef { /** * Collection Tfs Url (Host Url) */ collectionUrl?: string; /** * Collection Guid */ id?: string; /** * Collection Name */ name?: string; /** * Collection REST Url */ url?: string; } /** * The representation of a tag definition which is sent across the wire. */ export interface WebApiTagDefinition { /** * Whether or not the tag definition is active. */ active?: boolean; /** * ID of the tag definition. */ id?: string; /** * The name of the tag definition. */ name?: string; /** * Resource URL for the Tag Definition. */ url?: string; } export interface WebApiTeam extends WebApiTeamRef { /** * Team description */ description?: string; /** * Identity REST API Url to this team */ identityUrl?: string; projectId?: string; projectName?: string; } export interface WebApiTeamRef { /** * Team (Identity) Guid. A Team Foundation ID. */ id?: string; /** * Team name */ name?: string; /** * Team REST API Url */ url?: string; } export declare var TypeInfo: { ConnectedServiceKind: { enumValues: { "custom": number; "azureSubscription": number; "chef": number; "generic": number; }; }; Process: any; ProcessType: { enumValues: { "system": number; "custom": number; "inherited": number; }; }; ProjectChangeType: { enumValues: { "modified": number; "deleted": number; "added": number; }; }; ProjectInfo: any; ProjectMessage: any; ProjectVisibility: { enumValues: { "private": number; "organization": number; "public": number; }; }; SourceControlTypes: { enumValues: { "tfvc": number; "git": number; }; }; TeamProject: any; TeamProjectReference: any; TemporaryDataCreatedDTO: any; WebApiConnectedService: any; WebApiConnectedServiceDetails: any; WebApiProject: any; };
the_stack
import { ComponentFixture, TestBed, tick, fakeAsync } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Component, DebugElement, ViewChild } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { SohoMenuButtonComponent, SohoMenuButtonModule, } from './'; import { SohoIconModule } from '../icon'; describe('Soho Menu Button Unit Tests', () => { let comp: SohoMenuButtonComponent; let fixture: ComponentFixture<SohoMenuButtonComponent>; let de: DebugElement; let el: HTMLElement; beforeEach(() => { TestBed.configureTestingModule({ declarations: [SohoMenuButtonComponent], imports: [SohoIconModule] }); fixture = TestBed.createComponent(SohoMenuButtonComponent); comp = fixture.componentInstance; fixture.detectChanges(); de = fixture.debugElement; el = de.nativeElement; }); it('Check Content', () => { expect(el.nodeName).toEqual('DIV'); expect(el.classList).toContain('btn-menu'); }); it('check showArrow', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.showArrow = false; expect((comp as any).options.showArrow).toBeFalsy(); expect((comp as any).menuButton.settings.showArrow).toBeFalsy(); expect(spy).toHaveBeenCalled(); }); it('check showArrow sets option to true', () => { comp.showArrow = true; expect((comp as any).options.showArrow).toBeTruthy(); expect((comp as any).menuButton.settings.showArrow).toBeTruthy(); }); it('check showArrow sets option to true, when no menuButton set', () => { (comp as any).menuButton = undefined; comp.showArrow = true; expect((comp as any).options.showArrow).toBeTruthy(); }); it('check hideMenuArrow', () => { // const spy = spyOn((comp as any).ref, 'markForCheck'); comp.hideMenuArrow = false; expect((comp as any).buttonOptions.hideMenuArrow).toBeFalsy(); expect((comp as any).button.settings.hideMenuArrow).toBeFalsy(); // expect(spy).toHaveBeenCalled(); }); it('check hideMenuArrow sets option to true', () => { // const spy = spyOn((comp as any).ref, 'markForCheck'); comp.hideMenuArrow = true; expect((comp as any).buttonOptions.hideMenuArrow).toBeTruthy(); expect((comp as any).button.settings.hideMenuArrow).toBeTruthy(); // expect(spy).toHaveBeenCalled(); }); it('check hideMenuArrow sets option to true, when no menuButton set', () => { // const spy = spyOn((comp as any).ref, 'markForCheck'); (comp as any).menuButton = undefined; comp.hideMenuArrow = true; expect((comp as any).buttonOptions.hideMenuArrow).toBeTruthy(); // expect(spy).toHaveBeenCalledTimes(0); }); it('check autoFocus sets options to false', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.autoFocus = false; fixture.detectChanges(); expect((comp as any).options.autoFocus).toBeFalsy(); expect((comp as any).menuButton.settings.autoFocus).toBeFalsy(); expect(spy).toHaveBeenCalled(); }); it('check autoFocus sets options to false, before menuButton initialised.', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); (comp as any).menuButton = undefined; comp.autoFocus = false; fixture.detectChanges(); expect((comp as any).options.autoFocus).toBeFalsy(); expect(spy).toHaveBeenCalledTimes(0); }); it('check autoFocus sets option to true', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.autoFocus = true; fixture.detectChanges(); expect((comp as any).options.autoFocus).toBeTruthy(); expect((comp as any).menuButton.settings.autoFocus).toBeTruthy(); expect(spy).toHaveBeenCalled(); }); it('check mouseFocus sets options to false', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.mouseFocus = false; fixture.detectChanges(); expect((comp as any).options.mouseFocus).toBeFalsy(); expect((comp as any).menuButton.settings.mouseFocus).toBeFalsy(); expect(spy).toHaveBeenCalled(); }); it('check mouseFocus sets options to false, when menuButton not set', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); (comp as any).menuButton = undefined; comp.mouseFocus = false; fixture.detectChanges(); expect((comp as any).options.mouseFocus).toBeFalsy(); expect(spy).toHaveBeenCalledTimes(0); }); it('check mouseFocus sets option to true', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.mouseFocus = true; fixture.detectChanges(); expect((comp as any).options.mouseFocus).toBeTruthy(); expect((comp as any).menuButton.settings.mouseFocus).toBeTruthy(); expect(spy).toHaveBeenCalled(); }); it('check returnFocus sets options to false', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.returnFocus = false; expect((comp as any).options.returnFocus).toBeFalsy(); expect((comp as any).menuButton.settings.returnFocus).toBeFalsy(); expect(spy).toHaveBeenCalled(); }); it('check returnFocus sets options to false, without menuButton.', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); (comp as any).menuButton = undefined; comp.returnFocus = false; expect((comp as any).options.returnFocus).toBeFalsy(); expect(spy).toHaveBeenCalledTimes(0); }); it('check returnFocus sets option to true', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.returnFocus = true; expect((comp as any).options.returnFocus).toBeTruthy(); expect((comp as any).menuButton.settings.returnFocus).toBeTruthy(); expect(spy).toHaveBeenCalled(); }); it('check returnFocus sets option to true, without menuButton', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); (comp as any).menuButton = undefined; comp.returnFocus = true; expect((comp as any).options.returnFocus).toBeTruthy(); expect(spy).toHaveBeenCalledTimes(0); }); it('check trigger sets option', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.trigger = 'click'; expect((comp as any).options.trigger).toEqual('click'); expect((comp as any).menuButton.settings.trigger).toEqual('click'); expect(spy).toHaveBeenCalled(); }); it('check trigger sets option', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); (comp as any).menuButton = undefined; comp.trigger = 'click'; expect((comp as any).options.trigger).toEqual('click'); expect(spy).toHaveBeenCalledTimes(0); }); it('check menu sets options', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.menu = 'mymenu'; expect((comp as any).options.menu).toEqual('mymenu'); expect((comp as any).menuButton.settings.menu).toEqual('mymenu'); expect(spy).toHaveBeenCalled(); }); it('check menu sets options, without menuButton', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); (comp as any).menuButton = undefined; comp.menu = 'mymenu'; expect((comp as any).options.menu).toEqual('mymenu'); expect(spy).toHaveBeenCalledTimes(0); }); it('check attachToBody option', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.attachToBody = true; expect((comp as any).options.attachToBody).toEqual(true); expect((comp as any).menuButton.settings.attachToBody).toEqual(true); expect(spy).toHaveBeenCalled(); }); it('check ajaxBeforeOpenFunction sets options', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); comp.ajaxBeforeOpenFunction = () => { }; expect((comp as any).options.ajaxBeforeOpenFunction).not.toBeNull('mymenu'); expect((comp as any).menuButton.settings.ajaxBeforeOpenFunction).not.toBeNull('mymenu'); expect(spy).toHaveBeenCalledTimes(0); }); it('check ajaxBeforeOpenFunction sets options', () => { const spy = spyOn((comp as any).ref, 'markForCheck'); (comp as any).menuButton = undefined; comp.ajaxBeforeOpenFunction = () => { }; expect((comp as any).options.ajaxBeforeOpenFunction).not.toBeNull('mymenu'); expect(spy).toHaveBeenCalledTimes(0); }); it('check fires `selected`', () => { const spy = spyOn((comp as any), 'onSelected').and.callThrough(); const selectionResult: Array<any> = []; // list of selected anchors. // Emulate the event being triggered (args?) (comp as any).jQueryElement.trigger('selected', selectionResult); // Check it was caled expect(spy).toHaveBeenCalledTimes(1); }); it('check close', () => { const spy = spyOn((comp as any).menuButton, 'close').and.callFake(() => { }); comp.close(); expect(spy).toHaveBeenCalledTimes(1); }); it('check updated', () => { const spy = spyOn((comp as any).menuButton, 'updated').and.callThrough(); comp.updated(); expect(spy).toHaveBeenCalledTimes(1); }); it('check teardown', () => { const spy = spyOn((comp as any).menuButton, 'teardown').and.callThrough(); comp.teardown(); expect(spy).toHaveBeenCalledTimes(1); }); it('check beforeopen is called when the menu is opened.', () => { const spy = spyOn((comp as any), 'onBeforeOpen').and.callThrough(); // Emulate the event being triggered (args?) (comp as any).jQueryElement.trigger('beforeopen'); // Check it was caled expect(spy).toHaveBeenCalledTimes(1); }); it('check close', () => { const spy = spyOn((comp as any), 'onClose').and.callThrough(); // Emulate the event being triggered (args?) (comp as any).jQueryElement.trigger('close', el); // Check it was caled expect(spy).toHaveBeenCalledTimes(1); }); it('check open', () => { const spy = spyOn((comp as any), 'onOpen').and.callThrough(); // Emulate the event being triggered (args?) (comp as any).jQueryElement.trigger('open'); // Check it was caled expect(spy).toHaveBeenCalledTimes(1); }); }); @Component({ template: `<button soho-menu-button icon="user" menu="action-popupmenu" title="Charts"> <span title="foo">Hello</span> </button> <ul soho-popupmenu id="action-popupmenu"> <li><a soho-popupmenu-label>Admin</a></li> <li soho-popupmenu-separator></li> <li soho-popupmenu-item><a id="signout">Sign out</a></li> </ul>` }) export class TestSohoMenuButtonComponent { @ViewChild(SohoMenuButtonComponent) menuButton?: any; } describe('Soho Menu Button Render', () => { let menuButton: SohoMenuButtonComponent; let component: TestSohoMenuButtonComponent; let fixture: ComponentFixture<TestSohoMenuButtonComponent>; let de: DebugElement; let el: HTMLElement; beforeEach(() => { TestBed.configureTestingModule({ declarations: [TestSohoMenuButtonComponent], imports: [FormsModule, SohoMenuButtonModule, SohoIconModule] }); fixture = TestBed.createComponent(TestSohoMenuButtonComponent); component = fixture.componentInstance; menuButton = component.menuButton; de = fixture.debugElement; el = de.query(By.css('a[soho-popupmenu-label]')).nativeElement; fixture.detectChanges(); }); it('Check Item HTML content', () => { fixture.detectChanges(); expect(el.nodeName).toEqual('A'); }); // Issue with change detection // todo seems to fail intermittently on the last expect statement: expect(icon).toBeNull() - Phillip 6/4/19 // todo: this needs to be fixed in button.js so that updated() will tear down and reinit the component. xit('Check Item HTML content', fakeAsync(() => { fixture.detectChanges(); let icon = de.query(By.css('svg.icon-dropdown.icon')); expect(icon.nativeElement).toBeDefined(); menuButton.hideMenuArrow = true; fixture.detectChanges(); tick(); tick(); fixture.detectChanges(); icon = de.query(By.css('svg.icon-dropdown.icon')); expect(icon.nativeElement).toBeNull(); })); });
the_stack
import React from 'react'; import PropTypes from 'prop-types'; import Component from '../../react-class'; import { Flex, Item } from '../../Flex'; import InlineBlock from './InlineBlock'; import assign from '../../../common/assign'; import join from '../../../common/join'; import assignDefined from './assignDefined'; import toMoment from './toMoment'; import MonthDecadeView from './MonthDecadeView'; const ARROWS = { prev: ( <svg width="6" height="10" viewBox="0 0 6 10"> <path fillRule="evenodd" d="M2.197 5l2.865-2.866c.311-.31.311-.814 0-1.125-.31-.31-.814-.31-1.125 0L.477 4.47c-.293.294-.293.769 0 1.061l3.46 3.46c.311.311.815.311 1.125 0 .311-.31.311-.814 0-1.124L2.197 5z" /> </svg> ), next: ( <svg width="6" height="10" viewBox="0 0 6 10"> <path fillRule="evenodd" d="M3.803 5L.938 7.866c-.311.31-.311.814 0 1.125.31.31.814.31 1.125 0l3.46-3.46c.293-.294.293-.769 0-1.061l-3.46-3.46c-.311-.311-.815-.311-1.126 0-.31.31-.31.814 0 1.124L3.803 5z" /> </svg> ), right: ( <svg width="12" height="10" viewBox="0 0 12 10"> <g fillRule="evenodd"> <path d="M3.803 4.5L.938 7.366c-.311.31-.311.814 0 1.125.31.31.814.31 1.125 0l3.46-3.46c.293-.294.293-.769 0-1.061L2.063.51C1.751.198 1.247.198.936.51c-.31.31-.31.814 0 1.124L3.803 4.5zM9.803 4.5L6.937 7.366c-.31.31-.31.814 0 1.125.311.31.815.31 1.125 0l3.461-3.46c.293-.294.293-.769 0-1.061L8.063.51c-.311-.311-.815-.311-1.126 0-.31.31-.31.814 0 1.124L9.803 4.5z" transform="translate(0 .5)" /> </g> </svg> ), left: ( <svg width="12" height="10" viewBox="0 0 12 10"> <g fillRule="evenodd"> <path d="M3.803 4.5L.938 7.366c-.311.31-.311.814 0 1.125.31.31.814.31 1.125 0l3.46-3.46c.293-.294.293-.769 0-1.061L2.063.51C1.751.198 1.247.198.936.51c-.31.31-.31.814 0 1.124L3.803 4.5zM9.803 4.5L6.937 7.366c-.31.31-.31.814 0 1.125.311.31.815.31 1.125 0l3.461-3.46c.293-.294.293-.769 0-1.061L8.063.51c-.311-.311-.815-.311-1.126 0-.31.31-.31.814 0 1.124L9.803 4.5z" transform="rotate(180 6 4.75)" /> </g> </svg> ), }; export default class NavBar extends Component { constructor(props) { super(props); this.state = { viewDate: props.defaultViewDate, }; } prepareViewDate(props) { return props.viewDate === undefined ? this.state.viewDate : props.viewDate; } render() { const props = (this.p = assign({}, this.props)); const { rootClassName, index } = props; const viewMoment = (props.viewMoment = props.viewMoment || this.toMoment(this.prepareViewDate(props))); props.monthDecadeViewEnabled = props.expandedMonthDecadeView || props.enableMonthDecadeView; const secondary = props.secondary; const className = join( props.className, rootClassName, `${rootClassName}--theme-${props.theme}`, `${rootClassName}--with-month-decade-view` ); const monthDecadeView = props.monthDecadeViewEnabled ? this.renderMonthDecadeView() : null; const flexProps = assign({}, props); delete flexProps.rootClassName; delete flexProps.arrows; delete flexProps.doubleArrows; delete flexProps.date; delete flexProps.enableMonthDecadeView; delete flexProps.monthDecadeViewEnabled; delete flexProps.isDatePickerNavBar; delete flexProps.minDate; delete flexProps.maxDate; delete flexProps.mainNavBar; delete flexProps.multiView; delete flexProps.navDateFormat; delete flexProps.onNavClick; delete flexProps.onUpdate; delete flexProps.onViewDateChange; delete flexProps.renderNavNext; delete flexProps.renderNavPrev; delete flexProps.secondary; delete flexProps.theme; delete flexProps.viewDate; delete flexProps.viewMoment; delete flexProps.showClock; delete flexProps.enableMonthDecadeViewAnimation; delete flexProps.showMonthDecadeViewAnimation; delete flexProps.cancelButtonText; delete flexProps.clearButtonText; delete flexProps.okButtonText; if (typeof props.cleanup == 'function') { props.cleanup(flexProps); } return ( <Flex key="navBar" inline row {...flexProps} className={className}> {secondary && this.renderNav(-2, viewMoment, 'left')} {this.renderNav(-1, viewMoment, 'prev')} <Item key="month_year" className={join( `${rootClassName}-date`, props.monthDecadeViewEnabled ? '' : `${rootClassName}-date-disabled` )} style={{ textAlign: 'center' }} onMouseDown={ props.monthDecadeViewEnabled ? this.toggleMonthDecadeView : null } > {this.renderNavDate(viewMoment)} </Item> {this.renderNav(1, viewMoment, 'next')} {secondary && this.renderNav(2, viewMoment, 'right')} {monthDecadeView} </Flex> ); } renderMonthDecadeView() { if (!this.state.monthDecadeView) { return null; } const { viewMoment, theme, locale, minDate, maxDate, rootClassName, size, okButtonText, cancelButtonText, showClock, enableMonthDecadeViewAnimation, showMonthDecadeViewAnimation, } = this.p; const className = join( `${rootClassName}-month-decade-view`, (size <= 1 || size === undefined) && `${rootClassName}-month-decade-view-month`, showClock && `${rootClassName}-month-decade-view-calendar` ); const modalClassName = join( `${rootClassName}-month-decade-view-modal`, enableMonthDecadeViewAnimation && `${rootClassName}-month-decade-view-show-animation` ); const modalWrapperClassName = size || size === undefined ? modalClassName : null; const monthDecadeViewProps = assignDefined( { defaultViewDate: viewMoment, defaultDate: viewMoment, ref: view => { this.monthDecadeView = view; }, focusDecadeView: false, className, theme, okButtonText, cancelButtonText, onOkClick: this.onMonthDecadeViewOk, onCancelClick: this.onMonthDecadeViewCancel, }, { minDate, maxDate, locale, } ); if (this.props.renderMonthDecadeView) { return this.props.renderMonthDecadeView(monthDecadeViewProps); } return ( <div style={{ animationDuration: `${showMonthDecadeViewAnimation}ms` }} className={modalWrapperClassName} > <MonthDecadeView {...monthDecadeViewProps} /> </div> ); } toggleMonthDecadeView(event) { if (this.isMonthDecadeViewVisible()) { this.hideMonthDecadeView(event); } else { this.showMonthDecadeView(event); } } getMonthDecadeViewView() { return this.monthDecadeView; } isMonthDecadeViewVisible() { return !!this.monthDecadeView; } onMonthDecadeViewOk(dateString, { dateMoment, timestamp }) { this.hideMonthDecadeView(); this.onViewDateChange({ dateMoment, timestamp }); } onMonthDecadeViewCancel() { this.hideMonthDecadeView(); } showMonthDecadeView(event) { event.preventDefault(); this.setState({ monthDecadeView: true, }); if (this.props.onShowMonthDecadeView) { this.props.onShowMonthDecadeView(); } } hideMonthDecadeView(event) { if (event && event.preventDefault) { event.preventDefault(); } this.setState({ monthDecadeView: false, }); if (this.props.onHideMonthDecadeView) { this.props.onHideMonthDecadeView(); } } toMoment(value, props) { props = props || this.props; return toMoment(value, { locale: props.locale, dateFormat: props.dateFormat, }); } renderNav(dir, viewMoment, name) { const props = this.p; let disabled = dir < 0 ? props.prevDisabled : props.nextDisabled; const secondary = Math.abs(dir) == 2; if (dir < 0 && props.minDate) { const gotoMoment = this.getGotoMoment(dir, viewMoment).endOf('month'); if (gotoMoment.isBefore(this.toMoment(props.minDate))) { disabled = true; } } if (dir > 0 && props.maxDate) { const gotoMoment = this.getGotoMoment(dir, viewMoment).startOf('month'); if (gotoMoment.isAfter(this.toMoment(props.maxDate))) { disabled = true; } } if (this.state.monthDecadeView) { disabled = true; } const { rootClassName } = props; const className = join( `${rootClassName}-arrow`, `${rootClassName}-arrow--${name}`, secondary && `${rootClassName}-secondary-arrow`, disabled && `${rootClassName}-arrow--disabled` ); const arrowClass = `${rootClassName}-arrows-pos`; const arrowDivClass = `${rootClassName}-arrows-div`; const arrow = props.arrows[dir] || props.arrows[name] || ARROWS[name]; let children; const dirArrow = props.arrows[dir]; if (dirArrow) { children = dirArrow; } else { const doubleArrows = dir < -1 ? arrow : dir > 1 ? arrow : null; children = dir < 0 ? ( <div className={arrowDivClass}> {secondary ? ( <div className={arrowClass}>{doubleArrows}</div> ) : ( <div className={arrowClass}>{arrow}</div> )} </div> ) : ( <div className={arrowDivClass}> {secondary ? ( <div className={arrowClass}>{doubleArrows}</div> ) : ( <div className={arrowClass}>{arrow}</div> )} </div> ); } const navProps = { dir, name, disabled, onClick: !disabled ? this.onNavClick.bind(this, dir, viewMoment) : null, className, children, }; if (props.renderNav) { return props.renderNav(navProps); } if (dir < 0 && props.renderNavPrev) { return props.renderNavPrev(navProps); } if (dir > 0 && props.renderNavNext) { return props.renderNavNext(navProps); } return <InlineBlock key={name} {...navProps} disabled={null} name={null} />; } getGotoMoment(dir, viewMoment) { viewMoment = viewMoment || this.p.viewMoment; const sign = dir < 0 ? -1 : 1; const abs = Math.abs(dir); const mom = this.toMoment(viewMoment); mom.add(sign, abs == 1 ? 'month' : 'year'); return mom; } onNavClick(dir, viewMoment, event) { const props = this.props; let dateMoment = this.toMoment(viewMoment); if (props.onUpdate) { dateMoment = props.onUpdate(dateMoment, dir); } else { const sign = dir < 0 ? -1 : 1; const abs = Math.abs(dir); dateMoment.add(sign, abs == 1 ? 'month' : 'year'); } const timestamp = +dateMoment; props.onNavClick(dir, viewMoment, event); const disabled = dir < 0 ? props.prevDisabled : props.nextDisabled; if (disabled) { return; } this.onViewDateChange({ dateMoment, timestamp, }); } renderNavDate(viewMoment) { const props = this.props; const text = viewMoment.format(props.navDateFormat); if (props.renderNavDate) { return props.renderNavDate(viewMoment, text); } return text; } onViewDateChange({ dateMoment, timestamp }) { if (this.props.viewDate === undefined) { this.setState({ viewDate: timestamp, }); } if (this.props.onViewDateChange) { const dateString = dateMoment.format(this.props.dateFormat); this.props.onViewDateChange(dateString, { dateString, dateMoment, timestamp, }); } } } NavBar.defaultProps = { rootClassName: 'inovua-react-toolkit-calendar__nav-bar', arrows: {}, doubleArrows: {}, theme: 'default', isDatePickerNavBar: true, navDateFormat: 'MMM YYYY', enableMonthDecadeView: true, onNavClick: (dir, viewMoment) => {}, onViewDateChange: () => {}, }; NavBar.propTypes = { rootClassName: PropTypes.string, secondary: PropTypes.bool, showClock: PropTypes.bool, enableMonthDecadeViewAnimation: PropTypes.bool, showMonthDecadeViewAnimation: PropTypes.number, renderNav: PropTypes.func, renderNavPrev: PropTypes.func, renderNavNext: PropTypes.func, arrows: PropTypes.object, doubleArrows: PropTypes.object, navDateFormat: PropTypes.string, onUpdate: PropTypes.func, onNavClick: PropTypes.func, onViewDateChange: PropTypes.func, onClick: PropTypes.any, };
the_stack